a6f5957e4693d21fc49cbc2ea7c2fe47b7e8d5bf
[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::{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::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::ChainHash;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex, RwLock};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
65
66 #[test]
67 fn test_insane_channel_opens() {
68         // Stand up a network of 2 nodes
69         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
70         let mut cfg = UserConfig::default();
71         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
72         let chanmon_cfgs = create_chanmon_cfgs(2);
73         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
74         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
75         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
76
77         // Instantiate channel parameters where we push the maximum msats given our
78         // funding satoshis
79         let channel_value_sat = 31337; // same as funding satoshis
80         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
81         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
82
83         // Have node0 initiate a channel to node1 with aforementioned parameters
84         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
85
86         // Extract the channel open message from node0 to node1
87         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
88
89         // Test helper that asserts we get the correct error string given a mutator
90         // that supposedly makes the channel open message insane
91         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
92                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
93                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
94                 assert_eq!(msg_events.len(), 1);
95                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
96                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
97                         match action {
98                                 &ErrorAction::SendErrorMessage { .. } => {
99                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
100                                 },
101                                 _ => panic!("unexpected event!"),
102                         }
103                 } else { assert!(false); }
104         };
105
106         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
107
108         // Test all mutations that would make the channel open message insane
109         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 });
110         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 });
111
112         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
113
114         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 });
115
116         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
117
118         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 });
119
120         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 });
121
122         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
123
124         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 }
126
127 #[test]
128 fn test_funding_exceeds_no_wumbo_limit() {
129         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
130         // them.
131         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
132         let chanmon_cfgs = create_chanmon_cfgs(2);
133         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
134         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
135         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
136         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
137
138         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
139                 Err(APIError::APIMisuseError { err }) => {
140                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
141                 },
142                 _ => panic!()
143         }
144 }
145
146 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
147         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
148         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
149         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
150         // in normal testing, we test it explicitly here.
151         let chanmon_cfgs = create_chanmon_cfgs(2);
152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
155         let default_config = UserConfig::default();
156
157         // Have node0 initiate a channel to node1 with aforementioned parameters
158         let mut push_amt = 100_000_000;
159         let feerate_per_kw = 253;
160         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
161         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
162         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
163
164         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();
165         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
166         if !send_from_initiator {
167                 open_channel_message.channel_reserve_satoshis = 0;
168                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169         }
170         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
171
172         // Extract the channel accept message from node1 to node0
173         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
174         if send_from_initiator {
175                 accept_channel_message.channel_reserve_satoshis = 0;
176                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
177         }
178         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
179         {
180                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
181                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
182                 let mut sender_node_per_peer_lock;
183                 let mut sender_node_peer_state_lock;
184
185                 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
186                 match channel_phase {
187                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
188                                 let chan_context = channel_phase.context_mut();
189                                 chan_context.holder_selected_channel_reserve_satoshis = 0;
190                                 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
191                         },
192                         ChannelPhase::Funded(_) => assert!(false),
193                 }
194         }
195
196         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
197         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
198         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
199
200         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
201         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
202         if send_from_initiator {
203                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
204                         // Note that for outbound channels we have to consider the commitment tx fee and the
205                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
206                         // well as an additional HTLC.
207                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
208         } else {
209                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
210         }
211 }
212
213 #[test]
214 fn test_counterparty_no_reserve() {
215         do_test_counterparty_no_reserve(true);
216         do_test_counterparty_no_reserve(false);
217 }
218
219 #[test]
220 fn test_async_inbound_update_fee() {
221         let chanmon_cfgs = create_chanmon_cfgs(2);
222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
224         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
225         create_announced_chan_between_nodes(&nodes, 0, 1);
226
227         // balancing
228         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
229
230         // A                                        B
231         // update_fee                            ->
232         // send (1) commitment_signed            -.
233         //                                       <- update_add_htlc/commitment_signed
234         // send (2) RAA (awaiting remote revoke) -.
235         // (1) commitment_signed is delivered    ->
236         //                                       .- send (3) RAA (awaiting remote revoke)
237         // (2) RAA is delivered                  ->
238         //                                       .- send (4) commitment_signed
239         //                                       <- (3) RAA is delivered
240         // send (5) commitment_signed            -.
241         //                                       <- (4) commitment_signed is delivered
242         // send (6) RAA                          -.
243         // (5) commitment_signed is delivered    ->
244         //                                       <- RAA
245         // (6) RAA is delivered                  ->
246
247         // First nodes[0] generates an update_fee
248         {
249                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
250                 *feerate_lock += 20;
251         }
252         nodes[0].node.timer_tick_occurred();
253         check_added_monitors!(nodes[0], 1);
254
255         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
256         assert_eq!(events_0.len(), 1);
257         let (update_msg, commitment_signed) = match events_0[0] { // (1)
258                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
259                         (update_fee.as_ref(), commitment_signed)
260                 },
261                 _ => panic!("Unexpected event"),
262         };
263
264         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
265
266         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
267         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
268         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
269                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
270         check_added_monitors!(nodes[1], 1);
271
272         let payment_event = {
273                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
274                 assert_eq!(events_1.len(), 1);
275                 SendEvent::from_event(events_1.remove(0))
276         };
277         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
278         assert_eq!(payment_event.msgs.len(), 1);
279
280         // ...now when the messages get delivered everyone should be happy
281         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
282         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
283         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
284         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
285         check_added_monitors!(nodes[0], 1);
286
287         // deliver(1), generate (3):
288         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
289         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
290         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
291         check_added_monitors!(nodes[1], 1);
292
293         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
294         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
295         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
296         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
298         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
299         assert!(bs_update.update_fee.is_none()); // (4)
300         check_added_monitors!(nodes[1], 1);
301
302         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
303         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
304         assert!(as_update.update_add_htlcs.is_empty()); // (5)
305         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
307         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
308         assert!(as_update.update_fee.is_none()); // (5)
309         check_added_monitors!(nodes[0], 1);
310
311         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
312         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
313         // only (6) so get_event_msg's assert(len == 1) passes
314         check_added_monitors!(nodes[0], 1);
315
316         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
317         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
318         check_added_monitors!(nodes[1], 1);
319
320         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
321         check_added_monitors!(nodes[0], 1);
322
323         let events_2 = nodes[0].node.get_and_clear_pending_events();
324         assert_eq!(events_2.len(), 1);
325         match events_2[0] {
326                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
327                 _ => panic!("Unexpected event"),
328         }
329
330         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
331         check_added_monitors!(nodes[1], 1);
332 }
333
334 #[test]
335 fn test_update_fee_unordered_raa() {
336         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
337         // crash in an earlier version of the update_fee patch)
338         let chanmon_cfgs = create_chanmon_cfgs(2);
339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
342         create_announced_chan_between_nodes(&nodes, 0, 1);
343
344         // balancing
345         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
346
347         // First nodes[0] generates an update_fee
348         {
349                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
350                 *feerate_lock += 20;
351         }
352         nodes[0].node.timer_tick_occurred();
353         check_added_monitors!(nodes[0], 1);
354
355         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
356         assert_eq!(events_0.len(), 1);
357         let update_msg = match events_0[0] { // (1)
358                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
359                         update_fee.as_ref()
360                 },
361                 _ => panic!("Unexpected event"),
362         };
363
364         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
365
366         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
367         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
368         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
369                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
370         check_added_monitors!(nodes[1], 1);
371
372         let payment_event = {
373                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
374                 assert_eq!(events_1.len(), 1);
375                 SendEvent::from_event(events_1.remove(0))
376         };
377         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
378         assert_eq!(payment_event.msgs.len(), 1);
379
380         // ...now when the messages get delivered everyone should be happy
381         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
382         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
383         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
384         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
388         check_added_monitors!(nodes[1], 1);
389
390         // We can't continue, sadly, because our (1) now has a bogus signature
391 }
392
393 #[test]
394 fn test_multi_flight_update_fee() {
395         let chanmon_cfgs = create_chanmon_cfgs(2);
396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
398         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
399         create_announced_chan_between_nodes(&nodes, 0, 1);
400
401         // A                                        B
402         // update_fee/commitment_signed          ->
403         //                                       .- send (1) RAA and (2) commitment_signed
404         // update_fee (never committed)          ->
405         // (3) update_fee                        ->
406         // We have to manually generate the above update_fee, it is allowed by the protocol but we
407         // don't track which updates correspond to which revoke_and_ack responses so we're in
408         // AwaitingRAA mode and will not generate the update_fee yet.
409         //                                       <- (1) RAA delivered
410         // (3) is generated and send (4) CS      -.
411         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
412         // know the per_commitment_point to use for it.
413         //                                       <- (2) commitment_signed delivered
414         // revoke_and_ack                        ->
415         //                                          B should send no response here
416         // (4) commitment_signed delivered       ->
417         //                                       <- RAA/commitment_signed delivered
418         // revoke_and_ack                        ->
419
420         // First nodes[0] generates an update_fee
421         let initial_feerate;
422         {
423                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
424                 initial_feerate = *feerate_lock;
425                 *feerate_lock = initial_feerate + 20;
426         }
427         nodes[0].node.timer_tick_occurred();
428         check_added_monitors!(nodes[0], 1);
429
430         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
431         assert_eq!(events_0.len(), 1);
432         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
433                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
434                         (update_fee.as_ref().unwrap(), commitment_signed)
435                 },
436                 _ => panic!("Unexpected event"),
437         };
438
439         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
440         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
441         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
442         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
443         check_added_monitors!(nodes[1], 1);
444
445         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
446         // transaction:
447         {
448                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
449                 *feerate_lock = initial_feerate + 40;
450         }
451         nodes[0].node.timer_tick_occurred();
452         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
453         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
454
455         // Create the (3) update_fee message that nodes[0] will generate before it does...
456         let mut update_msg_2 = msgs::UpdateFee {
457                 channel_id: update_msg_1.channel_id.clone(),
458                 feerate_per_kw: (initial_feerate + 30) as u32,
459         };
460
461         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
462
463         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
464         // Deliver (3)
465         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
466
467         // Deliver (1), generating (3) and (4)
468         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
469         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
470         check_added_monitors!(nodes[0], 1);
471         assert!(as_second_update.update_add_htlcs.is_empty());
472         assert!(as_second_update.update_fulfill_htlcs.is_empty());
473         assert!(as_second_update.update_fail_htlcs.is_empty());
474         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
475         // Check that the update_fee newly generated matches what we delivered:
476         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
477         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
478
479         // Deliver (2) commitment_signed
480         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
481         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
482         check_added_monitors!(nodes[0], 1);
483         // No commitment_signed so get_event_msg's assert(len == 1) passes
484
485         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
486         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
487         check_added_monitors!(nodes[1], 1);
488
489         // Delever (4)
490         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
491         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
492         check_added_monitors!(nodes[1], 1);
493
494         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
495         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
496         check_added_monitors!(nodes[0], 1);
497
498         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
499         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
500         // No commitment_signed so get_event_msg's assert(len == 1) passes
501         check_added_monitors!(nodes[0], 1);
502
503         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
504         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
505         check_added_monitors!(nodes[1], 1);
506 }
507
508 fn do_test_sanity_on_in_flight_opens(steps: u8) {
509         // Previously, we had issues deserializing channels when we hadn't connected the first block
510         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
511         // serialization round-trips and simply do steps towards opening a channel and then drop the
512         // Node objects.
513
514         let chanmon_cfgs = create_chanmon_cfgs(2);
515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
517         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
518
519         if steps & 0b1000_0000 != 0{
520                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
521                 connect_block(&nodes[0], &block);
522                 connect_block(&nodes[1], &block);
523         }
524
525         if steps & 0x0f == 0 { return; }
526         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
527         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
528
529         if steps & 0x0f == 1 { return; }
530         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
531         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
532
533         if steps & 0x0f == 2 { return; }
534         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
535
536         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
537
538         if steps & 0x0f == 3 { return; }
539         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
540         check_added_monitors!(nodes[0], 0);
541         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
542
543         if steps & 0x0f == 4 { return; }
544         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
545         {
546                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
547                 assert_eq!(added_monitors.len(), 1);
548                 assert_eq!(added_monitors[0].0, funding_output);
549                 added_monitors.clear();
550         }
551         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
552
553         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
554
555         if steps & 0x0f == 5 { return; }
556         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
557         {
558                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
559                 assert_eq!(added_monitors.len(), 1);
560                 assert_eq!(added_monitors[0].0, funding_output);
561                 added_monitors.clear();
562         }
563
564         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
565         let events_4 = nodes[0].node.get_and_clear_pending_events();
566         assert_eq!(events_4.len(), 0);
567
568         if steps & 0x0f == 6 { return; }
569         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
570
571         if steps & 0x0f == 7 { return; }
572         confirm_transaction_at(&nodes[0], &tx, 2);
573         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
574         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
575         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
576 }
577
578 #[test]
579 fn test_sanity_on_in_flight_opens() {
580         do_test_sanity_on_in_flight_opens(0);
581         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
582         do_test_sanity_on_in_flight_opens(1);
583         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
584         do_test_sanity_on_in_flight_opens(2);
585         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
586         do_test_sanity_on_in_flight_opens(3);
587         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
588         do_test_sanity_on_in_flight_opens(4);
589         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
590         do_test_sanity_on_in_flight_opens(5);
591         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
592         do_test_sanity_on_in_flight_opens(6);
593         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
594         do_test_sanity_on_in_flight_opens(7);
595         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
596         do_test_sanity_on_in_flight_opens(8);
597         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
598 }
599
600 #[test]
601 fn test_update_fee_vanilla() {
602         let chanmon_cfgs = create_chanmon_cfgs(2);
603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
606         create_announced_chan_between_nodes(&nodes, 0, 1);
607
608         {
609                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
610                 *feerate_lock += 25;
611         }
612         nodes[0].node.timer_tick_occurred();
613         check_added_monitors!(nodes[0], 1);
614
615         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
616         assert_eq!(events_0.len(), 1);
617         let (update_msg, commitment_signed) = match events_0[0] {
618                         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 } } => {
619                         (update_fee.as_ref(), commitment_signed)
620                 },
621                 _ => panic!("Unexpected event"),
622         };
623         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
624
625         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
626         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
627         check_added_monitors!(nodes[1], 1);
628
629         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
630         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
631         check_added_monitors!(nodes[0], 1);
632
633         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
634         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
635         // No commitment_signed so get_event_msg's assert(len == 1) passes
636         check_added_monitors!(nodes[0], 1);
637
638         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
639         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
640         check_added_monitors!(nodes[1], 1);
641 }
642
643 #[test]
644 fn test_update_fee_that_funder_cannot_afford() {
645         let chanmon_cfgs = create_chanmon_cfgs(2);
646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
648         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
649         let channel_value = 5000;
650         let push_sats = 700;
651         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
652         let channel_id = chan.2;
653         let secp_ctx = Secp256k1::new();
654         let default_config = UserConfig::default();
655         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
656
657         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
658
659         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
660         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
661         // calculate two different feerates here - the expected local limit as well as the expected
662         // remote limit.
663         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;
664         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
665         {
666                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
667                 *feerate_lock = feerate;
668         }
669         nodes[0].node.timer_tick_occurred();
670         check_added_monitors!(nodes[0], 1);
671         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
672
673         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
674
675         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
676
677         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
678         {
679                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
680
681                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
682                 assert_eq!(commitment_tx.output.len(), 2);
683                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
684                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
685                 actual_fee = channel_value - actual_fee;
686                 assert_eq!(total_fee, actual_fee);
687         }
688
689         {
690                 // Increment the feerate by a small constant, accounting for rounding errors
691                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
692                 *feerate_lock += 4;
693         }
694         nodes[0].node.timer_tick_occurred();
695         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
696         check_added_monitors!(nodes[0], 0);
697
698         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
699
700         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
701         // needed to sign the new commitment tx and (2) sign the new commitment tx.
702         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
703                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
704                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
705                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
706                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
707                 ).flatten().unwrap();
708                 let chan_signer = local_chan.get_signer();
709                 let pubkeys = chan_signer.as_ref().pubkeys();
710                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
711                  pubkeys.funding_pubkey)
712         };
713         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
714                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
715                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
716                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
717                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
718                 ).flatten().unwrap();
719                 let chan_signer = remote_chan.get_signer();
720                 let pubkeys = chan_signer.as_ref().pubkeys();
721                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
722                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
723                  pubkeys.funding_pubkey)
724         };
725
726         // Assemble the set of keys we can use for signatures for our commitment_signed message.
727         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
728                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
729
730         let res = {
731                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
732                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
733                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
734                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
735                 ).flatten().unwrap();
736                 let local_chan_signer = local_chan.get_signer();
737                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
738                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
739                         INITIAL_COMMITMENT_NUMBER - 1,
740                         push_sats,
741                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
742                         local_funding, remote_funding,
743                         commit_tx_keys.clone(),
744                         non_buffer_feerate + 4,
745                         &mut htlcs,
746                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
747                 );
748                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
749         };
750
751         let commit_signed_msg = msgs::CommitmentSigned {
752                 channel_id: chan.2,
753                 signature: res.0,
754                 htlc_signatures: res.1,
755                 #[cfg(taproot)]
756                 partial_signature_with_nonce: None,
757         };
758
759         let update_fee = msgs::UpdateFee {
760                 channel_id: chan.2,
761                 feerate_per_kw: non_buffer_feerate + 4,
762         };
763
764         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
765
766         //While producing the commitment_signed response after handling a received update_fee request the
767         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
768         //Should produce and error.
769         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
770         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
771         check_added_monitors!(nodes[1], 1);
772         check_closed_broadcast!(nodes[1], true);
773         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
774                 [nodes[0].node.get_our_node_id()], channel_value);
775 }
776
777 #[test]
778 fn test_update_fee_with_fundee_update_add_htlc() {
779         let chanmon_cfgs = create_chanmon_cfgs(2);
780         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
781         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
782         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
783         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
784
785         // balancing
786         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
787
788         {
789                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
790                 *feerate_lock += 20;
791         }
792         nodes[0].node.timer_tick_occurred();
793         check_added_monitors!(nodes[0], 1);
794
795         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
796         assert_eq!(events_0.len(), 1);
797         let (update_msg, commitment_signed) = match events_0[0] {
798                         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 } } => {
799                         (update_fee.as_ref(), commitment_signed)
800                 },
801                 _ => panic!("Unexpected event"),
802         };
803         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
804         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
805         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
806         check_added_monitors!(nodes[1], 1);
807
808         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
809
810         // nothing happens since node[1] is in AwaitingRemoteRevoke
811         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
812                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
813         {
814                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
815                 assert_eq!(added_monitors.len(), 0);
816                 added_monitors.clear();
817         }
818         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
819         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
820         // node[1] has nothing to do
821
822         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
823         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
824         check_added_monitors!(nodes[0], 1);
825
826         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
827         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
828         // No commitment_signed so get_event_msg's assert(len == 1) passes
829         check_added_monitors!(nodes[0], 1);
830         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
831         check_added_monitors!(nodes[1], 1);
832         // AwaitingRemoteRevoke ends here
833
834         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
835         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
836         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
837         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
838         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
839         assert_eq!(commitment_update.update_fee.is_none(), true);
840
841         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
842         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
843         check_added_monitors!(nodes[0], 1);
844         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
845
846         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
847         check_added_monitors!(nodes[1], 1);
848         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
849
850         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
851         check_added_monitors!(nodes[1], 1);
852         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
853         // No commitment_signed so get_event_msg's assert(len == 1) passes
854
855         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
856         check_added_monitors!(nodes[0], 1);
857         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
858
859         expect_pending_htlcs_forwardable!(nodes[0]);
860
861         let events = nodes[0].node.get_and_clear_pending_events();
862         assert_eq!(events.len(), 1);
863         match events[0] {
864                 Event::PaymentClaimable { .. } => { },
865                 _ => panic!("Unexpected event"),
866         };
867
868         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
869
870         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
871         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
872         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
873         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
874         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
875 }
876
877 #[test]
878 fn test_update_fee() {
879         let chanmon_cfgs = create_chanmon_cfgs(2);
880         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
881         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
882         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
883         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
884         let channel_id = chan.2;
885
886         // A                                        B
887         // (1) update_fee/commitment_signed      ->
888         //                                       <- (2) revoke_and_ack
889         //                                       .- send (3) commitment_signed
890         // (4) update_fee/commitment_signed      ->
891         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
892         //                                       <- (3) commitment_signed delivered
893         // send (6) revoke_and_ack               -.
894         //                                       <- (5) deliver revoke_and_ack
895         // (6) deliver revoke_and_ack            ->
896         //                                       .- send (7) commitment_signed in response to (4)
897         //                                       <- (7) deliver commitment_signed
898         // revoke_and_ack                        ->
899
900         // Create and deliver (1)...
901         let feerate;
902         {
903                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
904                 feerate = *feerate_lock;
905                 *feerate_lock = feerate + 20;
906         }
907         nodes[0].node.timer_tick_occurred();
908         check_added_monitors!(nodes[0], 1);
909
910         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
911         assert_eq!(events_0.len(), 1);
912         let (update_msg, commitment_signed) = match events_0[0] {
913                         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 } } => {
914                         (update_fee.as_ref(), commitment_signed)
915                 },
916                 _ => panic!("Unexpected event"),
917         };
918         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
919
920         // Generate (2) and (3):
921         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
922         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
923         check_added_monitors!(nodes[1], 1);
924
925         // Deliver (2):
926         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
927         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
928         check_added_monitors!(nodes[0], 1);
929
930         // Create and deliver (4)...
931         {
932                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
933                 *feerate_lock = feerate + 30;
934         }
935         nodes[0].node.timer_tick_occurred();
936         check_added_monitors!(nodes[0], 1);
937         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
938         assert_eq!(events_0.len(), 1);
939         let (update_msg, commitment_signed) = match events_0[0] {
940                         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 } } => {
941                         (update_fee.as_ref(), commitment_signed)
942                 },
943                 _ => panic!("Unexpected event"),
944         };
945
946         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
947         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
948         check_added_monitors!(nodes[1], 1);
949         // ... creating (5)
950         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
951         // No commitment_signed so get_event_msg's assert(len == 1) passes
952
953         // Handle (3), creating (6):
954         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
955         check_added_monitors!(nodes[0], 1);
956         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
957         // No commitment_signed so get_event_msg's assert(len == 1) passes
958
959         // Deliver (5):
960         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
961         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
962         check_added_monitors!(nodes[0], 1);
963
964         // Deliver (6), creating (7):
965         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
966         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
967         assert!(commitment_update.update_add_htlcs.is_empty());
968         assert!(commitment_update.update_fulfill_htlcs.is_empty());
969         assert!(commitment_update.update_fail_htlcs.is_empty());
970         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
971         assert!(commitment_update.update_fee.is_none());
972         check_added_monitors!(nodes[1], 1);
973
974         // Deliver (7)
975         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
976         check_added_monitors!(nodes[0], 1);
977         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
978         // No commitment_signed so get_event_msg's assert(len == 1) passes
979
980         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
981         check_added_monitors!(nodes[1], 1);
982         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
983
984         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
985         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
986         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
987         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
988         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
989 }
990
991 #[test]
992 fn fake_network_test() {
993         // Simple test which builds a network of ChannelManagers, connects them to each other, and
994         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
995         let chanmon_cfgs = create_chanmon_cfgs(4);
996         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
997         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
998         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
999
1000         // Create some initial channels
1001         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1002         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1003         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1004
1005         // Rebalance the network a bit by relaying one payment through all the channels...
1006         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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
1011         // Send some more payments
1012         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1013         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1014         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1015
1016         // Test failure packets
1017         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1018         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1019
1020         // Add a new channel that skips 3
1021         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1022
1023         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1024         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1025         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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
1031         // Do some rebalance loop payments, simultaneously
1032         let mut hops = Vec::with_capacity(3);
1033         hops.push(RouteHop {
1034                 pubkey: nodes[2].node.get_our_node_id(),
1035                 node_features: NodeFeatures::empty(),
1036                 short_channel_id: chan_2.0.contents.short_channel_id,
1037                 channel_features: ChannelFeatures::empty(),
1038                 fee_msat: 0,
1039                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1040                 maybe_announced_channel: true,
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[3].node.get_our_node_id(),
1044                 node_features: NodeFeatures::empty(),
1045                 short_channel_id: chan_3.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::empty(),
1047                 fee_msat: 0,
1048                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1049                 maybe_announced_channel: true,
1050         });
1051         hops.push(RouteHop {
1052                 pubkey: nodes[1].node.get_our_node_id(),
1053                 node_features: nodes[1].node.node_features(),
1054                 short_channel_id: chan_4.0.contents.short_channel_id,
1055                 channel_features: nodes[1].node.channel_features(),
1056                 fee_msat: 1000000,
1057                 cltv_expiry_delta: TEST_FINAL_CLTV,
1058                 maybe_announced_channel: true,
1059         });
1060         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;
1061         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;
1062         let payment_preimage_1 = send_along_route(&nodes[1],
1063                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1064                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1065
1066         let mut hops = Vec::with_capacity(3);
1067         hops.push(RouteHop {
1068                 pubkey: nodes[3].node.get_our_node_id(),
1069                 node_features: NodeFeatures::empty(),
1070                 short_channel_id: chan_4.0.contents.short_channel_id,
1071                 channel_features: ChannelFeatures::empty(),
1072                 fee_msat: 0,
1073                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1074                 maybe_announced_channel: true,
1075         });
1076         hops.push(RouteHop {
1077                 pubkey: nodes[2].node.get_our_node_id(),
1078                 node_features: NodeFeatures::empty(),
1079                 short_channel_id: chan_3.0.contents.short_channel_id,
1080                 channel_features: ChannelFeatures::empty(),
1081                 fee_msat: 0,
1082                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1083                 maybe_announced_channel: true,
1084         });
1085         hops.push(RouteHop {
1086                 pubkey: nodes[1].node.get_our_node_id(),
1087                 node_features: nodes[1].node.node_features(),
1088                 short_channel_id: chan_2.0.contents.short_channel_id,
1089                 channel_features: nodes[1].node.channel_features(),
1090                 fee_msat: 1000000,
1091                 cltv_expiry_delta: TEST_FINAL_CLTV,
1092                 maybe_announced_channel: true,
1093         });
1094         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;
1095         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;
1096         let payment_hash_2 = send_along_route(&nodes[1],
1097                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1098                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1099
1100         // Claim the rebalances...
1101         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1102         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1103
1104         // Close down the channels...
1105         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1106         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1107         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1108         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1109         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1110         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1111         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1112         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1113         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1114         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1115         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1116         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1117 }
1118
1119 #[test]
1120 fn holding_cell_htlc_counting() {
1121         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1122         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1123         // commitment dance rounds.
1124         let chanmon_cfgs = create_chanmon_cfgs(3);
1125         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1126         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1127         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1128         create_announced_chan_between_nodes(&nodes, 0, 1);
1129         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1130
1131         // Fetch a route in advance as we will be unable to once we're unable to send.
1132         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1133
1134         let mut payments = Vec::new();
1135         for _ in 0..50 {
1136                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1137                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1138                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1139                 payments.push((payment_preimage, payment_hash));
1140         }
1141         check_added_monitors!(nodes[1], 1);
1142
1143         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1144         assert_eq!(events.len(), 1);
1145         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1146         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1147
1148         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1149         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1150         // another HTLC.
1151         {
1152                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1153                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1154                         ), true, APIError::ChannelUnavailable { .. }, {});
1155                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1156         }
1157
1158         // This should also be true if we try to forward a payment.
1159         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1160         {
1161                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1162                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1163                 check_added_monitors!(nodes[0], 1);
1164         }
1165
1166         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1167         assert_eq!(events.len(), 1);
1168         let payment_event = SendEvent::from_event(events.pop().unwrap());
1169         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1170
1171         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1172         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1173         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1174         // fails), the second will process the resulting failure and fail the HTLC backward.
1175         expect_pending_htlcs_forwardable!(nodes[1]);
1176         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 }]);
1177         check_added_monitors!(nodes[1], 1);
1178
1179         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1180         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1181         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1182
1183         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1184
1185         // Now forward all the pending HTLCs and claim them back
1186         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1187         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1188         check_added_monitors!(nodes[2], 1);
1189
1190         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1191         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1192         check_added_monitors!(nodes[1], 1);
1193         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1194
1195         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1196         check_added_monitors!(nodes[1], 1);
1197         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1198
1199         for ref update in as_updates.update_add_htlcs.iter() {
1200                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1201         }
1202         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1203         check_added_monitors!(nodes[2], 1);
1204         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1205         check_added_monitors!(nodes[2], 1);
1206         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1207
1208         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1209         check_added_monitors!(nodes[1], 1);
1210         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1211         check_added_monitors!(nodes[1], 1);
1212         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1213
1214         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1215         check_added_monitors!(nodes[2], 1);
1216
1217         expect_pending_htlcs_forwardable!(nodes[2]);
1218
1219         let events = nodes[2].node.get_and_clear_pending_events();
1220         assert_eq!(events.len(), payments.len());
1221         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1222                 match event {
1223                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1224                                 assert_eq!(*payment_hash, *hash);
1225                         },
1226                         _ => panic!("Unexpected event"),
1227                 };
1228         }
1229
1230         for (preimage, _) in payments.drain(..) {
1231                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1232         }
1233
1234         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1235 }
1236
1237 #[test]
1238 fn duplicate_htlc_test() {
1239         // Test that we accept duplicate payment_hash HTLCs across the network and that
1240         // claiming/failing them are all separate and don't affect each other
1241         let chanmon_cfgs = create_chanmon_cfgs(6);
1242         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1243         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1244         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1245
1246         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1247         create_announced_chan_between_nodes(&nodes, 0, 3);
1248         create_announced_chan_between_nodes(&nodes, 1, 3);
1249         create_announced_chan_between_nodes(&nodes, 2, 3);
1250         create_announced_chan_between_nodes(&nodes, 3, 4);
1251         create_announced_chan_between_nodes(&nodes, 3, 5);
1252
1253         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1254
1255         *nodes[0].network_payment_count.borrow_mut() -= 1;
1256         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1257
1258         *nodes[0].network_payment_count.borrow_mut() -= 1;
1259         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1260
1261         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1262         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1263         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1264 }
1265
1266 #[test]
1267 fn test_duplicate_htlc_different_direction_onchain() {
1268         // Test that ChannelMonitor doesn't generate 2 preimage txn
1269         // when we have 2 HTLCs with same preimage that go across a node
1270         // in opposite directions, even with the same payment secret.
1271         let chanmon_cfgs = create_chanmon_cfgs(2);
1272         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1273         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1274         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1275
1276         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1277
1278         // balancing
1279         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1280
1281         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1282
1283         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1284         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1285         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1286
1287         // Provide preimage to node 0 by claiming payment
1288         nodes[0].node.claim_funds(payment_preimage);
1289         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1290         check_added_monitors!(nodes[0], 1);
1291
1292         // Broadcast node 1 commitment txn
1293         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1294
1295         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1296         let mut has_both_htlcs = 0; // check htlcs match ones committed
1297         for outp in remote_txn[0].output.iter() {
1298                 if outp.value == 800_000 / 1000 {
1299                         has_both_htlcs += 1;
1300                 } else if outp.value == 900_000 / 1000 {
1301                         has_both_htlcs += 1;
1302                 }
1303         }
1304         assert_eq!(has_both_htlcs, 2);
1305
1306         mine_transaction(&nodes[0], &remote_txn[0]);
1307         check_added_monitors!(nodes[0], 1);
1308         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1309         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1310
1311         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1312         assert_eq!(claim_txn.len(), 3);
1313
1314         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1315         check_spends!(claim_txn[1], remote_txn[0]);
1316         check_spends!(claim_txn[2], remote_txn[0]);
1317         let preimage_tx = &claim_txn[0];
1318         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1319                 (&claim_txn[1], &claim_txn[2])
1320         } else {
1321                 (&claim_txn[2], &claim_txn[1])
1322         };
1323
1324         assert_eq!(preimage_tx.input.len(), 1);
1325         assert_eq!(preimage_bump_tx.input.len(), 1);
1326
1327         assert_eq!(preimage_tx.input.len(), 1);
1328         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1329         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1330
1331         assert_eq!(timeout_tx.input.len(), 1);
1332         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1333         check_spends!(timeout_tx, remote_txn[0]);
1334         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1335
1336         let events = nodes[0].node.get_and_clear_pending_msg_events();
1337         assert_eq!(events.len(), 3);
1338         for e in events {
1339                 match e {
1340                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1341                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1342                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1343                                 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1344                         },
1345                         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, .. } } => {
1346                                 assert!(update_add_htlcs.is_empty());
1347                                 assert!(update_fail_htlcs.is_empty());
1348                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1349                                 assert!(update_fail_malformed_htlcs.is_empty());
1350                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1351                         },
1352                         _ => panic!("Unexpected event"),
1353                 }
1354         }
1355 }
1356
1357 #[test]
1358 fn test_basic_channel_reserve() {
1359         let chanmon_cfgs = create_chanmon_cfgs(2);
1360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1362         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1363         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1364
1365         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1366         let channel_reserve = chan_stat.channel_reserve_msat;
1367
1368         // The 2* and +1 are for the fee spike reserve.
1369         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));
1370         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1371         let (mut route, our_payment_hash, _, our_payment_secret) =
1372                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1373         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1374         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1375                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1376         match err {
1377                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1378                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1379                         else { panic!("Unexpected error variant"); }
1380                 },
1381                 _ => panic!("Unexpected error variant"),
1382         }
1383         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1384
1385         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1386 }
1387
1388 #[test]
1389 fn test_fee_spike_violation_fails_htlc() {
1390         let chanmon_cfgs = create_chanmon_cfgs(2);
1391         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1392         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1393         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1394         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1395
1396         let (mut route, payment_hash, _, payment_secret) =
1397                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1398         route.paths[0].hops[0].fee_msat += 1;
1399         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1400         let secp_ctx = Secp256k1::new();
1401         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1402
1403         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1404
1405         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1406         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1407                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1408         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1409         let msg = msgs::UpdateAddHTLC {
1410                 channel_id: chan.2,
1411                 htlc_id: 0,
1412                 amount_msat: htlc_msat,
1413                 payment_hash: payment_hash,
1414                 cltv_expiry: htlc_cltv,
1415                 onion_routing_packet: onion_packet,
1416                 skimmed_fee_msat: None,
1417         };
1418
1419         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1420
1421         // Now manually create the commitment_signed message corresponding to the update_add
1422         // nodes[0] just sent. In the code for construction of this message, "local" refers
1423         // to the sender of the message, and "remote" refers to the receiver.
1424
1425         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1426
1427         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1428
1429         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1430         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1431         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1432                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1433                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1434                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1435                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1436                 ).flatten().unwrap();
1437                 let chan_signer = local_chan.get_signer();
1438                 // Make the signer believe we validated another commitment, so we can release the secret
1439                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1440
1441                 let pubkeys = chan_signer.as_ref().pubkeys();
1442                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1443                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1444                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1445                  chan_signer.as_ref().pubkeys().funding_pubkey)
1446         };
1447         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1448                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1449                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1450                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1451                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1452                 ).flatten().unwrap();
1453                 let chan_signer = remote_chan.get_signer();
1454                 let pubkeys = chan_signer.as_ref().pubkeys();
1455                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1456                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1457                  chan_signer.as_ref().pubkeys().funding_pubkey)
1458         };
1459
1460         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1461         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1462                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1463
1464         // Build the remote commitment transaction so we can sign it, and then later use the
1465         // signature for the commitment_signed message.
1466         let local_chan_balance = 1313;
1467
1468         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1469                 offered: false,
1470                 amount_msat: 3460001,
1471                 cltv_expiry: htlc_cltv,
1472                 payment_hash,
1473                 transaction_output_index: Some(1),
1474         };
1475
1476         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1477
1478         let res = {
1479                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1480                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1481                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1482                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1483                 ).flatten().unwrap();
1484                 let local_chan_signer = local_chan.get_signer();
1485                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1486                         commitment_number,
1487                         95000,
1488                         local_chan_balance,
1489                         local_funding, remote_funding,
1490                         commit_tx_keys.clone(),
1491                         feerate_per_kw,
1492                         &mut vec![(accepted_htlc_info, ())],
1493                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1494                 );
1495                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1496         };
1497
1498         let commit_signed_msg = msgs::CommitmentSigned {
1499                 channel_id: chan.2,
1500                 signature: res.0,
1501                 htlc_signatures: res.1,
1502                 #[cfg(taproot)]
1503                 partial_signature_with_nonce: None,
1504         };
1505
1506         // Send the commitment_signed message to the nodes[1].
1507         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1508         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1509
1510         // Send the RAA to nodes[1].
1511         let raa_msg = msgs::RevokeAndACK {
1512                 channel_id: chan.2,
1513                 per_commitment_secret: local_secret,
1514                 next_per_commitment_point: next_local_point,
1515                 #[cfg(taproot)]
1516                 next_local_nonce: None,
1517         };
1518         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1519
1520         let events = nodes[1].node.get_and_clear_pending_msg_events();
1521         assert_eq!(events.len(), 1);
1522         // Make sure the HTLC failed in the way we expect.
1523         match events[0] {
1524                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1525                         assert_eq!(update_fail_htlcs.len(), 1);
1526                         update_fail_htlcs[0].clone()
1527                 },
1528                 _ => panic!("Unexpected event"),
1529         };
1530         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1531                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1532
1533         check_added_monitors!(nodes[1], 2);
1534 }
1535
1536 #[test]
1537 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1538         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1539         // Set the fee rate for the channel very high, to the point where the fundee
1540         // sending any above-dust amount would result in a channel reserve violation.
1541         // In this test we check that we would be prevented from sending an HTLC in
1542         // this situation.
1543         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1546         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1547         let default_config = UserConfig::default();
1548         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1549
1550         let mut push_amt = 100_000_000;
1551         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1552
1553         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1554
1555         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1556
1557         // Fetch a route in advance as we will be unable to once we're unable to send.
1558         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1559         // Sending exactly enough to hit the reserve amount should be accepted
1560         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1561                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1562         }
1563
1564         // However one more HTLC should be significantly over the reserve amount and fail.
1565         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1566                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1567                 ), true, APIError::ChannelUnavailable { .. }, {});
1568         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1569 }
1570
1571 #[test]
1572 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1573         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1574         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1577         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1578         let default_config = UserConfig::default();
1579         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1580
1581         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1582         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1583         // transaction fee with 0 HTLCs (183 sats)).
1584         let mut push_amt = 100_000_000;
1585         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1586         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1587         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1588
1589         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1590         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1591                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1592         }
1593
1594         let (mut route, payment_hash, _, payment_secret) =
1595                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1596         route.paths[0].hops[0].fee_msat = 700_000;
1597         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1598         let secp_ctx = Secp256k1::new();
1599         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1600         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1601         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1602         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1603                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1604         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1605         let msg = msgs::UpdateAddHTLC {
1606                 channel_id: chan.2,
1607                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1608                 amount_msat: htlc_msat,
1609                 payment_hash: payment_hash,
1610                 cltv_expiry: htlc_cltv,
1611                 onion_routing_packet: onion_packet,
1612                 skimmed_fee_msat: None,
1613         };
1614
1615         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1616         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1617         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1618         assert_eq!(nodes[0].node.list_channels().len(), 0);
1619         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1620         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1621         check_added_monitors!(nodes[0], 1);
1622         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() },
1623                 [nodes[1].node.get_our_node_id()], 100000);
1624 }
1625
1626 #[test]
1627 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1628         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1629         // calculating our commitment transaction fee (this was previously broken).
1630         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1631         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1632
1633         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1634         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1635         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1636         let default_config = UserConfig::default();
1637         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1638
1639         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1640         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1641         // transaction fee with 0 HTLCs (183 sats)).
1642         let mut push_amt = 100_000_000;
1643         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1644         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1645         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1646
1647         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1648                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1649         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1650         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1651         // commitment transaction fee.
1652         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1653
1654         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1655         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1656                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1657         }
1658
1659         // One more than the dust amt should fail, however.
1660         let (mut route, our_payment_hash, _, our_payment_secret) =
1661                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1662         route.paths[0].hops[0].fee_msat += 1;
1663         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1664                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1665                 ), true, APIError::ChannelUnavailable { .. }, {});
1666 }
1667
1668 #[test]
1669 fn test_chan_init_feerate_unaffordability() {
1670         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1671         // channel reserve and feerate requirements.
1672         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1673         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1676         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1677         let default_config = UserConfig::default();
1678         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1679
1680         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1681         // HTLC.
1682         let mut push_amt = 100_000_000;
1683         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1684         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1685                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1686
1687         // During open, we don't have a "counterparty channel reserve" to check against, so that
1688         // requirement only comes into play on the open_channel handling side.
1689         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1690         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1691         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1692         open_channel_msg.push_msat += 1;
1693         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1694
1695         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1696         assert_eq!(msg_events.len(), 1);
1697         match msg_events[0] {
1698                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1699                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1700                 },
1701                 _ => panic!("Unexpected event"),
1702         }
1703 }
1704
1705 #[test]
1706 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1707         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1708         // calculating our counterparty's commitment transaction fee (this was previously broken).
1709         let chanmon_cfgs = create_chanmon_cfgs(2);
1710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1712         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1713         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1714
1715         let payment_amt = 46000; // Dust amount
1716         // In the previous code, these first four payments would succeed.
1717         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1718         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1719         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1720         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721
1722         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1723         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1724         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1725         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1726         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1728
1729         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1730         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1731         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1732         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1733 }
1734
1735 #[test]
1736 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1737         let chanmon_cfgs = create_chanmon_cfgs(3);
1738         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1739         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1740         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1741         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1742         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1743
1744         let feemsat = 239;
1745         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1746         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1747         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1748         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1749
1750         // Add a 2* and +1 for the fee spike reserve.
1751         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1752         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;
1753         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1754
1755         // Add a pending HTLC.
1756         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1757         let payment_event_1 = {
1758                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1759                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1760                 check_added_monitors!(nodes[0], 1);
1761
1762                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1763                 assert_eq!(events.len(), 1);
1764                 SendEvent::from_event(events.remove(0))
1765         };
1766         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1767
1768         // Attempt to trigger a channel reserve violation --> payment failure.
1769         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1770         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;
1771         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1772         let mut route_2 = route_1.clone();
1773         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1774
1775         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1776         let secp_ctx = Secp256k1::new();
1777         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1778         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1779         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1780         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1781                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1782         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1783         let msg = msgs::UpdateAddHTLC {
1784                 channel_id: chan.2,
1785                 htlc_id: 1,
1786                 amount_msat: htlc_msat + 1,
1787                 payment_hash: our_payment_hash_1,
1788                 cltv_expiry: htlc_cltv,
1789                 onion_routing_packet: onion_packet,
1790                 skimmed_fee_msat: None,
1791         };
1792
1793         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1794         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1795         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1796         assert_eq!(nodes[1].node.list_channels().len(), 1);
1797         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1798         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1799         check_added_monitors!(nodes[1], 1);
1800         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1801                 [nodes[0].node.get_our_node_id()], 100000);
1802 }
1803
1804 #[test]
1805 fn test_inbound_outbound_capacity_is_not_zero() {
1806         let chanmon_cfgs = create_chanmon_cfgs(2);
1807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1809         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1810         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1811         let channels0 = node_chanmgrs[0].list_channels();
1812         let channels1 = node_chanmgrs[1].list_channels();
1813         let default_config = UserConfig::default();
1814         assert_eq!(channels0.len(), 1);
1815         assert_eq!(channels1.len(), 1);
1816
1817         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1818         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1819         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1820
1821         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1822         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1823 }
1824
1825 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1826         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1827 }
1828
1829 #[test]
1830 fn test_channel_reserve_holding_cell_htlcs() {
1831         let chanmon_cfgs = create_chanmon_cfgs(3);
1832         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1833         // When this test was written, the default base fee floated based on the HTLC count.
1834         // It is now fixed, so we simply set the fee to the expected value here.
1835         let mut config = test_default_channel_config();
1836         config.channel_config.forwarding_fee_base_msat = 239;
1837         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1838         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1839         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1840         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1841
1842         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1843         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1844
1845         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1846         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1847
1848         macro_rules! expect_forward {
1849                 ($node: expr) => {{
1850                         let mut events = $node.node.get_and_clear_pending_msg_events();
1851                         assert_eq!(events.len(), 1);
1852                         check_added_monitors!($node, 1);
1853                         let payment_event = SendEvent::from_event(events.remove(0));
1854                         payment_event
1855                 }}
1856         }
1857
1858         let feemsat = 239; // set above
1859         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1860         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1861         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1862
1863         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1864
1865         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1866         {
1867                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1868                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1869                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1870                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1871                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1872
1873                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1874                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1875                         ), true, APIError::ChannelUnavailable { .. }, {});
1876                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1877         }
1878
1879         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1880         // nodes[0]'s wealth
1881         loop {
1882                 let amt_msat = recv_value_0 + total_fee_msat;
1883                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1884                 // Also, ensure that each payment has enough to be over the dust limit to
1885                 // ensure it'll be included in each commit tx fee calculation.
1886                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1887                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1888                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1889                         break;
1890                 }
1891
1892                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1893                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1894                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1895                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1896                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1897
1898                 let (stat01_, stat11_, stat12_, stat22_) = (
1899                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1900                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1901                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1902                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1903                 );
1904
1905                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1906                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1907                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1908                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1909                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1910         }
1911
1912         // adding pending output.
1913         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1914         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1915         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1916         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1917         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1918         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1919         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1920         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1921         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1922         // policy.
1923         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1924         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1925         let amt_msat_1 = recv_value_1 + total_fee_msat;
1926
1927         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);
1928         let payment_event_1 = {
1929                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1930                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1931                 check_added_monitors!(nodes[0], 1);
1932
1933                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1934                 assert_eq!(events.len(), 1);
1935                 SendEvent::from_event(events.remove(0))
1936         };
1937         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1938
1939         // channel reserve test with htlc pending output > 0
1940         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1941         {
1942                 let mut route = route_1.clone();
1943                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1944                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1945                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1946                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1947                         ), true, APIError::ChannelUnavailable { .. }, {});
1948                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1949         }
1950
1951         // split the rest to test holding cell
1952         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1953         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1954         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1955         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1956         {
1957                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1958                 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);
1959         }
1960
1961         // now see if they go through on both sides
1962         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);
1963         // but this will stuck in the holding cell
1964         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1965                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1966         check_added_monitors!(nodes[0], 0);
1967         let events = nodes[0].node.get_and_clear_pending_events();
1968         assert_eq!(events.len(), 0);
1969
1970         // test with outbound holding cell amount > 0
1971         {
1972                 let (mut route, our_payment_hash, _, our_payment_secret) =
1973                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1974                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1975                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1976                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1977                         ), true, APIError::ChannelUnavailable { .. }, {});
1978                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1979         }
1980
1981         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);
1982         // this will also stuck in the holding cell
1983         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1984                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1985         check_added_monitors!(nodes[0], 0);
1986         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1987         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1988
1989         // flush the pending htlc
1990         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1991         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1992         check_added_monitors!(nodes[1], 1);
1993
1994         // the pending htlc should be promoted to committed
1995         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1996         check_added_monitors!(nodes[0], 1);
1997         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1998
1999         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2000         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2001         // No commitment_signed so get_event_msg's assert(len == 1) passes
2002         check_added_monitors!(nodes[0], 1);
2003
2004         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2005         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2006         check_added_monitors!(nodes[1], 1);
2007
2008         expect_pending_htlcs_forwardable!(nodes[1]);
2009
2010         let ref payment_event_11 = expect_forward!(nodes[1]);
2011         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2012         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2013
2014         expect_pending_htlcs_forwardable!(nodes[2]);
2015         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2016
2017         // flush the htlcs in the holding cell
2018         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2019         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2020         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2021         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2022         expect_pending_htlcs_forwardable!(nodes[1]);
2023
2024         let ref payment_event_3 = expect_forward!(nodes[1]);
2025         assert_eq!(payment_event_3.msgs.len(), 2);
2026         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2027         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2028
2029         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2030         expect_pending_htlcs_forwardable!(nodes[2]);
2031
2032         let events = nodes[2].node.get_and_clear_pending_events();
2033         assert_eq!(events.len(), 2);
2034         match events[0] {
2035                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2036                         assert_eq!(our_payment_hash_21, *payment_hash);
2037                         assert_eq!(recv_value_21, amount_msat);
2038                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2039                         assert_eq!(via_channel_id, Some(chan_2.2));
2040                         match &purpose {
2041                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2042                                         assert!(payment_preimage.is_none());
2043                                         assert_eq!(our_payment_secret_21, *payment_secret);
2044                                 },
2045                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2046                         }
2047                 },
2048                 _ => panic!("Unexpected event"),
2049         }
2050         match events[1] {
2051                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2052                         assert_eq!(our_payment_hash_22, *payment_hash);
2053                         assert_eq!(recv_value_22, amount_msat);
2054                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2055                         assert_eq!(via_channel_id, Some(chan_2.2));
2056                         match &purpose {
2057                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2058                                         assert!(payment_preimage.is_none());
2059                                         assert_eq!(our_payment_secret_22, *payment_secret);
2060                                 },
2061                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2062                         }
2063                 },
2064                 _ => panic!("Unexpected event"),
2065         }
2066
2067         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2068         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2069         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2070
2071         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2072         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2073         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2074
2075         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2076         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);
2077         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2078         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2079         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2080
2081         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2082         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2083 }
2084
2085 #[test]
2086 fn channel_reserve_in_flight_removes() {
2087         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2088         // can send to its counterparty, but due to update ordering, the other side may not yet have
2089         // considered those HTLCs fully removed.
2090         // This tests that we don't count HTLCs which will not be included in the next remote
2091         // commitment transaction towards the reserve value (as it implies no commitment transaction
2092         // will be generated which violates the remote reserve value).
2093         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2094         // To test this we:
2095         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2096         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2097         //    you only consider the value of the first HTLC, it may not),
2098         //  * start routing a third HTLC from A to B,
2099         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2100         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2101         //  * deliver the first fulfill from B
2102         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2103         //    claim,
2104         //  * deliver A's response CS and RAA.
2105         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2106         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2107         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2108         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2109         let chanmon_cfgs = create_chanmon_cfgs(2);
2110         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2111         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2112         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2113         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2114
2115         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2116         // Route the first two HTLCs.
2117         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2118         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2119         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2120
2121         // Start routing the third HTLC (this is just used to get everyone in the right state).
2122         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2123         let send_1 = {
2124                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2125                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2126                 check_added_monitors!(nodes[0], 1);
2127                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2128                 assert_eq!(events.len(), 1);
2129                 SendEvent::from_event(events.remove(0))
2130         };
2131
2132         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2133         // initial fulfill/CS.
2134         nodes[1].node.claim_funds(payment_preimage_1);
2135         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2136         check_added_monitors!(nodes[1], 1);
2137         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2138
2139         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2140         // remove the second HTLC when we send the HTLC back from B to A.
2141         nodes[1].node.claim_funds(payment_preimage_2);
2142         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2143         check_added_monitors!(nodes[1], 1);
2144         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2145
2146         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2147         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2148         check_added_monitors!(nodes[0], 1);
2149         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2150         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2151
2152         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2153         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2154         check_added_monitors!(nodes[1], 1);
2155         // B is already AwaitingRAA, so cant generate a CS here
2156         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2157
2158         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2159         check_added_monitors!(nodes[1], 1);
2160         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2161
2162         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2163         check_added_monitors!(nodes[0], 1);
2164         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2165
2166         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2167         check_added_monitors!(nodes[1], 1);
2168         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2169
2170         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2171         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2172         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2173         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2174         // on-chain as necessary).
2175         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2176         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2177         check_added_monitors!(nodes[0], 1);
2178         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2179         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2180
2181         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2182         check_added_monitors!(nodes[1], 1);
2183         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2184
2185         expect_pending_htlcs_forwardable!(nodes[1]);
2186         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2187
2188         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2189         // resolve the second HTLC from A's point of view.
2190         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2191         check_added_monitors!(nodes[0], 1);
2192         expect_payment_path_successful!(nodes[0]);
2193         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2194
2195         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2196         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2197         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2198         let send_2 = {
2199                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2200                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2201                 check_added_monitors!(nodes[1], 1);
2202                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2203                 assert_eq!(events.len(), 1);
2204                 SendEvent::from_event(events.remove(0))
2205         };
2206
2207         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2208         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2209         check_added_monitors!(nodes[0], 1);
2210         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2211
2212         // Now just resolve all the outstanding messages/HTLCs for completeness...
2213
2214         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2215         check_added_monitors!(nodes[1], 1);
2216         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2217
2218         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2219         check_added_monitors!(nodes[1], 1);
2220
2221         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2222         check_added_monitors!(nodes[0], 1);
2223         expect_payment_path_successful!(nodes[0]);
2224         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2225
2226         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2227         check_added_monitors!(nodes[1], 1);
2228         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2229
2230         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2231         check_added_monitors!(nodes[0], 1);
2232
2233         expect_pending_htlcs_forwardable!(nodes[0]);
2234         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2235
2236         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2237         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2238 }
2239
2240 #[test]
2241 fn channel_monitor_network_test() {
2242         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2243         // tests that ChannelMonitor is able to recover from various states.
2244         let chanmon_cfgs = create_chanmon_cfgs(5);
2245         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2246         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2247         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2248
2249         // Create some initial channels
2250         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2251         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2252         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2253         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2254
2255         // Make sure all nodes are at the same starting height
2256         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2257         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2258         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2259         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2260         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2261
2262         // Rebalance the network a bit by relaying one payment through all the channels...
2263         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2264         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2265         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2266         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2267
2268         // Simple case with no pending HTLCs:
2269         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2270         check_added_monitors!(nodes[1], 1);
2271         check_closed_broadcast!(nodes[1], true);
2272         {
2273                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2274                 assert_eq!(node_txn.len(), 1);
2275                 mine_transaction(&nodes[0], &node_txn[0]);
2276                 check_added_monitors!(nodes[0], 1);
2277                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2278         }
2279         check_closed_broadcast!(nodes[0], true);
2280         assert_eq!(nodes[0].node.list_channels().len(), 0);
2281         assert_eq!(nodes[1].node.list_channels().len(), 1);
2282         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2283         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2284
2285         // One pending HTLC is discarded by the force-close:
2286         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2287
2288         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2289         // broadcasted until we reach the timelock time).
2290         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2291         check_closed_broadcast!(nodes[1], true);
2292         check_added_monitors!(nodes[1], 1);
2293         {
2294                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2295                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2296                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2297                 mine_transaction(&nodes[2], &node_txn[0]);
2298                 check_added_monitors!(nodes[2], 1);
2299                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2300         }
2301         check_closed_broadcast!(nodes[2], true);
2302         assert_eq!(nodes[1].node.list_channels().len(), 0);
2303         assert_eq!(nodes[2].node.list_channels().len(), 1);
2304         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2305         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2306
2307         macro_rules! claim_funds {
2308                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2309                         {
2310                                 $node.node.claim_funds($preimage);
2311                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2312                                 check_added_monitors!($node, 1);
2313
2314                                 let events = $node.node.get_and_clear_pending_msg_events();
2315                                 assert_eq!(events.len(), 1);
2316                                 match events[0] {
2317                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2318                                                 assert!(update_add_htlcs.is_empty());
2319                                                 assert!(update_fail_htlcs.is_empty());
2320                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2321                                         },
2322                                         _ => panic!("Unexpected event"),
2323                                 };
2324                         }
2325                 }
2326         }
2327
2328         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2329         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2330         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2331         check_added_monitors!(nodes[2], 1);
2332         check_closed_broadcast!(nodes[2], true);
2333         let node2_commitment_txid;
2334         {
2335                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2336                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2337                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2338                 node2_commitment_txid = node_txn[0].txid();
2339
2340                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2341                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2342                 mine_transaction(&nodes[3], &node_txn[0]);
2343                 check_added_monitors!(nodes[3], 1);
2344                 check_preimage_claim(&nodes[3], &node_txn);
2345         }
2346         check_closed_broadcast!(nodes[3], true);
2347         assert_eq!(nodes[2].node.list_channels().len(), 0);
2348         assert_eq!(nodes[3].node.list_channels().len(), 1);
2349         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2350         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2351
2352         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2353         // confusing us in the following tests.
2354         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2355
2356         // One pending HTLC to time out:
2357         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2358         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2359         // buffer space).
2360
2361         let (close_chan_update_1, close_chan_update_2) = {
2362                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2363                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2364                 assert_eq!(events.len(), 2);
2365                 let close_chan_update_1 = match events[0] {
2366                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2367                                 msg.clone()
2368                         },
2369                         _ => panic!("Unexpected event"),
2370                 };
2371                 match events[1] {
2372                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2373                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2374                         },
2375                         _ => panic!("Unexpected event"),
2376                 }
2377                 check_added_monitors!(nodes[3], 1);
2378
2379                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2380                 {
2381                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2382                         node_txn.retain(|tx| {
2383                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2384                                         false
2385                                 } else { true }
2386                         });
2387                 }
2388
2389                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2390
2391                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2392                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2393
2394                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2395                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2396                 assert_eq!(events.len(), 2);
2397                 let close_chan_update_2 = match events[0] {
2398                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2399                                 msg.clone()
2400                         },
2401                         _ => panic!("Unexpected event"),
2402                 };
2403                 match events[1] {
2404                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2405                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2406                         },
2407                         _ => panic!("Unexpected event"),
2408                 }
2409                 check_added_monitors!(nodes[4], 1);
2410                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2411                 check_closed_event!(nodes[4], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2412
2413                 mine_transaction(&nodes[4], &node_txn[0]);
2414                 check_preimage_claim(&nodes[4], &node_txn);
2415                 (close_chan_update_1, close_chan_update_2)
2416         };
2417         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2418         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2419         assert_eq!(nodes[3].node.list_channels().len(), 0);
2420         assert_eq!(nodes[4].node.list_channels().len(), 0);
2421
2422         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2423                 Ok(ChannelMonitorUpdateStatus::Completed));
2424         check_closed_event!(nodes[3], 1, ClosureReason::HolderForceClosed, [nodes[4].node.get_our_node_id()], 100000);
2425 }
2426
2427 #[test]
2428 fn test_justice_tx_htlc_timeout() {
2429         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2430         let mut alice_config = UserConfig::default();
2431         alice_config.channel_handshake_config.announced_channel = true;
2432         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2433         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2434         let mut bob_config = UserConfig::default();
2435         bob_config.channel_handshake_config.announced_channel = true;
2436         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2437         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2438         let user_cfgs = [Some(alice_config), Some(bob_config)];
2439         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2440         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2441         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2444         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2445         // Create some new channels:
2446         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2447
2448         // A pending HTLC which will be revoked:
2449         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2450         // Get the will-be-revoked local txn from nodes[0]
2451         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2452         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2453         assert_eq!(revoked_local_txn[0].input.len(), 1);
2454         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2455         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2456         assert_eq!(revoked_local_txn[1].input.len(), 1);
2457         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2458         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2459         // Revoke the old state
2460         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2461
2462         {
2463                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2464                 {
2465                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2466                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2467                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2468                         check_spends!(node_txn[0], revoked_local_txn[0]);
2469                         node_txn.swap_remove(0);
2470                 }
2471                 check_added_monitors!(nodes[1], 1);
2472                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2473                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2474
2475                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2476                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2477                 // Verify broadcast of revoked HTLC-timeout
2478                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2479                 check_added_monitors!(nodes[0], 1);
2480                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2481                 // Broadcast revoked HTLC-timeout on node 1
2482                 mine_transaction(&nodes[1], &node_txn[1]);
2483                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2484         }
2485         get_announce_close_broadcast_events(&nodes, 0, 1);
2486         assert_eq!(nodes[0].node.list_channels().len(), 0);
2487         assert_eq!(nodes[1].node.list_channels().len(), 0);
2488 }
2489
2490 #[test]
2491 fn test_justice_tx_htlc_success() {
2492         // Test justice txn built on revoked HTLC-Success tx, against both sides
2493         let mut alice_config = UserConfig::default();
2494         alice_config.channel_handshake_config.announced_channel = true;
2495         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2496         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2497         let mut bob_config = UserConfig::default();
2498         bob_config.channel_handshake_config.announced_channel = true;
2499         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2500         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2501         let user_cfgs = [Some(alice_config), Some(bob_config)];
2502         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2503         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2504         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2507         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2508         // Create some new channels:
2509         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2510
2511         // A pending HTLC which will be revoked:
2512         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2513         // Get the will-be-revoked local txn from B
2514         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2515         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2516         assert_eq!(revoked_local_txn[0].input.len(), 1);
2517         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2518         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2519         // Revoke the old state
2520         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2521         {
2522                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2523                 {
2524                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2525                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2526                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2527
2528                         check_spends!(node_txn[0], revoked_local_txn[0]);
2529                         node_txn.swap_remove(0);
2530                 }
2531                 check_added_monitors!(nodes[0], 1);
2532                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2533
2534                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2536                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2537                 check_added_monitors!(nodes[1], 1);
2538                 mine_transaction(&nodes[0], &node_txn[1]);
2539                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2540                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2541         }
2542         get_announce_close_broadcast_events(&nodes, 0, 1);
2543         assert_eq!(nodes[0].node.list_channels().len(), 0);
2544         assert_eq!(nodes[1].node.list_channels().len(), 0);
2545 }
2546
2547 #[test]
2548 fn revoked_output_claim() {
2549         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2550         // transaction is broadcast by its counterparty
2551         let chanmon_cfgs = create_chanmon_cfgs(2);
2552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2554         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2555         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2556         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2557         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2558         assert_eq!(revoked_local_txn.len(), 1);
2559         // Only output is the full channel value back to nodes[0]:
2560         assert_eq!(revoked_local_txn[0].output.len(), 1);
2561         // Send a payment through, updating everyone's latest commitment txn
2562         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2563
2564         // Inform nodes[1] that nodes[0] broadcast a stale tx
2565         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2566         check_added_monitors!(nodes[1], 1);
2567         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2568         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2569         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2570
2571         check_spends!(node_txn[0], revoked_local_txn[0]);
2572
2573         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2574         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2575         get_announce_close_broadcast_events(&nodes, 0, 1);
2576         check_added_monitors!(nodes[0], 1);
2577         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2578 }
2579
2580 #[test]
2581 fn test_forming_justice_tx_from_monitor_updates() {
2582         do_test_forming_justice_tx_from_monitor_updates(true);
2583         do_test_forming_justice_tx_from_monitor_updates(false);
2584 }
2585
2586 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2587         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2588         // is properly formed and can be broadcasted/confirmed successfully in the event
2589         // that a revoked commitment transaction is broadcasted
2590         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2591         let chanmon_cfgs = create_chanmon_cfgs(2);
2592         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2593         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2594         let persisters = vec![WatchtowerPersister::new(destination_script0),
2595                 WatchtowerPersister::new(destination_script1)];
2596         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2598         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2599         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2600         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2601
2602         if !broadcast_initial_commitment {
2603                 // Send a payment to move the channel forward
2604                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2605         }
2606
2607         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2608         // We'll keep this commitment transaction to broadcast once it's revoked.
2609         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2610         assert_eq!(revoked_local_txn.len(), 1);
2611         let revoked_commitment_tx = &revoked_local_txn[0];
2612
2613         // Send another payment, now revoking the previous commitment tx
2614         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2615
2616         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2617         check_spends!(justice_tx, revoked_commitment_tx);
2618
2619         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2620         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2621
2622         check_added_monitors!(nodes[1], 1);
2623         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2624                 &[nodes[0].node.get_our_node_id()], 100_000);
2625         get_announce_close_broadcast_events(&nodes, 1, 0);
2626
2627         check_added_monitors!(nodes[0], 1);
2628         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2629                 &[nodes[1].node.get_our_node_id()], 100_000);
2630
2631         // Check that the justice tx has sent the revoked output value to nodes[1]
2632         let monitor = get_monitor!(nodes[1], channel_id);
2633         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2634                 match balance {
2635                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2636                         _ => panic!("Unexpected balance type"),
2637                 }
2638         });
2639         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2640         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2641         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2642         assert_eq!(total_claimable_balance, expected_claimable_balance);
2643 }
2644
2645
2646 #[test]
2647 fn claim_htlc_outputs_shared_tx() {
2648         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2649         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2650         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2653         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2654
2655         // Create some new channel:
2656         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2657
2658         // Rebalance the network to generate htlc in the two directions
2659         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2660         // 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
2661         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2662         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2663
2664         // Get the will-be-revoked local txn from node[0]
2665         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2666         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2667         assert_eq!(revoked_local_txn[0].input.len(), 1);
2668         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2669         assert_eq!(revoked_local_txn[1].input.len(), 1);
2670         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2671         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2672         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2673
2674         //Revoke the old state
2675         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2676
2677         {
2678                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2679                 check_added_monitors!(nodes[0], 1);
2680                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2681                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2682                 check_added_monitors!(nodes[1], 1);
2683                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2684                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2685                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2686
2687                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2688                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2689
2690                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2691                 check_spends!(node_txn[0], revoked_local_txn[0]);
2692
2693                 let mut witness_lens = BTreeSet::new();
2694                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2695                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2696                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2697                 assert_eq!(witness_lens.len(), 3);
2698                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2699                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2700                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2701
2702                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2703                 // ANTI_REORG_DELAY confirmations.
2704                 mine_transaction(&nodes[1], &node_txn[0]);
2705                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2706                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2707         }
2708         get_announce_close_broadcast_events(&nodes, 0, 1);
2709         assert_eq!(nodes[0].node.list_channels().len(), 0);
2710         assert_eq!(nodes[1].node.list_channels().len(), 0);
2711 }
2712
2713 #[test]
2714 fn claim_htlc_outputs_single_tx() {
2715         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2716         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2717         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2721
2722         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2723
2724         // Rebalance the network to generate htlc in the two directions
2725         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2726         // 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
2727         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2728         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2729         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2730
2731         // Get the will-be-revoked local txn from node[0]
2732         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2733
2734         //Revoke the old state
2735         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2736
2737         {
2738                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2739                 check_added_monitors!(nodes[0], 1);
2740                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2741                 check_added_monitors!(nodes[1], 1);
2742                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2743                 let mut events = nodes[0].node.get_and_clear_pending_events();
2744                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2745                 match events.last().unwrap() {
2746                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2747                         _ => panic!("Unexpected event"),
2748                 }
2749
2750                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2751                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2752
2753                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2754
2755                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2756                 assert_eq!(node_txn[0].input.len(), 1);
2757                 check_spends!(node_txn[0], chan_1.3);
2758                 assert_eq!(node_txn[1].input.len(), 1);
2759                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2760                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2761                 check_spends!(node_txn[1], node_txn[0]);
2762
2763                 // Filter out any non justice transactions.
2764                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2765                 assert!(node_txn.len() > 3);
2766
2767                 assert_eq!(node_txn[0].input.len(), 1);
2768                 assert_eq!(node_txn[1].input.len(), 1);
2769                 assert_eq!(node_txn[2].input.len(), 1);
2770
2771                 check_spends!(node_txn[0], revoked_local_txn[0]);
2772                 check_spends!(node_txn[1], revoked_local_txn[0]);
2773                 check_spends!(node_txn[2], revoked_local_txn[0]);
2774
2775                 let mut witness_lens = BTreeSet::new();
2776                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2777                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2778                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2779                 assert_eq!(witness_lens.len(), 3);
2780                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2781                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2782                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2783
2784                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2785                 // ANTI_REORG_DELAY confirmations.
2786                 mine_transaction(&nodes[1], &node_txn[0]);
2787                 mine_transaction(&nodes[1], &node_txn[1]);
2788                 mine_transaction(&nodes[1], &node_txn[2]);
2789                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2790                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2791         }
2792         get_announce_close_broadcast_events(&nodes, 0, 1);
2793         assert_eq!(nodes[0].node.list_channels().len(), 0);
2794         assert_eq!(nodes[1].node.list_channels().len(), 0);
2795 }
2796
2797 #[test]
2798 fn test_htlc_on_chain_success() {
2799         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2800         // the preimage backward accordingly. So here we test that ChannelManager is
2801         // broadcasting the right event to other nodes in payment path.
2802         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2803         // A --------------------> B ----------------------> C (preimage)
2804         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2805         // commitment transaction was broadcast.
2806         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2807         // towards B.
2808         // B should be able to claim via preimage if A then broadcasts its local tx.
2809         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2810         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2811         // PaymentSent event).
2812
2813         let chanmon_cfgs = create_chanmon_cfgs(3);
2814         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2815         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2816         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2817
2818         // Create some initial channels
2819         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2820         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2821
2822         // Ensure all nodes are at the same height
2823         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2824         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2825         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2826         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2827
2828         // Rebalance the network a bit by relaying one payment through all the channels...
2829         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2830         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2831
2832         let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2833         let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2834
2835         // Broadcast legit commitment tx from C on B's chain
2836         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2837         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2838         assert_eq!(commitment_tx.len(), 1);
2839         check_spends!(commitment_tx[0], chan_2.3);
2840         nodes[2].node.claim_funds(our_payment_preimage);
2841         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2842         nodes[2].node.claim_funds(our_payment_preimage_2);
2843         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2844         check_added_monitors!(nodes[2], 2);
2845         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2846         assert!(updates.update_add_htlcs.is_empty());
2847         assert!(updates.update_fail_htlcs.is_empty());
2848         assert!(updates.update_fail_malformed_htlcs.is_empty());
2849         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2850
2851         mine_transaction(&nodes[2], &commitment_tx[0]);
2852         check_closed_broadcast!(nodes[2], true);
2853         check_added_monitors!(nodes[2], 1);
2854         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2855         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2856         assert_eq!(node_txn.len(), 2);
2857         check_spends!(node_txn[0], commitment_tx[0]);
2858         check_spends!(node_txn[1], commitment_tx[0]);
2859         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2860         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2861         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2862         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2863         assert_eq!(node_txn[0].lock_time.0, 0);
2864         assert_eq!(node_txn[1].lock_time.0, 0);
2865
2866         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2867         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()]));
2868         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2869         {
2870                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2871                 assert_eq!(added_monitors.len(), 1);
2872                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2873                 added_monitors.clear();
2874         }
2875         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2876         assert_eq!(forwarded_events.len(), 3);
2877         match forwarded_events[0] {
2878                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2879                 _ => panic!("Unexpected event"),
2880         }
2881         let chan_id = Some(chan_1.2);
2882         match forwarded_events[1] {
2883                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2884                         assert_eq!(fee_earned_msat, Some(1000));
2885                         assert_eq!(prev_channel_id, chan_id);
2886                         assert_eq!(claim_from_onchain_tx, true);
2887                         assert_eq!(next_channel_id, Some(chan_2.2));
2888                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2889                 },
2890                 _ => panic!()
2891         }
2892         match forwarded_events[2] {
2893                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2894                         assert_eq!(fee_earned_msat, Some(1000));
2895                         assert_eq!(prev_channel_id, chan_id);
2896                         assert_eq!(claim_from_onchain_tx, true);
2897                         assert_eq!(next_channel_id, Some(chan_2.2));
2898                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2899                 },
2900                 _ => panic!()
2901         }
2902         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2903         {
2904                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2905                 assert_eq!(added_monitors.len(), 2);
2906                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2907                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2908                 added_monitors.clear();
2909         }
2910         assert_eq!(events.len(), 3);
2911
2912         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2913         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2914
2915         match nodes_2_event {
2916                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2917                 _ => panic!("Unexpected event"),
2918         }
2919
2920         match nodes_0_event {
2921                 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, .. } } => {
2922                         assert!(update_add_htlcs.is_empty());
2923                         assert!(update_fail_htlcs.is_empty());
2924                         assert_eq!(update_fulfill_htlcs.len(), 1);
2925                         assert!(update_fail_malformed_htlcs.is_empty());
2926                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2927                 },
2928                 _ => panic!("Unexpected event"),
2929         };
2930
2931         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2932         match events[0] {
2933                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2934                 _ => panic!("Unexpected event"),
2935         }
2936
2937         macro_rules! check_tx_local_broadcast {
2938                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2939                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2940                         assert_eq!(node_txn.len(), 2);
2941                         // Node[1]: 2 * HTLC-timeout tx
2942                         // Node[0]: 2 * HTLC-timeout tx
2943                         check_spends!(node_txn[0], $commitment_tx);
2944                         check_spends!(node_txn[1], $commitment_tx);
2945                         assert_ne!(node_txn[0].lock_time.0, 0);
2946                         assert_ne!(node_txn[1].lock_time.0, 0);
2947                         if $htlc_offered {
2948                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2949                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2950                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2951                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2952                         } else {
2953                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2954                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2955                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2956                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2957                         }
2958                         node_txn.clear();
2959                 } }
2960         }
2961         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2962         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2963
2964         // Broadcast legit commitment tx from A on B's chain
2965         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2966         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2967         check_spends!(node_a_commitment_tx[0], chan_1.3);
2968         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2969         check_closed_broadcast!(nodes[1], true);
2970         check_added_monitors!(nodes[1], 1);
2971         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2972         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2973         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2974         let commitment_spend =
2975                 if node_txn.len() == 1 {
2976                         &node_txn[0]
2977                 } else {
2978                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2979                         // FullBlockViaListen
2980                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2981                                 check_spends!(node_txn[1], commitment_tx[0]);
2982                                 check_spends!(node_txn[2], commitment_tx[0]);
2983                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2984                                 &node_txn[0]
2985                         } else {
2986                                 check_spends!(node_txn[0], commitment_tx[0]);
2987                                 check_spends!(node_txn[1], commitment_tx[0]);
2988                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2989                                 &node_txn[2]
2990                         }
2991                 };
2992
2993         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2994         assert_eq!(commitment_spend.input.len(), 2);
2995         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2996         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2997         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2998         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2999         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3000         // we already checked the same situation with A.
3001
3002         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3003         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3004         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3005         check_closed_broadcast!(nodes[0], true);
3006         check_added_monitors!(nodes[0], 1);
3007         let events = nodes[0].node.get_and_clear_pending_events();
3008         assert_eq!(events.len(), 5);
3009         let mut first_claimed = false;
3010         for event in events {
3011                 match event {
3012                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3013                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3014                                         assert!(!first_claimed);
3015                                         first_claimed = true;
3016                                 } else {
3017                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3018                                         assert_eq!(payment_hash, payment_hash_2);
3019                                 }
3020                         },
3021                         Event::PaymentPathSuccessful { .. } => {},
3022                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3023                         _ => panic!("Unexpected event"),
3024                 }
3025         }
3026         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3027 }
3028
3029 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3030         // Test that in case of a unilateral close onchain, we detect the state of output and
3031         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3032         // broadcasting the right event to other nodes in payment path.
3033         // A ------------------> B ----------------------> C (timeout)
3034         //    B's commitment tx                 C's commitment tx
3035         //            \                                  \
3036         //         B's HTLC timeout tx               B's timeout tx
3037
3038         let chanmon_cfgs = create_chanmon_cfgs(3);
3039         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3040         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3041         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3042         *nodes[0].connect_style.borrow_mut() = connect_style;
3043         *nodes[1].connect_style.borrow_mut() = connect_style;
3044         *nodes[2].connect_style.borrow_mut() = connect_style;
3045
3046         // Create some intial channels
3047         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3048         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3049
3050         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3051         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3052         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3053
3054         let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3055
3056         // Broadcast legit commitment tx from C on B's chain
3057         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3058         check_spends!(commitment_tx[0], chan_2.3);
3059         nodes[2].node.fail_htlc_backwards(&payment_hash);
3060         check_added_monitors!(nodes[2], 0);
3061         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3062         check_added_monitors!(nodes[2], 1);
3063
3064         let events = nodes[2].node.get_and_clear_pending_msg_events();
3065         assert_eq!(events.len(), 1);
3066         match events[0] {
3067                 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, .. } } => {
3068                         assert!(update_add_htlcs.is_empty());
3069                         assert!(!update_fail_htlcs.is_empty());
3070                         assert!(update_fulfill_htlcs.is_empty());
3071                         assert!(update_fail_malformed_htlcs.is_empty());
3072                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3073                 },
3074                 _ => panic!("Unexpected event"),
3075         };
3076         mine_transaction(&nodes[2], &commitment_tx[0]);
3077         check_closed_broadcast!(nodes[2], true);
3078         check_added_monitors!(nodes[2], 1);
3079         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3080         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3081         assert_eq!(node_txn.len(), 0);
3082
3083         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3084         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3085         mine_transaction(&nodes[1], &commitment_tx[0]);
3086         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3087                 , [nodes[2].node.get_our_node_id()], 100000);
3088         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3089         let timeout_tx = {
3090                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3091                 if nodes[1].connect_style.borrow().skips_blocks() {
3092                         assert_eq!(txn.len(), 1);
3093                 } else {
3094                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3095                 }
3096                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3097                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3098                 txn.remove(0)
3099         };
3100
3101         mine_transaction(&nodes[1], &timeout_tx);
3102         check_added_monitors!(nodes[1], 1);
3103         check_closed_broadcast!(nodes[1], true);
3104
3105         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3106
3107         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 }]);
3108         check_added_monitors!(nodes[1], 1);
3109         let events = nodes[1].node.get_and_clear_pending_msg_events();
3110         assert_eq!(events.len(), 1);
3111         match events[0] {
3112                 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, .. } } => {
3113                         assert!(update_add_htlcs.is_empty());
3114                         assert!(!update_fail_htlcs.is_empty());
3115                         assert!(update_fulfill_htlcs.is_empty());
3116                         assert!(update_fail_malformed_htlcs.is_empty());
3117                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3118                 },
3119                 _ => panic!("Unexpected event"),
3120         };
3121
3122         // Broadcast legit commitment tx from B on A's chain
3123         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3124         check_spends!(commitment_tx[0], chan_1.3);
3125
3126         mine_transaction(&nodes[0], &commitment_tx[0]);
3127         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3128
3129         check_closed_broadcast!(nodes[0], true);
3130         check_added_monitors!(nodes[0], 1);
3131         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3132         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3133         assert_eq!(node_txn.len(), 1);
3134         check_spends!(node_txn[0], commitment_tx[0]);
3135         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3136 }
3137
3138 #[test]
3139 fn test_htlc_on_chain_timeout() {
3140         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3141         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3142         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3143 }
3144
3145 #[test]
3146 fn test_simple_commitment_revoked_fail_backward() {
3147         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3148         // and fail backward accordingly.
3149
3150         let chanmon_cfgs = create_chanmon_cfgs(3);
3151         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3152         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3153         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3154
3155         // Create some initial channels
3156         create_announced_chan_between_nodes(&nodes, 0, 1);
3157         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3158
3159         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3160         // Get the will-be-revoked local txn from nodes[2]
3161         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3162         // Revoke the old state
3163         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3164
3165         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3166
3167         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3168         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3169         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3170         check_added_monitors!(nodes[1], 1);
3171         check_closed_broadcast!(nodes[1], true);
3172
3173         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 }]);
3174         check_added_monitors!(nodes[1], 1);
3175         let events = nodes[1].node.get_and_clear_pending_msg_events();
3176         assert_eq!(events.len(), 1);
3177         match events[0] {
3178                 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, .. } } => {
3179                         assert!(update_add_htlcs.is_empty());
3180                         assert_eq!(update_fail_htlcs.len(), 1);
3181                         assert!(update_fulfill_htlcs.is_empty());
3182                         assert!(update_fail_malformed_htlcs.is_empty());
3183                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3184
3185                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3186                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3187                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3188                 },
3189                 _ => panic!("Unexpected event"),
3190         }
3191 }
3192
3193 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3194         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3195         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3196         // commitment transaction anymore.
3197         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3198         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3199         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3200         // technically disallowed and we should probably handle it reasonably.
3201         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3202         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3203         // transactions:
3204         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3205         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3206         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3207         //   and once they revoke the previous commitment transaction (allowing us to send a new
3208         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3209         let chanmon_cfgs = create_chanmon_cfgs(3);
3210         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3211         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3212         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3213
3214         // Create some initial channels
3215         create_announced_chan_between_nodes(&nodes, 0, 1);
3216         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3217
3218         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3219         // Get the will-be-revoked local txn from nodes[2]
3220         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3221         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3222         // Revoke the old state
3223         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3224
3225         let value = if use_dust {
3226                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3227                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3228                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3229                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3230         } else { 3000000 };
3231
3232         let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3233         let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3234         let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3235
3236         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3237         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3238         check_added_monitors!(nodes[2], 1);
3239         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3240         assert!(updates.update_add_htlcs.is_empty());
3241         assert!(updates.update_fulfill_htlcs.is_empty());
3242         assert!(updates.update_fail_malformed_htlcs.is_empty());
3243         assert_eq!(updates.update_fail_htlcs.len(), 1);
3244         assert!(updates.update_fee.is_none());
3245         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3246         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3247         // Drop the last RAA from 3 -> 2
3248
3249         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3250         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3251         check_added_monitors!(nodes[2], 1);
3252         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3253         assert!(updates.update_add_htlcs.is_empty());
3254         assert!(updates.update_fulfill_htlcs.is_empty());
3255         assert!(updates.update_fail_malformed_htlcs.is_empty());
3256         assert_eq!(updates.update_fail_htlcs.len(), 1);
3257         assert!(updates.update_fee.is_none());
3258         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3259         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3260         check_added_monitors!(nodes[1], 1);
3261         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3262         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3263         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3264         check_added_monitors!(nodes[2], 1);
3265
3266         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3267         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3268         check_added_monitors!(nodes[2], 1);
3269         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3270         assert!(updates.update_add_htlcs.is_empty());
3271         assert!(updates.update_fulfill_htlcs.is_empty());
3272         assert!(updates.update_fail_malformed_htlcs.is_empty());
3273         assert_eq!(updates.update_fail_htlcs.len(), 1);
3274         assert!(updates.update_fee.is_none());
3275         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3276         // At this point first_payment_hash has dropped out of the latest two commitment
3277         // transactions that nodes[1] is tracking...
3278         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3279         check_added_monitors!(nodes[1], 1);
3280         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3281         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3282         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3283         check_added_monitors!(nodes[2], 1);
3284
3285         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3286         // on nodes[2]'s RAA.
3287         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3288         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3289                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3290         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3291         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3292         check_added_monitors!(nodes[1], 0);
3293
3294         if deliver_bs_raa {
3295                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3296                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3297                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3298                 check_added_monitors!(nodes[1], 1);
3299                 let events = nodes[1].node.get_and_clear_pending_events();
3300                 assert_eq!(events.len(), 2);
3301                 match events[0] {
3302                         Event::PendingHTLCsForwardable { .. } => { },
3303                         _ => panic!("Unexpected event"),
3304                 };
3305                 match events[1] {
3306                         Event::HTLCHandlingFailed { .. } => { },
3307                         _ => panic!("Unexpected event"),
3308                 }
3309                 // Deliberately don't process the pending fail-back so they all fail back at once after
3310                 // block connection just like the !deliver_bs_raa case
3311         }
3312
3313         let mut failed_htlcs = HashSet::new();
3314         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3315
3316         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3317         check_added_monitors!(nodes[1], 1);
3318         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3319
3320         let events = nodes[1].node.get_and_clear_pending_events();
3321         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3322         match events[0] {
3323                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3324                 _ => panic!("Unexepected event"),
3325         }
3326         match events[1] {
3327                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3328                         assert_eq!(*payment_hash, fourth_payment_hash);
3329                 },
3330                 _ => panic!("Unexpected event"),
3331         }
3332         match events[2] {
3333                 Event::PaymentFailed { ref payment_hash, .. } => {
3334                         assert_eq!(*payment_hash, fourth_payment_hash);
3335                 },
3336                 _ => panic!("Unexpected event"),
3337         }
3338
3339         nodes[1].node.process_pending_htlc_forwards();
3340         check_added_monitors!(nodes[1], 1);
3341
3342         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3343         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3344
3345         if deliver_bs_raa {
3346                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3347                 match nodes_2_event {
3348                         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, .. } } => {
3349                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3350                                 assert_eq!(update_add_htlcs.len(), 1);
3351                                 assert!(update_fulfill_htlcs.is_empty());
3352                                 assert!(update_fail_htlcs.is_empty());
3353                                 assert!(update_fail_malformed_htlcs.is_empty());
3354                         },
3355                         _ => panic!("Unexpected event"),
3356                 }
3357         }
3358
3359         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3360         match nodes_2_event {
3361                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3362                         assert_eq!(channel_id, chan_2.2);
3363                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3364                 },
3365                 _ => panic!("Unexpected event"),
3366         }
3367
3368         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3369         match nodes_0_event {
3370                 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, .. } } => {
3371                         assert!(update_add_htlcs.is_empty());
3372                         assert_eq!(update_fail_htlcs.len(), 3);
3373                         assert!(update_fulfill_htlcs.is_empty());
3374                         assert!(update_fail_malformed_htlcs.is_empty());
3375                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3376
3377                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3378                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3379                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3380
3381                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3382
3383                         let events = nodes[0].node.get_and_clear_pending_events();
3384                         assert_eq!(events.len(), 6);
3385                         match events[0] {
3386                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3387                                         assert!(failed_htlcs.insert(payment_hash.0));
3388                                         // If we delivered B's RAA we got an unknown preimage error, not something
3389                                         // that we should update our routing table for.
3390                                         if !deliver_bs_raa {
3391                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3392                                         }
3393                                 },
3394                                 _ => panic!("Unexpected event"),
3395                         }
3396                         match events[1] {
3397                                 Event::PaymentFailed { ref payment_hash, .. } => {
3398                                         assert_eq!(*payment_hash, first_payment_hash);
3399                                 },
3400                                 _ => panic!("Unexpected event"),
3401                         }
3402                         match events[2] {
3403                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3404                                         assert!(failed_htlcs.insert(payment_hash.0));
3405                                 },
3406                                 _ => panic!("Unexpected event"),
3407                         }
3408                         match events[3] {
3409                                 Event::PaymentFailed { ref payment_hash, .. } => {
3410                                         assert_eq!(*payment_hash, second_payment_hash);
3411                                 },
3412                                 _ => panic!("Unexpected event"),
3413                         }
3414                         match events[4] {
3415                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3416                                         assert!(failed_htlcs.insert(payment_hash.0));
3417                                 },
3418                                 _ => panic!("Unexpected event"),
3419                         }
3420                         match events[5] {
3421                                 Event::PaymentFailed { ref payment_hash, .. } => {
3422                                         assert_eq!(*payment_hash, third_payment_hash);
3423                                 },
3424                                 _ => panic!("Unexpected event"),
3425                         }
3426                 },
3427                 _ => panic!("Unexpected event"),
3428         }
3429
3430         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3431         match events[0] {
3432                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3433                 _ => panic!("Unexpected event"),
3434         }
3435
3436         assert!(failed_htlcs.contains(&first_payment_hash.0));
3437         assert!(failed_htlcs.contains(&second_payment_hash.0));
3438         assert!(failed_htlcs.contains(&third_payment_hash.0));
3439 }
3440
3441 #[test]
3442 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3443         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3444         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3445         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3446         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3447 }
3448
3449 #[test]
3450 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3451         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3452         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3453         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3454         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3455 }
3456
3457 #[test]
3458 fn fail_backward_pending_htlc_upon_channel_failure() {
3459         let chanmon_cfgs = create_chanmon_cfgs(2);
3460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3462         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3463         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3464
3465         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3466         {
3467                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3468                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3469                         PaymentId(payment_hash.0)).unwrap();
3470                 check_added_monitors!(nodes[0], 1);
3471
3472                 let payment_event = {
3473                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3474                         assert_eq!(events.len(), 1);
3475                         SendEvent::from_event(events.remove(0))
3476                 };
3477                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3478                 assert_eq!(payment_event.msgs.len(), 1);
3479         }
3480
3481         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3482         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3483         {
3484                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3485                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3486                 check_added_monitors!(nodes[0], 0);
3487
3488                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3489         }
3490
3491         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3492         {
3493                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3494
3495                 let secp_ctx = Secp256k1::new();
3496                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3497                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3498                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3499                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3500                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3501                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3502
3503                 // Send a 0-msat update_add_htlc to fail the channel.
3504                 let update_add_htlc = msgs::UpdateAddHTLC {
3505                         channel_id: chan.2,
3506                         htlc_id: 0,
3507                         amount_msat: 0,
3508                         payment_hash,
3509                         cltv_expiry,
3510                         onion_routing_packet,
3511                         skimmed_fee_msat: None,
3512                 };
3513                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3514         }
3515         let events = nodes[0].node.get_and_clear_pending_events();
3516         assert_eq!(events.len(), 3);
3517         // Check that Alice fails backward the pending HTLC from the second payment.
3518         match events[0] {
3519                 Event::PaymentPathFailed { payment_hash, .. } => {
3520                         assert_eq!(payment_hash, failed_payment_hash);
3521                 },
3522                 _ => panic!("Unexpected event"),
3523         }
3524         match events[1] {
3525                 Event::PaymentFailed { payment_hash, .. } => {
3526                         assert_eq!(payment_hash, failed_payment_hash);
3527                 },
3528                 _ => panic!("Unexpected event"),
3529         }
3530         match events[2] {
3531                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3532                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3533                 },
3534                 _ => panic!("Unexpected event {:?}", events[1]),
3535         }
3536         check_closed_broadcast!(nodes[0], true);
3537         check_added_monitors!(nodes[0], 1);
3538 }
3539
3540 #[test]
3541 fn test_htlc_ignore_latest_remote_commitment() {
3542         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3543         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3544         let chanmon_cfgs = create_chanmon_cfgs(2);
3545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3548         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3549                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3550                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3551                 // connect_style.
3552                 return;
3553         }
3554         create_announced_chan_between_nodes(&nodes, 0, 1);
3555
3556         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3557         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3558         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3559         check_closed_broadcast!(nodes[0], true);
3560         check_added_monitors!(nodes[0], 1);
3561         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3562
3563         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3564         assert_eq!(node_txn.len(), 3);
3565         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3566
3567         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3568         connect_block(&nodes[1], &block);
3569         check_closed_broadcast!(nodes[1], true);
3570         check_added_monitors!(nodes[1], 1);
3571         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3572
3573         // Duplicate the connect_block call since this may happen due to other listeners
3574         // registering new transactions
3575         connect_block(&nodes[1], &block);
3576 }
3577
3578 #[test]
3579 fn test_force_close_fail_back() {
3580         // Check which HTLCs are failed-backwards on channel force-closure
3581         let chanmon_cfgs = create_chanmon_cfgs(3);
3582         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3583         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3584         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3585         create_announced_chan_between_nodes(&nodes, 0, 1);
3586         create_announced_chan_between_nodes(&nodes, 1, 2);
3587
3588         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3589
3590         let mut payment_event = {
3591                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3592                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3593                 check_added_monitors!(nodes[0], 1);
3594
3595                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3596                 assert_eq!(events.len(), 1);
3597                 SendEvent::from_event(events.remove(0))
3598         };
3599
3600         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3601         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3602
3603         expect_pending_htlcs_forwardable!(nodes[1]);
3604
3605         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3606         assert_eq!(events_2.len(), 1);
3607         payment_event = SendEvent::from_event(events_2.remove(0));
3608         assert_eq!(payment_event.msgs.len(), 1);
3609
3610         check_added_monitors!(nodes[1], 1);
3611         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3612         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3613         check_added_monitors!(nodes[2], 1);
3614         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3615
3616         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3617         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3618         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3619
3620         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3621         check_closed_broadcast!(nodes[2], true);
3622         check_added_monitors!(nodes[2], 1);
3623         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3624         let tx = {
3625                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3626                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3627                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3628                 // back to nodes[1] upon timeout otherwise.
3629                 assert_eq!(node_txn.len(), 1);
3630                 node_txn.remove(0)
3631         };
3632
3633         mine_transaction(&nodes[1], &tx);
3634
3635         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3636         check_closed_broadcast!(nodes[1], true);
3637         check_added_monitors!(nodes[1], 1);
3638         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3639
3640         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3641         {
3642                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3643                         .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);
3644         }
3645         mine_transaction(&nodes[2], &tx);
3646         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3647         assert_eq!(node_txn.len(), 1);
3648         assert_eq!(node_txn[0].input.len(), 1);
3649         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3650         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3651         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3652
3653         check_spends!(node_txn[0], tx);
3654 }
3655
3656 #[test]
3657 fn test_dup_events_on_peer_disconnect() {
3658         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3659         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3660         // as we used to generate the event immediately upon receipt of the payment preimage in the
3661         // update_fulfill_htlc message.
3662
3663         let chanmon_cfgs = create_chanmon_cfgs(2);
3664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3666         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3667         create_announced_chan_between_nodes(&nodes, 0, 1);
3668
3669         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3670
3671         nodes[1].node.claim_funds(payment_preimage);
3672         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3673         check_added_monitors!(nodes[1], 1);
3674         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3675         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3676         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3677
3678         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3679         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3680
3681         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3682         reconnect_args.pending_htlc_claims.0 = 1;
3683         reconnect_nodes(reconnect_args);
3684         expect_payment_path_successful!(nodes[0]);
3685 }
3686
3687 #[test]
3688 fn test_peer_disconnected_before_funding_broadcasted() {
3689         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3690         // before the funding transaction has been broadcasted.
3691         let chanmon_cfgs = create_chanmon_cfgs(2);
3692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3695
3696         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3697         // broadcasted, even though it's created by `nodes[0]`.
3698         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();
3699         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3700         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3701         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3702         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3703
3704         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3705         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3706
3707         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3708
3709         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3710         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3711
3712         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3713         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3714         // broadcasted.
3715         {
3716                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3717         }
3718
3719         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3720         // disconnected before the funding transaction was broadcasted.
3721         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3722         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3723
3724         check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3725                 , [nodes[1].node.get_our_node_id()], 1000000);
3726         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3727                 , [nodes[0].node.get_our_node_id()], 1000000);
3728 }
3729
3730 #[test]
3731 fn test_simple_peer_disconnect() {
3732         // Test that we can reconnect when there are no lost messages
3733         let chanmon_cfgs = create_chanmon_cfgs(3);
3734         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3735         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3736         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3737         create_announced_chan_between_nodes(&nodes, 0, 1);
3738         create_announced_chan_between_nodes(&nodes, 1, 2);
3739
3740         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3741         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3742         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3743         reconnect_args.send_channel_ready = (true, true);
3744         reconnect_nodes(reconnect_args);
3745
3746         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3747         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3748         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3749         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3750
3751         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3752         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3753         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3754
3755         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3756         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3757         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3758         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3759
3760         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3761         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3762
3763         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3764         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3765
3766         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3767         reconnect_args.pending_cell_htlc_fails.0 = 1;
3768         reconnect_args.pending_cell_htlc_claims.0 = 1;
3769         reconnect_nodes(reconnect_args);
3770         {
3771                 let events = nodes[0].node.get_and_clear_pending_events();
3772                 assert_eq!(events.len(), 4);
3773                 match events[0] {
3774                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3775                                 assert_eq!(payment_preimage, payment_preimage_3);
3776                                 assert_eq!(payment_hash, payment_hash_3);
3777                         },
3778                         _ => panic!("Unexpected event"),
3779                 }
3780                 match events[1] {
3781                         Event::PaymentPathSuccessful { .. } => {},
3782                         _ => panic!("Unexpected event"),
3783                 }
3784                 match events[2] {
3785                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3786                                 assert_eq!(payment_hash, payment_hash_5);
3787                                 assert!(payment_failed_permanently);
3788                         },
3789                         _ => panic!("Unexpected event"),
3790                 }
3791                 match events[3] {
3792                         Event::PaymentFailed { payment_hash, .. } => {
3793                                 assert_eq!(payment_hash, payment_hash_5);
3794                         },
3795                         _ => panic!("Unexpected event"),
3796                 }
3797         }
3798         check_added_monitors(&nodes[0], 1);
3799
3800         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3801         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3802 }
3803
3804 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3805         // Test that we can reconnect when in-flight HTLC updates get dropped
3806         let chanmon_cfgs = create_chanmon_cfgs(2);
3807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3809         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3810
3811         let mut as_channel_ready = None;
3812         let channel_id = if messages_delivered == 0 {
3813                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3814                 as_channel_ready = Some(channel_ready);
3815                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3816                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3817                 // it before the channel_reestablish message.
3818                 chan_id
3819         } else {
3820                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3821         };
3822
3823         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3824
3825         let payment_event = {
3826                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3827                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3828                 check_added_monitors!(nodes[0], 1);
3829
3830                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3831                 assert_eq!(events.len(), 1);
3832                 SendEvent::from_event(events.remove(0))
3833         };
3834         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3835
3836         if messages_delivered < 2 {
3837                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3838         } else {
3839                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3840                 if messages_delivered >= 3 {
3841                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3842                         check_added_monitors!(nodes[1], 1);
3843                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3844
3845                         if messages_delivered >= 4 {
3846                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3847                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3848                                 check_added_monitors!(nodes[0], 1);
3849
3850                                 if messages_delivered >= 5 {
3851                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3852                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3853                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3854                                         check_added_monitors!(nodes[0], 1);
3855
3856                                         if messages_delivered >= 6 {
3857                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3858                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3859                                                 check_added_monitors!(nodes[1], 1);
3860                                         }
3861                                 }
3862                         }
3863                 }
3864         }
3865
3866         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3867         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3868         if messages_delivered < 3 {
3869                 if simulate_broken_lnd {
3870                         // lnd has a long-standing bug where they send a channel_ready prior to a
3871                         // channel_reestablish if you reconnect prior to channel_ready time.
3872                         //
3873                         // Here we simulate that behavior, delivering a channel_ready immediately on
3874                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3875                         // in `reconnect_nodes` but we currently don't fail based on that.
3876                         //
3877                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3878                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3879                 }
3880                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3881                 // received on either side, both sides will need to resend them.
3882                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3883                 reconnect_args.send_channel_ready = (true, true);
3884                 reconnect_args.pending_htlc_adds.1 = 1;
3885                 reconnect_nodes(reconnect_args);
3886         } else if messages_delivered == 3 {
3887                 // nodes[0] still wants its RAA + commitment_signed
3888                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3889                 reconnect_args.pending_responding_commitment_signed.0 = true;
3890                 reconnect_args.pending_raa.0 = true;
3891                 reconnect_nodes(reconnect_args);
3892         } else if messages_delivered == 4 {
3893                 // nodes[0] still wants its commitment_signed
3894                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3895                 reconnect_args.pending_responding_commitment_signed.0 = true;
3896                 reconnect_nodes(reconnect_args);
3897         } else if messages_delivered == 5 {
3898                 // nodes[1] still wants its final RAA
3899                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3900                 reconnect_args.pending_raa.1 = true;
3901                 reconnect_nodes(reconnect_args);
3902         } else if messages_delivered == 6 {
3903                 // Everything was delivered...
3904                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3905         }
3906
3907         let events_1 = nodes[1].node.get_and_clear_pending_events();
3908         if messages_delivered == 0 {
3909                 assert_eq!(events_1.len(), 2);
3910                 match events_1[0] {
3911                         Event::ChannelReady { .. } => { },
3912                         _ => panic!("Unexpected event"),
3913                 };
3914                 match events_1[1] {
3915                         Event::PendingHTLCsForwardable { .. } => { },
3916                         _ => panic!("Unexpected event"),
3917                 };
3918         } else {
3919                 assert_eq!(events_1.len(), 1);
3920                 match events_1[0] {
3921                         Event::PendingHTLCsForwardable { .. } => { },
3922                         _ => panic!("Unexpected event"),
3923                 };
3924         }
3925
3926         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3927         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3928         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3929
3930         nodes[1].node.process_pending_htlc_forwards();
3931
3932         let events_2 = nodes[1].node.get_and_clear_pending_events();
3933         assert_eq!(events_2.len(), 1);
3934         match events_2[0] {
3935                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3936                         assert_eq!(payment_hash_1, *payment_hash);
3937                         assert_eq!(amount_msat, 1_000_000);
3938                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3939                         assert_eq!(via_channel_id, Some(channel_id));
3940                         match &purpose {
3941                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3942                                         assert!(payment_preimage.is_none());
3943                                         assert_eq!(payment_secret_1, *payment_secret);
3944                                 },
3945                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3946                         }
3947                 },
3948                 _ => panic!("Unexpected event"),
3949         }
3950
3951         nodes[1].node.claim_funds(payment_preimage_1);
3952         check_added_monitors!(nodes[1], 1);
3953         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3954
3955         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3956         assert_eq!(events_3.len(), 1);
3957         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3958                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3959                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3960                         assert!(updates.update_add_htlcs.is_empty());
3961                         assert!(updates.update_fail_htlcs.is_empty());
3962                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3963                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3964                         assert!(updates.update_fee.is_none());
3965                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3966                 },
3967                 _ => panic!("Unexpected event"),
3968         };
3969
3970         if messages_delivered >= 1 {
3971                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3972
3973                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3974                 assert_eq!(events_4.len(), 1);
3975                 match events_4[0] {
3976                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3977                                 assert_eq!(payment_preimage_1, *payment_preimage);
3978                                 assert_eq!(payment_hash_1, *payment_hash);
3979                         },
3980                         _ => panic!("Unexpected event"),
3981                 }
3982
3983                 if messages_delivered >= 2 {
3984                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3985                         check_added_monitors!(nodes[0], 1);
3986                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3987
3988                         if messages_delivered >= 3 {
3989                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3990                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3991                                 check_added_monitors!(nodes[1], 1);
3992
3993                                 if messages_delivered >= 4 {
3994                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3995                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3996                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3997                                         check_added_monitors!(nodes[1], 1);
3998
3999                                         if messages_delivered >= 5 {
4000                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4001                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4002                                                 check_added_monitors!(nodes[0], 1);
4003                                         }
4004                                 }
4005                         }
4006                 }
4007         }
4008
4009         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4010         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4011         if messages_delivered < 2 {
4012                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4013                 reconnect_args.pending_htlc_claims.0 = 1;
4014                 reconnect_nodes(reconnect_args);
4015                 if messages_delivered < 1 {
4016                         expect_payment_sent!(nodes[0], payment_preimage_1);
4017                 } else {
4018                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4019                 }
4020         } else if messages_delivered == 2 {
4021                 // nodes[0] still wants its RAA + commitment_signed
4022                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4023                 reconnect_args.pending_responding_commitment_signed.1 = true;
4024                 reconnect_args.pending_raa.1 = true;
4025                 reconnect_nodes(reconnect_args);
4026         } else if messages_delivered == 3 {
4027                 // nodes[0] still wants its commitment_signed
4028                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4029                 reconnect_args.pending_responding_commitment_signed.1 = true;
4030                 reconnect_nodes(reconnect_args);
4031         } else if messages_delivered == 4 {
4032                 // nodes[1] still wants its final RAA
4033                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4034                 reconnect_args.pending_raa.0 = true;
4035                 reconnect_nodes(reconnect_args);
4036         } else if messages_delivered == 5 {
4037                 // Everything was delivered...
4038                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4039         }
4040
4041         if messages_delivered == 1 || messages_delivered == 2 {
4042                 expect_payment_path_successful!(nodes[0]);
4043         }
4044         if messages_delivered <= 5 {
4045                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4046                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4047         }
4048         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4049
4050         if messages_delivered > 2 {
4051                 expect_payment_path_successful!(nodes[0]);
4052         }
4053
4054         // Channel should still work fine...
4055         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4056         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4057         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4058 }
4059
4060 #[test]
4061 fn test_drop_messages_peer_disconnect_a() {
4062         do_test_drop_messages_peer_disconnect(0, true);
4063         do_test_drop_messages_peer_disconnect(0, false);
4064         do_test_drop_messages_peer_disconnect(1, false);
4065         do_test_drop_messages_peer_disconnect(2, false);
4066 }
4067
4068 #[test]
4069 fn test_drop_messages_peer_disconnect_b() {
4070         do_test_drop_messages_peer_disconnect(3, false);
4071         do_test_drop_messages_peer_disconnect(4, false);
4072         do_test_drop_messages_peer_disconnect(5, false);
4073         do_test_drop_messages_peer_disconnect(6, false);
4074 }
4075
4076 #[test]
4077 fn test_channel_ready_without_best_block_updated() {
4078         // Previously, if we were offline when a funding transaction was locked in, and then we came
4079         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4080         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4081         // channel_ready immediately instead.
4082         let chanmon_cfgs = create_chanmon_cfgs(2);
4083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4085         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4086         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4087
4088         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4089
4090         let conf_height = nodes[0].best_block_info().1 + 1;
4091         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4092         let block_txn = [funding_tx];
4093         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4094         let conf_block_header = nodes[0].get_block_header(conf_height);
4095         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4096
4097         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4098         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4099         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4100 }
4101
4102 #[test]
4103 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4104         let chanmon_cfgs = create_chanmon_cfgs(2);
4105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4107         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4108
4109         // Let channel_manager get ahead of chain_monitor by 1 block.
4110         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4111         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4112         let height_1 = nodes[0].best_block_info().1 + 1;
4113         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4114
4115         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4116         nodes[0].node.block_connected(&block_1, height_1);
4117
4118         // Create channel, and it gets added to chain_monitor in funding_created.
4119         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4120
4121         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4122         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4123         // was running ahead of chain_monitor at the time of funding_created.
4124         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4125         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4126         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4127         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4128
4129         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4130         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4131         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4132 }
4133
4134 #[test]
4135 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4136         let chanmon_cfgs = create_chanmon_cfgs(2);
4137         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4138         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4139         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4140
4141         // Let chain_monitor get ahead of channel_manager by 1 block.
4142         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4143         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4144         let height_1 = nodes[0].best_block_info().1 + 1;
4145         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4146
4147         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4148         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4149
4150         // Create channel, and it gets added to chain_monitor in funding_created.
4151         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4152
4153         // channel_manager can't really skip block_1, it should get it eventually.
4154         nodes[0].node.block_connected(&block_1, height_1);
4155
4156         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4157         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4158         // running behind at the time of funding_created.
4159         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4160         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4161         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4162         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4163
4164         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4165         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4166         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4167 }
4168
4169 #[test]
4170 fn test_drop_messages_peer_disconnect_dual_htlc() {
4171         // Test that we can handle reconnecting when both sides of a channel have pending
4172         // commitment_updates when we disconnect.
4173         let chanmon_cfgs = create_chanmon_cfgs(2);
4174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4176         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4177         create_announced_chan_between_nodes(&nodes, 0, 1);
4178
4179         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4180
4181         // Now try to send a second payment which will fail to send
4182         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4183         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4184                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4185         check_added_monitors!(nodes[0], 1);
4186
4187         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4188         assert_eq!(events_1.len(), 1);
4189         match events_1[0] {
4190                 MessageSendEvent::UpdateHTLCs { .. } => {},
4191                 _ => panic!("Unexpected event"),
4192         }
4193
4194         nodes[1].node.claim_funds(payment_preimage_1);
4195         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4196         check_added_monitors!(nodes[1], 1);
4197
4198         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4199         assert_eq!(events_2.len(), 1);
4200         match events_2[0] {
4201                 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 } } => {
4202                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4203                         assert!(update_add_htlcs.is_empty());
4204                         assert_eq!(update_fulfill_htlcs.len(), 1);
4205                         assert!(update_fail_htlcs.is_empty());
4206                         assert!(update_fail_malformed_htlcs.is_empty());
4207                         assert!(update_fee.is_none());
4208
4209                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4210                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4211                         assert_eq!(events_3.len(), 1);
4212                         match events_3[0] {
4213                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4214                                         assert_eq!(*payment_preimage, payment_preimage_1);
4215                                         assert_eq!(*payment_hash, payment_hash_1);
4216                                 },
4217                                 _ => panic!("Unexpected event"),
4218                         }
4219
4220                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4221                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4222                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4223                         check_added_monitors!(nodes[0], 1);
4224                 },
4225                 _ => panic!("Unexpected event"),
4226         }
4227
4228         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4229         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4230
4231         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4232                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4233         }, true).unwrap();
4234         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4235         assert_eq!(reestablish_1.len(), 1);
4236         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4237                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4238         }, false).unwrap();
4239         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4240         assert_eq!(reestablish_2.len(), 1);
4241
4242         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4243         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4244         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4245         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4246
4247         assert!(as_resp.0.is_none());
4248         assert!(bs_resp.0.is_none());
4249
4250         assert!(bs_resp.1.is_none());
4251         assert!(bs_resp.2.is_none());
4252
4253         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4254
4255         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4256         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4257         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4258         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4259         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4260         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4261         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4262         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4263         // No commitment_signed so get_event_msg's assert(len == 1) passes
4264         check_added_monitors!(nodes[1], 1);
4265
4266         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4267         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4268         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4269         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4270         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4271         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4272         assert!(bs_second_commitment_signed.update_fee.is_none());
4273         check_added_monitors!(nodes[1], 1);
4274
4275         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4276         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4277         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4278         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4279         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4280         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4281         assert!(as_commitment_signed.update_fee.is_none());
4282         check_added_monitors!(nodes[0], 1);
4283
4284         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4285         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4286         // No commitment_signed so get_event_msg's assert(len == 1) passes
4287         check_added_monitors!(nodes[0], 1);
4288
4289         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4290         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4291         // No commitment_signed so get_event_msg's assert(len == 1) passes
4292         check_added_monitors!(nodes[1], 1);
4293
4294         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4295         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4296         check_added_monitors!(nodes[1], 1);
4297
4298         expect_pending_htlcs_forwardable!(nodes[1]);
4299
4300         let events_5 = nodes[1].node.get_and_clear_pending_events();
4301         assert_eq!(events_5.len(), 1);
4302         match events_5[0] {
4303                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4304                         assert_eq!(payment_hash_2, *payment_hash);
4305                         match &purpose {
4306                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4307                                         assert!(payment_preimage.is_none());
4308                                         assert_eq!(payment_secret_2, *payment_secret);
4309                                 },
4310                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4311                         }
4312                 },
4313                 _ => panic!("Unexpected event"),
4314         }
4315
4316         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4317         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4318         check_added_monitors!(nodes[0], 1);
4319
4320         expect_payment_path_successful!(nodes[0]);
4321         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4322 }
4323
4324 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4325         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4326         // to avoid our counterparty failing the channel.
4327         let chanmon_cfgs = create_chanmon_cfgs(2);
4328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4330         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4331
4332         create_announced_chan_between_nodes(&nodes, 0, 1);
4333
4334         let our_payment_hash = if send_partial_mpp {
4335                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4336                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4337                 // indicates there are more HTLCs coming.
4338                 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.
4339                 let payment_id = PaymentId([42; 32]);
4340                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4341                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4342                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4343                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4344                         &None, session_privs[0]).unwrap();
4345                 check_added_monitors!(nodes[0], 1);
4346                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4347                 assert_eq!(events.len(), 1);
4348                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4349                 // hop should *not* yet generate any PaymentClaimable event(s).
4350                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4351                 our_payment_hash
4352         } else {
4353                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4354         };
4355
4356         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4357         connect_block(&nodes[0], &block);
4358         connect_block(&nodes[1], &block);
4359         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4360         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4361                 block.header.prev_blockhash = block.block_hash();
4362                 connect_block(&nodes[0], &block);
4363                 connect_block(&nodes[1], &block);
4364         }
4365
4366         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4367
4368         check_added_monitors!(nodes[1], 1);
4369         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4370         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4371         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4372         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4373         assert!(htlc_timeout_updates.update_fee.is_none());
4374
4375         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4376         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4377         // 100_000 msat as u64, followed by the height at which we failed back above
4378         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4379         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4380         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4381 }
4382
4383 #[test]
4384 fn test_htlc_timeout() {
4385         do_test_htlc_timeout(true);
4386         do_test_htlc_timeout(false);
4387 }
4388
4389 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4390         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4391         let chanmon_cfgs = create_chanmon_cfgs(3);
4392         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4393         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4394         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4395         create_announced_chan_between_nodes(&nodes, 0, 1);
4396         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4397
4398         // Make sure all nodes are at the same starting height
4399         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4400         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4401         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4402
4403         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4404         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4405         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4406                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4407         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4408         check_added_monitors!(nodes[1], 1);
4409
4410         // Now attempt to route a second payment, which should be placed in the holding cell
4411         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4412         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4413         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4414                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4415         if forwarded_htlc {
4416                 check_added_monitors!(nodes[0], 1);
4417                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4418                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4419                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4420                 expect_pending_htlcs_forwardable!(nodes[1]);
4421         }
4422         check_added_monitors!(nodes[1], 0);
4423
4424         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4425         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4426         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4427         connect_blocks(&nodes[1], 1);
4428
4429         if forwarded_htlc {
4430                 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 }]);
4431                 check_added_monitors!(nodes[1], 1);
4432                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4433                 assert_eq!(fail_commit.len(), 1);
4434                 match fail_commit[0] {
4435                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4436                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4437                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4438                         },
4439                         _ => unreachable!(),
4440                 }
4441                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4442         } else {
4443                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4444         }
4445 }
4446
4447 #[test]
4448 fn test_holding_cell_htlc_add_timeouts() {
4449         do_test_holding_cell_htlc_add_timeouts(false);
4450         do_test_holding_cell_htlc_add_timeouts(true);
4451 }
4452
4453 macro_rules! check_spendable_outputs {
4454         ($node: expr, $keysinterface: expr) => {
4455                 {
4456                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4457                         let mut txn = Vec::new();
4458                         let mut all_outputs = Vec::new();
4459                         let secp_ctx = Secp256k1::new();
4460                         for event in events.drain(..) {
4461                                 match event {
4462                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4463                                                 for outp in outputs.drain(..) {
4464                                                         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());
4465                                                         all_outputs.push(outp);
4466                                                 }
4467                                         },
4468                                         _ => panic!("Unexpected event"),
4469                                 };
4470                         }
4471                         if all_outputs.len() > 1 {
4472                                 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) {
4473                                         txn.push(tx);
4474                                 }
4475                         }
4476                         txn
4477                 }
4478         }
4479 }
4480
4481 #[test]
4482 fn test_claim_sizeable_push_msat() {
4483         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4484         let chanmon_cfgs = create_chanmon_cfgs(2);
4485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4487         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4488
4489         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4490         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4491         check_closed_broadcast!(nodes[1], true);
4492         check_added_monitors!(nodes[1], 1);
4493         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4494         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4495         assert_eq!(node_txn.len(), 1);
4496         check_spends!(node_txn[0], chan.3);
4497         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
4498
4499         mine_transaction(&nodes[1], &node_txn[0]);
4500         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4501
4502         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4503         assert_eq!(spend_txn.len(), 1);
4504         assert_eq!(spend_txn[0].input.len(), 1);
4505         check_spends!(spend_txn[0], node_txn[0]);
4506         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4507 }
4508
4509 #[test]
4510 fn test_claim_on_remote_sizeable_push_msat() {
4511         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4512         // to_remote output is encumbered by a P2WPKH
4513         let chanmon_cfgs = create_chanmon_cfgs(2);
4514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4517
4518         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4519         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4520         check_closed_broadcast!(nodes[0], true);
4521         check_added_monitors!(nodes[0], 1);
4522         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4523
4524         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4525         assert_eq!(node_txn.len(), 1);
4526         check_spends!(node_txn[0], chan.3);
4527         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
4528
4529         mine_transaction(&nodes[1], &node_txn[0]);
4530         check_closed_broadcast!(nodes[1], true);
4531         check_added_monitors!(nodes[1], 1);
4532         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4533         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4534
4535         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4536         assert_eq!(spend_txn.len(), 1);
4537         check_spends!(spend_txn[0], node_txn[0]);
4538 }
4539
4540 #[test]
4541 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4542         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4543         // to_remote output is encumbered by a P2WPKH
4544
4545         let chanmon_cfgs = create_chanmon_cfgs(2);
4546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4548         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4549
4550         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4551         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4552         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4553         assert_eq!(revoked_local_txn[0].input.len(), 1);
4554         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4555
4556         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4557         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4558         check_closed_broadcast!(nodes[1], true);
4559         check_added_monitors!(nodes[1], 1);
4560         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4561
4562         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4563         mine_transaction(&nodes[1], &node_txn[0]);
4564         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4565
4566         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4567         assert_eq!(spend_txn.len(), 3);
4568         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4569         check_spends!(spend_txn[1], node_txn[0]);
4570         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4571 }
4572
4573 #[test]
4574 fn test_static_spendable_outputs_preimage_tx() {
4575         let chanmon_cfgs = create_chanmon_cfgs(2);
4576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4579
4580         // Create some initial channels
4581         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4582
4583         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4584
4585         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4586         assert_eq!(commitment_tx[0].input.len(), 1);
4587         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4588
4589         // Settle A's commitment tx on B's chain
4590         nodes[1].node.claim_funds(payment_preimage);
4591         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4592         check_added_monitors!(nodes[1], 1);
4593         mine_transaction(&nodes[1], &commitment_tx[0]);
4594         check_added_monitors!(nodes[1], 1);
4595         let events = nodes[1].node.get_and_clear_pending_msg_events();
4596         match events[0] {
4597                 MessageSendEvent::UpdateHTLCs { .. } => {},
4598                 _ => panic!("Unexpected event"),
4599         }
4600         match events[1] {
4601                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4602                 _ => panic!("Unexepected event"),
4603         }
4604
4605         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4606         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4607         assert_eq!(node_txn.len(), 1);
4608         check_spends!(node_txn[0], commitment_tx[0]);
4609         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4610
4611         mine_transaction(&nodes[1], &node_txn[0]);
4612         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4613         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4614
4615         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4616         assert_eq!(spend_txn.len(), 1);
4617         check_spends!(spend_txn[0], node_txn[0]);
4618 }
4619
4620 #[test]
4621 fn test_static_spendable_outputs_timeout_tx() {
4622         let chanmon_cfgs = create_chanmon_cfgs(2);
4623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4625         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4626
4627         // Create some initial channels
4628         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4629
4630         // Rebalance the network a bit by relaying one payment through all the channels ...
4631         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4632
4633         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4634
4635         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4636         assert_eq!(commitment_tx[0].input.len(), 1);
4637         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4638
4639         // Settle A's commitment tx on B' chain
4640         mine_transaction(&nodes[1], &commitment_tx[0]);
4641         check_added_monitors!(nodes[1], 1);
4642         let events = nodes[1].node.get_and_clear_pending_msg_events();
4643         match events[0] {
4644                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4645                 _ => panic!("Unexpected event"),
4646         }
4647         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4648
4649         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4650         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4651         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4652         check_spends!(node_txn[0],  commitment_tx[0].clone());
4653         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4654
4655         mine_transaction(&nodes[1], &node_txn[0]);
4656         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4657         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4658         expect_payment_failed!(nodes[1], our_payment_hash, false);
4659
4660         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4661         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4662         check_spends!(spend_txn[0], commitment_tx[0]);
4663         check_spends!(spend_txn[1], node_txn[0]);
4664         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4665 }
4666
4667 #[test]
4668 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4669         let chanmon_cfgs = create_chanmon_cfgs(2);
4670         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4671         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4672         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4673
4674         // Create some initial channels
4675         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4676
4677         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4678         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4679         assert_eq!(revoked_local_txn[0].input.len(), 1);
4680         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4681
4682         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4683
4684         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4685         check_closed_broadcast!(nodes[1], true);
4686         check_added_monitors!(nodes[1], 1);
4687         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4688
4689         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4690         assert_eq!(node_txn.len(), 1);
4691         assert_eq!(node_txn[0].input.len(), 2);
4692         check_spends!(node_txn[0], revoked_local_txn[0]);
4693
4694         mine_transaction(&nodes[1], &node_txn[0]);
4695         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4696
4697         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4698         assert_eq!(spend_txn.len(), 1);
4699         check_spends!(spend_txn[0], node_txn[0]);
4700 }
4701
4702 #[test]
4703 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4704         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4705         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4706         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4707         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4708         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4709
4710         // Create some initial channels
4711         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4712
4713         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4714         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4715         assert_eq!(revoked_local_txn[0].input.len(), 1);
4716         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4717
4718         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4719
4720         // A will generate HTLC-Timeout from revoked commitment tx
4721         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4722         check_closed_broadcast!(nodes[0], true);
4723         check_added_monitors!(nodes[0], 1);
4724         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4725         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4726
4727         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4728         assert_eq!(revoked_htlc_txn.len(), 1);
4729         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4730         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4731         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4732         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4733
4734         // B will generate justice tx from A's revoked commitment/HTLC tx
4735         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4736         check_closed_broadcast!(nodes[1], true);
4737         check_added_monitors!(nodes[1], 1);
4738         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4739
4740         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4741         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4742         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4743         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4744         // transactions next...
4745         assert_eq!(node_txn[0].input.len(), 3);
4746         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4747
4748         assert_eq!(node_txn[1].input.len(), 2);
4749         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4750         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4751                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4752         } else {
4753                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4754                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4755         }
4756
4757         mine_transaction(&nodes[1], &node_txn[1]);
4758         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4759
4760         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4761         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4762         assert_eq!(spend_txn.len(), 1);
4763         assert_eq!(spend_txn[0].input.len(), 1);
4764         check_spends!(spend_txn[0], node_txn[1]);
4765 }
4766
4767 #[test]
4768 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4769         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4770         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4773         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4774
4775         // Create some initial channels
4776         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4777
4778         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4779         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4780         assert_eq!(revoked_local_txn[0].input.len(), 1);
4781         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4782
4783         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4784         assert_eq!(revoked_local_txn[0].output.len(), 2);
4785
4786         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4787
4788         // B will generate HTLC-Success from revoked commitment tx
4789         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4790         check_closed_broadcast!(nodes[1], true);
4791         check_added_monitors!(nodes[1], 1);
4792         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4793         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4794
4795         assert_eq!(revoked_htlc_txn.len(), 1);
4796         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4797         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4798         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4799
4800         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4801         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4802         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4803
4804         // A will generate justice tx from B's revoked commitment/HTLC tx
4805         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4806         check_closed_broadcast!(nodes[0], true);
4807         check_added_monitors!(nodes[0], 1);
4808         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4809
4810         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4811         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4812
4813         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4814         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4815         // transactions next...
4816         assert_eq!(node_txn[0].input.len(), 2);
4817         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4818         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4819                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4820         } else {
4821                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4822                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4823         }
4824
4825         assert_eq!(node_txn[1].input.len(), 1);
4826         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4827
4828         mine_transaction(&nodes[0], &node_txn[1]);
4829         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4830
4831         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4832         // didn't try to generate any new transactions.
4833
4834         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4835         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4836         assert_eq!(spend_txn.len(), 3);
4837         assert_eq!(spend_txn[0].input.len(), 1);
4838         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4839         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4840         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4841         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4842 }
4843
4844 #[test]
4845 fn test_onchain_to_onchain_claim() {
4846         // Test that in case of channel closure, we detect the state of output and claim HTLC
4847         // on downstream peer's remote commitment tx.
4848         // First, have C claim an HTLC against its own latest commitment transaction.
4849         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4850         // channel.
4851         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4852         // gets broadcast.
4853
4854         let chanmon_cfgs = create_chanmon_cfgs(3);
4855         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4856         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4857         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4858
4859         // Create some initial channels
4860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4861         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4862
4863         // Ensure all nodes are at the same height
4864         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4865         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4866         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4867         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4868
4869         // Rebalance the network a bit by relaying one payment through all the channels ...
4870         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4871         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4872
4873         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4874         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4875         check_spends!(commitment_tx[0], chan_2.3);
4876         nodes[2].node.claim_funds(payment_preimage);
4877         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4878         check_added_monitors!(nodes[2], 1);
4879         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4880         assert!(updates.update_add_htlcs.is_empty());
4881         assert!(updates.update_fail_htlcs.is_empty());
4882         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4883         assert!(updates.update_fail_malformed_htlcs.is_empty());
4884
4885         mine_transaction(&nodes[2], &commitment_tx[0]);
4886         check_closed_broadcast!(nodes[2], true);
4887         check_added_monitors!(nodes[2], 1);
4888         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4889
4890         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4891         assert_eq!(c_txn.len(), 1);
4892         check_spends!(c_txn[0], commitment_tx[0]);
4893         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4894         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4895         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4896
4897         // 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
4898         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4899         check_added_monitors!(nodes[1], 1);
4900         let events = nodes[1].node.get_and_clear_pending_events();
4901         assert_eq!(events.len(), 2);
4902         match events[0] {
4903                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4904                 _ => panic!("Unexpected event"),
4905         }
4906         match events[1] {
4907                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4908                         assert_eq!(fee_earned_msat, Some(1000));
4909                         assert_eq!(prev_channel_id, Some(chan_1.2));
4910                         assert_eq!(claim_from_onchain_tx, true);
4911                         assert_eq!(next_channel_id, Some(chan_2.2));
4912                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4913                 },
4914                 _ => panic!("Unexpected event"),
4915         }
4916         check_added_monitors!(nodes[1], 1);
4917         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4918         assert_eq!(msg_events.len(), 3);
4919         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4920         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4921
4922         match nodes_2_event {
4923                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4924                 _ => panic!("Unexpected event"),
4925         }
4926
4927         match nodes_0_event {
4928                 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, .. } } => {
4929                         assert!(update_add_htlcs.is_empty());
4930                         assert!(update_fail_htlcs.is_empty());
4931                         assert_eq!(update_fulfill_htlcs.len(), 1);
4932                         assert!(update_fail_malformed_htlcs.is_empty());
4933                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4934                 },
4935                 _ => panic!("Unexpected event"),
4936         };
4937
4938         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4939         match msg_events[0] {
4940                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4941                 _ => panic!("Unexpected event"),
4942         }
4943
4944         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4945         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4946         mine_transaction(&nodes[1], &commitment_tx[0]);
4947         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4948         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4949         // ChannelMonitor: HTLC-Success tx
4950         assert_eq!(b_txn.len(), 1);
4951         check_spends!(b_txn[0], commitment_tx[0]);
4952         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4953         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4954         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4955
4956         check_closed_broadcast!(nodes[1], true);
4957         check_added_monitors!(nodes[1], 1);
4958 }
4959
4960 #[test]
4961 fn test_duplicate_payment_hash_one_failure_one_success() {
4962         // Topology : A --> B --> C --> D
4963         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4964         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4965         // we forward one of the payments onwards to D.
4966         let chanmon_cfgs = create_chanmon_cfgs(4);
4967         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4968         // When this test was written, the default base fee floated based on the HTLC count.
4969         // It is now fixed, so we simply set the fee to the expected value here.
4970         let mut config = test_default_channel_config();
4971         config.channel_config.forwarding_fee_base_msat = 196;
4972         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4973                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4974         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4975
4976         create_announced_chan_between_nodes(&nodes, 0, 1);
4977         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4978         create_announced_chan_between_nodes(&nodes, 2, 3);
4979
4980         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4981         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4982         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4983         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4984         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4985
4986         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4987
4988         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4989         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4990         // script push size limit so that the below script length checks match
4991         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4992         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4993                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
4994         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4995         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4996
4997         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4998         assert_eq!(commitment_txn[0].input.len(), 1);
4999         check_spends!(commitment_txn[0], chan_2.3);
5000
5001         mine_transaction(&nodes[1], &commitment_txn[0]);
5002         check_closed_broadcast!(nodes[1], true);
5003         check_added_monitors!(nodes[1], 1);
5004         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5005         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5006
5007         let htlc_timeout_tx;
5008         { // Extract one of the two HTLC-Timeout transaction
5009                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5010                 // ChannelMonitor: timeout tx * 2-or-3
5011                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5012
5013                 check_spends!(node_txn[0], commitment_txn[0]);
5014                 assert_eq!(node_txn[0].input.len(), 1);
5015                 assert_eq!(node_txn[0].output.len(), 1);
5016
5017                 if node_txn.len() > 2 {
5018                         check_spends!(node_txn[1], commitment_txn[0]);
5019                         assert_eq!(node_txn[1].input.len(), 1);
5020                         assert_eq!(node_txn[1].output.len(), 1);
5021                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5022
5023                         check_spends!(node_txn[2], commitment_txn[0]);
5024                         assert_eq!(node_txn[2].input.len(), 1);
5025                         assert_eq!(node_txn[2].output.len(), 1);
5026                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5027                 } else {
5028                         check_spends!(node_txn[1], commitment_txn[0]);
5029                         assert_eq!(node_txn[1].input.len(), 1);
5030                         assert_eq!(node_txn[1].output.len(), 1);
5031                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5032                 }
5033
5034                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5035                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5036                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5037                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5038                 if node_txn.len() > 2 {
5039                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5040                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5041                 } else {
5042                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5043                 }
5044         }
5045
5046         nodes[2].node.claim_funds(our_payment_preimage);
5047         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5048
5049         mine_transaction(&nodes[2], &commitment_txn[0]);
5050         check_added_monitors!(nodes[2], 2);
5051         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5052         let events = nodes[2].node.get_and_clear_pending_msg_events();
5053         match events[0] {
5054                 MessageSendEvent::UpdateHTLCs { .. } => {},
5055                 _ => panic!("Unexpected event"),
5056         }
5057         match events[1] {
5058                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5059                 _ => panic!("Unexepected event"),
5060         }
5061         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5062         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5063         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5064         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5065         assert_eq!(htlc_success_txn[0].input.len(), 1);
5066         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5067         assert_eq!(htlc_success_txn[1].input.len(), 1);
5068         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5069         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5070         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5071
5072         mine_transaction(&nodes[1], &htlc_timeout_tx);
5073         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5074         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 }]);
5075         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5076         assert!(htlc_updates.update_add_htlcs.is_empty());
5077         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5078         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5079         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5080         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5081         check_added_monitors!(nodes[1], 1);
5082
5083         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5084         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5085         {
5086                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5087         }
5088         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5089
5090         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5091         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5092         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5093         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5094         assert!(updates.update_add_htlcs.is_empty());
5095         assert!(updates.update_fail_htlcs.is_empty());
5096         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5097         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5098         assert!(updates.update_fail_malformed_htlcs.is_empty());
5099         check_added_monitors!(nodes[1], 1);
5100
5101         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5102         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5103         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5104 }
5105
5106 #[test]
5107 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5108         let chanmon_cfgs = create_chanmon_cfgs(2);
5109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5110         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5111         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5112
5113         // Create some initial channels
5114         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5115
5116         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5117         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5118         assert_eq!(local_txn.len(), 1);
5119         assert_eq!(local_txn[0].input.len(), 1);
5120         check_spends!(local_txn[0], chan_1.3);
5121
5122         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5123         nodes[1].node.claim_funds(payment_preimage);
5124         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5125         check_added_monitors!(nodes[1], 1);
5126
5127         mine_transaction(&nodes[1], &local_txn[0]);
5128         check_added_monitors!(nodes[1], 1);
5129         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5130         let events = nodes[1].node.get_and_clear_pending_msg_events();
5131         match events[0] {
5132                 MessageSendEvent::UpdateHTLCs { .. } => {},
5133                 _ => panic!("Unexpected event"),
5134         }
5135         match events[1] {
5136                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5137                 _ => panic!("Unexepected event"),
5138         }
5139         let node_tx = {
5140                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5141                 assert_eq!(node_txn.len(), 1);
5142                 assert_eq!(node_txn[0].input.len(), 1);
5143                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5144                 check_spends!(node_txn[0], local_txn[0]);
5145                 node_txn[0].clone()
5146         };
5147
5148         mine_transaction(&nodes[1], &node_tx);
5149         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5150
5151         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5152         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5153         assert_eq!(spend_txn.len(), 1);
5154         assert_eq!(spend_txn[0].input.len(), 1);
5155         check_spends!(spend_txn[0], node_tx);
5156         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5157 }
5158
5159 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5160         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5161         // unrevoked commitment transaction.
5162         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5163         // a remote RAA before they could be failed backwards (and combinations thereof).
5164         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5165         // use the same payment hashes.
5166         // Thus, we use a six-node network:
5167         //
5168         // A \         / E
5169         //    - C - D -
5170         // B /         \ F
5171         // And test where C fails back to A/B when D announces its latest commitment transaction
5172         let chanmon_cfgs = create_chanmon_cfgs(6);
5173         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5174         // When this test was written, the default base fee floated based on the HTLC count.
5175         // It is now fixed, so we simply set the fee to the expected value here.
5176         let mut config = test_default_channel_config();
5177         config.channel_config.forwarding_fee_base_msat = 196;
5178         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5179                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5180         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5181
5182         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5183         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5184         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5185         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5186         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5187
5188         // Rebalance and check output sanity...
5189         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5190         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5191         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5192
5193         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5194                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5195         // 0th HTLC:
5196         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
5197         // 1st HTLC:
5198         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
5199         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5200         // 2nd HTLC:
5201         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
5202         // 3rd HTLC:
5203         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
5204         // 4th HTLC:
5205         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5206         // 5th HTLC:
5207         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5208         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5209         // 6th HTLC:
5210         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());
5211         // 7th HTLC:
5212         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());
5213
5214         // 8th HTLC:
5215         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5216         // 9th HTLC:
5217         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5218         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
5219
5220         // 10th HTLC:
5221         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
5222         // 11th HTLC:
5223         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5224         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());
5225
5226         // Double-check that six of the new HTLC were added
5227         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5228         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5229         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5230         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5231
5232         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5233         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5234         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5235         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5236         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5237         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5238         check_added_monitors!(nodes[4], 0);
5239
5240         let failed_destinations = vec![
5241                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5242                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5243                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5244                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5245         ];
5246         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5247         check_added_monitors!(nodes[4], 1);
5248
5249         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5250         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5251         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5252         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5253         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5254         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5255
5256         // Fail 3rd below-dust and 7th above-dust HTLCs
5257         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5258         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5259         check_added_monitors!(nodes[5], 0);
5260
5261         let failed_destinations_2 = vec![
5262                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5263                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5264         ];
5265         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5266         check_added_monitors!(nodes[5], 1);
5267
5268         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5269         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5270         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5271         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5272
5273         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5274
5275         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5276         let failed_destinations_3 = vec![
5277                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5278                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5279                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5280                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5281                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5282                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5283         ];
5284         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5285         check_added_monitors!(nodes[3], 1);
5286         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5287         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5288         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5289         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5290         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5291         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5292         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5293         if deliver_last_raa {
5294                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5295         } else {
5296                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5297         }
5298
5299         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5300         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5301         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5302         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5303         //
5304         // We now broadcast the latest commitment transaction, which *should* result in failures for
5305         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5306         // the non-broadcast above-dust HTLCs.
5307         //
5308         // Alternatively, we may broadcast the previous commitment transaction, which should only
5309         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5310         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5311
5312         if announce_latest {
5313                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5314         } else {
5315                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5316         }
5317         let events = nodes[2].node.get_and_clear_pending_events();
5318         let close_event = if deliver_last_raa {
5319                 assert_eq!(events.len(), 2 + 6);
5320                 events.last().clone().unwrap()
5321         } else {
5322                 assert_eq!(events.len(), 1);
5323                 events.last().clone().unwrap()
5324         };
5325         match close_event {
5326                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5327                 _ => panic!("Unexpected event"),
5328         }
5329
5330         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5331         check_closed_broadcast!(nodes[2], true);
5332         if deliver_last_raa {
5333                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5334
5335                 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();
5336                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5337         } else {
5338                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5339                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5340                 } else {
5341                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5342                 };
5343
5344                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5345         }
5346         check_added_monitors!(nodes[2], 3);
5347
5348         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5349         assert_eq!(cs_msgs.len(), 2);
5350         let mut a_done = false;
5351         for msg in cs_msgs {
5352                 match msg {
5353                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5354                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5355                                 // should be failed-backwards here.
5356                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5357                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5358                                         for htlc in &updates.update_fail_htlcs {
5359                                                 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 });
5360                                         }
5361                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5362                                         assert!(!a_done);
5363                                         a_done = true;
5364                                         &nodes[0]
5365                                 } else {
5366                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5367                                         for htlc in &updates.update_fail_htlcs {
5368                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5369                                         }
5370                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5371                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5372                                         &nodes[1]
5373                                 };
5374                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5375                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5376                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5377                                 if announce_latest {
5378                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5379                                         if *node_id == nodes[0].node.get_our_node_id() {
5380                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5381                                         }
5382                                 }
5383                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5384                         },
5385                         _ => panic!("Unexpected event"),
5386                 }
5387         }
5388
5389         let as_events = nodes[0].node.get_and_clear_pending_events();
5390         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5391         let mut as_failds = HashSet::new();
5392         let mut as_updates = 0;
5393         for event in as_events.iter() {
5394                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5395                         assert!(as_failds.insert(*payment_hash));
5396                         if *payment_hash != payment_hash_2 {
5397                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5398                         } else {
5399                                 assert!(!payment_failed_permanently);
5400                         }
5401                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5402                                 as_updates += 1;
5403                         }
5404                 } else if let &Event::PaymentFailed { .. } = event {
5405                 } else { panic!("Unexpected event"); }
5406         }
5407         assert!(as_failds.contains(&payment_hash_1));
5408         assert!(as_failds.contains(&payment_hash_2));
5409         if announce_latest {
5410                 assert!(as_failds.contains(&payment_hash_3));
5411                 assert!(as_failds.contains(&payment_hash_5));
5412         }
5413         assert!(as_failds.contains(&payment_hash_6));
5414
5415         let bs_events = nodes[1].node.get_and_clear_pending_events();
5416         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5417         let mut bs_failds = HashSet::new();
5418         let mut bs_updates = 0;
5419         for event in bs_events.iter() {
5420                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5421                         assert!(bs_failds.insert(*payment_hash));
5422                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5423                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5424                         } else {
5425                                 assert!(!payment_failed_permanently);
5426                         }
5427                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5428                                 bs_updates += 1;
5429                         }
5430                 } else if let &Event::PaymentFailed { .. } = event {
5431                 } else { panic!("Unexpected event"); }
5432         }
5433         assert!(bs_failds.contains(&payment_hash_1));
5434         assert!(bs_failds.contains(&payment_hash_2));
5435         if announce_latest {
5436                 assert!(bs_failds.contains(&payment_hash_4));
5437         }
5438         assert!(bs_failds.contains(&payment_hash_5));
5439
5440         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5441         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5442         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5443         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5444         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5445         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5446 }
5447
5448 #[test]
5449 fn test_fail_backwards_latest_remote_announce_a() {
5450         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5451 }
5452
5453 #[test]
5454 fn test_fail_backwards_latest_remote_announce_b() {
5455         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5456 }
5457
5458 #[test]
5459 fn test_fail_backwards_previous_remote_announce() {
5460         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5461         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5462         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5463 }
5464
5465 #[test]
5466 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5467         let chanmon_cfgs = create_chanmon_cfgs(2);
5468         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5469         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5470         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5471
5472         // Create some initial channels
5473         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5474
5475         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5476         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5477         assert_eq!(local_txn[0].input.len(), 1);
5478         check_spends!(local_txn[0], chan_1.3);
5479
5480         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5481         mine_transaction(&nodes[0], &local_txn[0]);
5482         check_closed_broadcast!(nodes[0], true);
5483         check_added_monitors!(nodes[0], 1);
5484         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5485         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5486
5487         let htlc_timeout = {
5488                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5489                 assert_eq!(node_txn.len(), 1);
5490                 assert_eq!(node_txn[0].input.len(), 1);
5491                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5492                 check_spends!(node_txn[0], local_txn[0]);
5493                 node_txn[0].clone()
5494         };
5495
5496         mine_transaction(&nodes[0], &htlc_timeout);
5497         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5498         expect_payment_failed!(nodes[0], our_payment_hash, false);
5499
5500         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5501         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5502         assert_eq!(spend_txn.len(), 3);
5503         check_spends!(spend_txn[0], local_txn[0]);
5504         assert_eq!(spend_txn[1].input.len(), 1);
5505         check_spends!(spend_txn[1], htlc_timeout);
5506         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5507         assert_eq!(spend_txn[2].input.len(), 2);
5508         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5509         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5510                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5511 }
5512
5513 #[test]
5514 fn test_key_derivation_params() {
5515         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5516         // manager rotation to test that `channel_keys_id` returned in
5517         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5518         // then derive a `delayed_payment_key`.
5519
5520         let chanmon_cfgs = create_chanmon_cfgs(3);
5521
5522         // We manually create the node configuration to backup the seed.
5523         let seed = [42; 32];
5524         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5525         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);
5526         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5527         let scorer = RwLock::new(test_utils::TestScorer::new());
5528         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5529         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)) };
5530         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5531         node_cfgs.remove(0);
5532         node_cfgs.insert(0, node);
5533
5534         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5535         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5536
5537         // Create some initial channels
5538         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5539         // for node 0
5540         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5541         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5542         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5543
5544         // Ensure all nodes are at the same height
5545         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5546         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5547         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5548         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5549
5550         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5551         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5552         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5553         assert_eq!(local_txn_1[0].input.len(), 1);
5554         check_spends!(local_txn_1[0], chan_1.3);
5555
5556         // We check funding pubkey are unique
5557         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]));
5558         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]));
5559         if from_0_funding_key_0 == from_1_funding_key_0
5560             || from_0_funding_key_0 == from_1_funding_key_1
5561             || from_0_funding_key_1 == from_1_funding_key_0
5562             || from_0_funding_key_1 == from_1_funding_key_1 {
5563                 panic!("Funding pubkeys aren't unique");
5564         }
5565
5566         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5567         mine_transaction(&nodes[0], &local_txn_1[0]);
5568         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5569         check_closed_broadcast!(nodes[0], true);
5570         check_added_monitors!(nodes[0], 1);
5571         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5572
5573         let htlc_timeout = {
5574                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5575                 assert_eq!(node_txn.len(), 1);
5576                 assert_eq!(node_txn[0].input.len(), 1);
5577                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5578                 check_spends!(node_txn[0], local_txn_1[0]);
5579                 node_txn[0].clone()
5580         };
5581
5582         mine_transaction(&nodes[0], &htlc_timeout);
5583         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5584         expect_payment_failed!(nodes[0], our_payment_hash, false);
5585
5586         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5587         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5588         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5589         assert_eq!(spend_txn.len(), 3);
5590         check_spends!(spend_txn[0], local_txn_1[0]);
5591         assert_eq!(spend_txn[1].input.len(), 1);
5592         check_spends!(spend_txn[1], htlc_timeout);
5593         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5594         assert_eq!(spend_txn[2].input.len(), 2);
5595         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5596         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5597                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5598 }
5599
5600 #[test]
5601 fn test_static_output_closing_tx() {
5602         let chanmon_cfgs = create_chanmon_cfgs(2);
5603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5606
5607         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5608
5609         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5610         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5611
5612         mine_transaction(&nodes[0], &closing_tx);
5613         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5614         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5615
5616         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5617         assert_eq!(spend_txn.len(), 1);
5618         check_spends!(spend_txn[0], closing_tx);
5619
5620         mine_transaction(&nodes[1], &closing_tx);
5621         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5622         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5623
5624         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5625         assert_eq!(spend_txn.len(), 1);
5626         check_spends!(spend_txn[0], closing_tx);
5627 }
5628
5629 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5630         let chanmon_cfgs = create_chanmon_cfgs(2);
5631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5634         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5635
5636         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5637
5638         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5639         // present in B's local commitment transaction, but none of A's commitment transactions.
5640         nodes[1].node.claim_funds(payment_preimage);
5641         check_added_monitors!(nodes[1], 1);
5642         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5643
5644         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5645         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5646         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5647
5648         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5649         check_added_monitors!(nodes[0], 1);
5650         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5651         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5652         check_added_monitors!(nodes[1], 1);
5653
5654         let starting_block = nodes[1].best_block_info();
5655         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5656         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5657                 connect_block(&nodes[1], &block);
5658                 block.header.prev_blockhash = block.block_hash();
5659         }
5660         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5661         check_closed_broadcast!(nodes[1], true);
5662         check_added_monitors!(nodes[1], 1);
5663         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
5664 }
5665
5666 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5667         let chanmon_cfgs = create_chanmon_cfgs(2);
5668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5670         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5671         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5672
5673         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5674         nodes[0].node.send_payment_with_route(&route, payment_hash,
5675                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5676         check_added_monitors!(nodes[0], 1);
5677
5678         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5679
5680         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5681         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5682         // to "time out" the HTLC.
5683
5684         let starting_block = nodes[1].best_block_info();
5685         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5686
5687         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5688                 connect_block(&nodes[0], &block);
5689                 block.header.prev_blockhash = block.block_hash();
5690         }
5691         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5692         check_closed_broadcast!(nodes[0], true);
5693         check_added_monitors!(nodes[0], 1);
5694         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5695 }
5696
5697 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5698         let chanmon_cfgs = create_chanmon_cfgs(3);
5699         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5700         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5701         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5702         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5703
5704         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5705         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5706         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5707         // actually revoked.
5708         let htlc_value = if use_dust { 50000 } else { 3000000 };
5709         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5710         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5711         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5712         check_added_monitors!(nodes[1], 1);
5713
5714         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5715         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5716         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5717         check_added_monitors!(nodes[0], 1);
5718         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5719         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5720         check_added_monitors!(nodes[1], 1);
5721         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5722         check_added_monitors!(nodes[1], 1);
5723         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5724
5725         if check_revoke_no_close {
5726                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5727                 check_added_monitors!(nodes[0], 1);
5728         }
5729
5730         let starting_block = nodes[1].best_block_info();
5731         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5732         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5733                 connect_block(&nodes[0], &block);
5734                 block.header.prev_blockhash = block.block_hash();
5735         }
5736         if !check_revoke_no_close {
5737                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5738                 check_closed_broadcast!(nodes[0], true);
5739                 check_added_monitors!(nodes[0], 1);
5740                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5741         } else {
5742                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5743         }
5744 }
5745
5746 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5747 // There are only a few cases to test here:
5748 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5749 //    broadcastable commitment transactions result in channel closure,
5750 //  * its included in an unrevoked-but-previous remote commitment transaction,
5751 //  * its included in the latest remote or local commitment transactions.
5752 // We test each of the three possible commitment transactions individually and use both dust and
5753 // non-dust HTLCs.
5754 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5755 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5756 // tested for at least one of the cases in other tests.
5757 #[test]
5758 fn htlc_claim_single_commitment_only_a() {
5759         do_htlc_claim_local_commitment_only(true);
5760         do_htlc_claim_local_commitment_only(false);
5761
5762         do_htlc_claim_current_remote_commitment_only(true);
5763         do_htlc_claim_current_remote_commitment_only(false);
5764 }
5765
5766 #[test]
5767 fn htlc_claim_single_commitment_only_b() {
5768         do_htlc_claim_previous_remote_commitment_only(true, false);
5769         do_htlc_claim_previous_remote_commitment_only(false, false);
5770         do_htlc_claim_previous_remote_commitment_only(true, true);
5771         do_htlc_claim_previous_remote_commitment_only(false, true);
5772 }
5773
5774 #[test]
5775 #[should_panic]
5776 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5777         let chanmon_cfgs = create_chanmon_cfgs(2);
5778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5780         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5781         // Force duplicate randomness for every get-random call
5782         for node in nodes.iter() {
5783                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5784         }
5785
5786         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5787         let channel_value_satoshis=10000;
5788         let push_msat=10001;
5789         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5790         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5791         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5792         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5793
5794         // Create a second channel with the same random values. This used to panic due to a colliding
5795         // channel_id, but now panics due to a colliding outbound SCID alias.
5796         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5797 }
5798
5799 #[test]
5800 fn bolt2_open_channel_sending_node_checks_part2() {
5801         let chanmon_cfgs = create_chanmon_cfgs(2);
5802         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5803         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5804         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5805
5806         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5807         let channel_value_satoshis=2^24;
5808         let push_msat=10001;
5809         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5810
5811         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5812         let channel_value_satoshis=10000;
5813         // Test when push_msat is equal to 1000 * funding_satoshis.
5814         let push_msat=1000*channel_value_satoshis+1;
5815         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5816
5817         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5818         let channel_value_satoshis=10000;
5819         let push_msat=10001;
5820         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
5821         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5822         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5823
5824         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5825         // 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
5826         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5827
5828         // 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.
5829         assert!(BREAKDOWN_TIMEOUT>0);
5830         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5831
5832         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5833         let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5834         assert_eq!(node0_to_1_send_open_channel.chain_hash, chain_hash);
5835
5836         // 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.
5837         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5838         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5839         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5840         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5841         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5842 }
5843
5844 #[test]
5845 fn bolt2_open_channel_sane_dust_limit() {
5846         let chanmon_cfgs = create_chanmon_cfgs(2);
5847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5850
5851         let channel_value_satoshis=1000000;
5852         let push_msat=10001;
5853         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5854         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5855         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5856         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5857
5858         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5859         let events = nodes[1].node.get_and_clear_pending_msg_events();
5860         let err_msg = match events[0] {
5861                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5862                         msg.clone()
5863                 },
5864                 _ => panic!("Unexpected event"),
5865         };
5866         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5867 }
5868
5869 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5870 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5871 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5872 // is no longer affordable once it's freed.
5873 #[test]
5874 fn test_fail_holding_cell_htlc_upon_free() {
5875         let chanmon_cfgs = create_chanmon_cfgs(2);
5876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5878         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5879         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5880
5881         // First nodes[0] generates an update_fee, setting the channel's
5882         // pending_update_fee.
5883         {
5884                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5885                 *feerate_lock += 20;
5886         }
5887         nodes[0].node.timer_tick_occurred();
5888         check_added_monitors!(nodes[0], 1);
5889
5890         let events = nodes[0].node.get_and_clear_pending_msg_events();
5891         assert_eq!(events.len(), 1);
5892         let (update_msg, commitment_signed) = match events[0] {
5893                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5894                         (update_fee.as_ref(), commitment_signed)
5895                 },
5896                 _ => panic!("Unexpected event"),
5897         };
5898
5899         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5900
5901         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5902         let channel_reserve = chan_stat.channel_reserve_msat;
5903         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5904         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5905
5906         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5907         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5908         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5909
5910         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5911         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5912                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5913         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5914         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5915
5916         // Flush the pending fee update.
5917         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5918         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5919         check_added_monitors!(nodes[1], 1);
5920         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5921         check_added_monitors!(nodes[0], 1);
5922
5923         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5924         // HTLC, but now that the fee has been raised the payment will now fail, causing
5925         // us to surface its failure to the user.
5926         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5927         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5928         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5929
5930         // Check that the payment failed to be sent out.
5931         let events = nodes[0].node.get_and_clear_pending_events();
5932         assert_eq!(events.len(), 2);
5933         match &events[0] {
5934                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5935                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5936                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5937                         assert_eq!(*payment_failed_permanently, false);
5938                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5939                 },
5940                 _ => panic!("Unexpected event"),
5941         }
5942         match &events[1] {
5943                 &Event::PaymentFailed { ref payment_hash, .. } => {
5944                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5945                 },
5946                 _ => panic!("Unexpected event"),
5947         }
5948 }
5949
5950 // Test that if multiple HTLCs are released from the holding cell and one is
5951 // valid but the other is no longer valid upon release, the valid HTLC can be
5952 // successfully completed while the other one fails as expected.
5953 #[test]
5954 fn test_free_and_fail_holding_cell_htlcs() {
5955         let chanmon_cfgs = create_chanmon_cfgs(2);
5956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5958         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5959         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5960
5961         // First nodes[0] generates an update_fee, setting the channel's
5962         // pending_update_fee.
5963         {
5964                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5965                 *feerate_lock += 200;
5966         }
5967         nodes[0].node.timer_tick_occurred();
5968         check_added_monitors!(nodes[0], 1);
5969
5970         let events = nodes[0].node.get_and_clear_pending_msg_events();
5971         assert_eq!(events.len(), 1);
5972         let (update_msg, commitment_signed) = match events[0] {
5973                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5974                         (update_fee.as_ref(), commitment_signed)
5975                 },
5976                 _ => panic!("Unexpected event"),
5977         };
5978
5979         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5980
5981         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5982         let channel_reserve = chan_stat.channel_reserve_msat;
5983         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5984         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5985
5986         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5987         let amt_1 = 20000;
5988         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5989         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5990         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5991
5992         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5993         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5994                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5995         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5996         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5997         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5998         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5999                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6000         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6001         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6002
6003         // Flush the pending fee update.
6004         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6005         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6006         check_added_monitors!(nodes[1], 1);
6007         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6008         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6009         check_added_monitors!(nodes[0], 2);
6010
6011         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6012         // but now that the fee has been raised the second payment will now fail, causing us
6013         // to surface its failure to the user. The first payment should succeed.
6014         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6015         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6016         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6017
6018         // Check that the second payment failed to be sent out.
6019         let events = nodes[0].node.get_and_clear_pending_events();
6020         assert_eq!(events.len(), 2);
6021         match &events[0] {
6022                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6023                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6024                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6025                         assert_eq!(*payment_failed_permanently, false);
6026                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6027                 },
6028                 _ => panic!("Unexpected event"),
6029         }
6030         match &events[1] {
6031                 &Event::PaymentFailed { ref payment_hash, .. } => {
6032                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6033                 },
6034                 _ => panic!("Unexpected event"),
6035         }
6036
6037         // Complete the first payment and the RAA from the fee update.
6038         let (payment_event, send_raa_event) = {
6039                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6040                 assert_eq!(msgs.len(), 2);
6041                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6042         };
6043         let raa = match send_raa_event {
6044                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6045                 _ => panic!("Unexpected event"),
6046         };
6047         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6048         check_added_monitors!(nodes[1], 1);
6049         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6050         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6051         let events = nodes[1].node.get_and_clear_pending_events();
6052         assert_eq!(events.len(), 1);
6053         match events[0] {
6054                 Event::PendingHTLCsForwardable { .. } => {},
6055                 _ => panic!("Unexpected event"),
6056         }
6057         nodes[1].node.process_pending_htlc_forwards();
6058         let events = nodes[1].node.get_and_clear_pending_events();
6059         assert_eq!(events.len(), 1);
6060         match events[0] {
6061                 Event::PaymentClaimable { .. } => {},
6062                 _ => panic!("Unexpected event"),
6063         }
6064         nodes[1].node.claim_funds(payment_preimage_1);
6065         check_added_monitors!(nodes[1], 1);
6066         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6067
6068         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6069         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6070         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6071         expect_payment_sent!(nodes[0], payment_preimage_1);
6072 }
6073
6074 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6075 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6076 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6077 // once it's freed.
6078 #[test]
6079 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6080         let chanmon_cfgs = create_chanmon_cfgs(3);
6081         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6082         // Avoid having to include routing fees in calculations
6083         let mut config = test_default_channel_config();
6084         config.channel_config.forwarding_fee_base_msat = 0;
6085         config.channel_config.forwarding_fee_proportional_millionths = 0;
6086         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6087         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6088         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6089         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6090
6091         // First nodes[1] generates an update_fee, setting the channel's
6092         // pending_update_fee.
6093         {
6094                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6095                 *feerate_lock += 20;
6096         }
6097         nodes[1].node.timer_tick_occurred();
6098         check_added_monitors!(nodes[1], 1);
6099
6100         let events = nodes[1].node.get_and_clear_pending_msg_events();
6101         assert_eq!(events.len(), 1);
6102         let (update_msg, commitment_signed) = match events[0] {
6103                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6104                         (update_fee.as_ref(), commitment_signed)
6105                 },
6106                 _ => panic!("Unexpected event"),
6107         };
6108
6109         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6110
6111         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6112         let channel_reserve = chan_stat.channel_reserve_msat;
6113         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6114         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6115
6116         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6117         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6118         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6119         let payment_event = {
6120                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6121                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6122                 check_added_monitors!(nodes[0], 1);
6123
6124                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6125                 assert_eq!(events.len(), 1);
6126
6127                 SendEvent::from_event(events.remove(0))
6128         };
6129         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6130         check_added_monitors!(nodes[1], 0);
6131         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6132         expect_pending_htlcs_forwardable!(nodes[1]);
6133
6134         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6135         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6136
6137         // Flush the pending fee update.
6138         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6139         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6140         check_added_monitors!(nodes[2], 1);
6141         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6142         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6143         check_added_monitors!(nodes[1], 2);
6144
6145         // A final RAA message is generated to finalize the fee update.
6146         let events = nodes[1].node.get_and_clear_pending_msg_events();
6147         assert_eq!(events.len(), 1);
6148
6149         let raa_msg = match &events[0] {
6150                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6151                         msg.clone()
6152                 },
6153                 _ => panic!("Unexpected event"),
6154         };
6155
6156         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6157         check_added_monitors!(nodes[2], 1);
6158         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6159
6160         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6161         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6162         assert_eq!(process_htlc_forwards_event.len(), 2);
6163         match &process_htlc_forwards_event[0] {
6164                 &Event::PendingHTLCsForwardable { .. } => {},
6165                 _ => panic!("Unexpected event"),
6166         }
6167
6168         // In response, we call ChannelManager's process_pending_htlc_forwards
6169         nodes[1].node.process_pending_htlc_forwards();
6170         check_added_monitors!(nodes[1], 1);
6171
6172         // This causes the HTLC to be failed backwards.
6173         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6174         assert_eq!(fail_event.len(), 1);
6175         let (fail_msg, commitment_signed) = match &fail_event[0] {
6176                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6177                         assert_eq!(updates.update_add_htlcs.len(), 0);
6178                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6179                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6180                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6181                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6182                 },
6183                 _ => panic!("Unexpected event"),
6184         };
6185
6186         // Pass the failure messages back to nodes[0].
6187         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6188         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6189
6190         // Complete the HTLC failure+removal process.
6191         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6192         check_added_monitors!(nodes[0], 1);
6193         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6194         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6195         check_added_monitors!(nodes[1], 2);
6196         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6197         assert_eq!(final_raa_event.len(), 1);
6198         let raa = match &final_raa_event[0] {
6199                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6200                 _ => panic!("Unexpected event"),
6201         };
6202         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6203         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6204         check_added_monitors!(nodes[0], 1);
6205 }
6206
6207 #[test]
6208 fn test_payment_route_reaching_same_channel_twice() {
6209         //A route should not go through the same channel twice
6210         //It is enforced when constructing a route.
6211         let chanmon_cfgs = create_chanmon_cfgs(2);
6212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6214         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6215         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6216
6217         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6218                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6219         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6220
6221         // Extend the path by itself, essentially simulating route going through same channel twice
6222         let cloned_hops = route.paths[0].hops.clone();
6223         route.paths[0].hops.extend_from_slice(&cloned_hops);
6224
6225         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6226                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6227         ), false, APIError::InvalidRoute { ref err },
6228         assert_eq!(err, &"Path went through the same channel twice"));
6229 }
6230
6231 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6232 // 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.
6233 //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.
6234
6235 #[test]
6236 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6237         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6238         let chanmon_cfgs = create_chanmon_cfgs(2);
6239         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6240         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6241         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6242         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6243
6244         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6245         route.paths[0].hops[0].fee_msat = 100;
6246
6247         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6248                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6249                 ), true, APIError::ChannelUnavailable { .. }, {});
6250         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6251 }
6252
6253 #[test]
6254 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6255         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6256         let chanmon_cfgs = create_chanmon_cfgs(2);
6257         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6258         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6259         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6260         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6261
6262         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6263         route.paths[0].hops[0].fee_msat = 0;
6264         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6265                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6266                 true, APIError::ChannelUnavailable { ref err },
6267                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6268
6269         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6270         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6271 }
6272
6273 #[test]
6274 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6275         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6276         let chanmon_cfgs = create_chanmon_cfgs(2);
6277         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6278         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6279         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6280         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6281
6282         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6283         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6284                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6285         check_added_monitors!(nodes[0], 1);
6286         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6287         updates.update_add_htlcs[0].amount_msat = 0;
6288
6289         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6290         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6291         check_closed_broadcast!(nodes[1], true).unwrap();
6292         check_added_monitors!(nodes[1], 1);
6293         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6294                 [nodes[0].node.get_our_node_id()], 100000);
6295 }
6296
6297 #[test]
6298 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6299         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6300         //It is enforced when constructing a route.
6301         let chanmon_cfgs = create_chanmon_cfgs(2);
6302         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6303         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6304         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6305         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6306
6307         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6308                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6309         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6310         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6311         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6312                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6313                 ), true, APIError::InvalidRoute { ref err },
6314                 assert_eq!(err, &"Channel CLTV overflowed?"));
6315 }
6316
6317 #[test]
6318 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6319         //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.
6320         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6321         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6322         let chanmon_cfgs = create_chanmon_cfgs(2);
6323         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6327         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6328                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6329
6330         // Fetch a route in advance as we will be unable to once we're unable to send.
6331         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6332         for i in 0..max_accepted_htlcs {
6333                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6334                 let payment_event = {
6335                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6336                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6337                         check_added_monitors!(nodes[0], 1);
6338
6339                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6340                         assert_eq!(events.len(), 1);
6341                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6342                                 assert_eq!(htlcs[0].htlc_id, i);
6343                         } else {
6344                                 assert!(false);
6345                         }
6346                         SendEvent::from_event(events.remove(0))
6347                 };
6348                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6349                 check_added_monitors!(nodes[1], 0);
6350                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6351
6352                 expect_pending_htlcs_forwardable!(nodes[1]);
6353                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6354         }
6355         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6356                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6357                 ), true, APIError::ChannelUnavailable { .. }, {});
6358
6359         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6360 }
6361
6362 #[test]
6363 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6364         //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.
6365         let chanmon_cfgs = create_chanmon_cfgs(2);
6366         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6367         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6368         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6369         let channel_value = 100000;
6370         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6371         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6372
6373         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6374
6375         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6376         // Manually create a route over our max in flight (which our router normally automatically
6377         // limits us to.
6378         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6379         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6380                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6381                 ), true, APIError::ChannelUnavailable { .. }, {});
6382         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6383
6384         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6385 }
6386
6387 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6388 #[test]
6389 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6390         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6391         let chanmon_cfgs = create_chanmon_cfgs(2);
6392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6395         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6396         let htlc_minimum_msat: u64;
6397         {
6398                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6399                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6400                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6401                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6402         }
6403
6404         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6405         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6406                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6407         check_added_monitors!(nodes[0], 1);
6408         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6409         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6410         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6411         assert!(nodes[1].node.list_channels().is_empty());
6412         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6413         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()));
6414         check_added_monitors!(nodes[1], 1);
6415         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6416 }
6417
6418 #[test]
6419 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6420         //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
6421         let chanmon_cfgs = create_chanmon_cfgs(2);
6422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6424         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6425         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6426
6427         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6428         let channel_reserve = chan_stat.channel_reserve_msat;
6429         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6430         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6431         // The 2* and +1 are for the fee spike reserve.
6432         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6433
6434         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6435         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6436         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6437                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6438         check_added_monitors!(nodes[0], 1);
6439         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6440
6441         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6442         // at this time channel-initiatee receivers are not required to enforce that senders
6443         // respect the fee_spike_reserve.
6444         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6445         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6446
6447         assert!(nodes[1].node.list_channels().is_empty());
6448         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6449         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6450         check_added_monitors!(nodes[1], 1);
6451         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6452 }
6453
6454 #[test]
6455 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6456         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6457         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6458         let chanmon_cfgs = create_chanmon_cfgs(2);
6459         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6460         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6461         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6462         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6463
6464         let send_amt = 3999999;
6465         let (mut route, our_payment_hash, _, our_payment_secret) =
6466                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6467         route.paths[0].hops[0].fee_msat = send_amt;
6468         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6469         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6470         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6471         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6472                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6473         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6474
6475         let mut msg = msgs::UpdateAddHTLC {
6476                 channel_id: chan.2,
6477                 htlc_id: 0,
6478                 amount_msat: 1000,
6479                 payment_hash: our_payment_hash,
6480                 cltv_expiry: htlc_cltv,
6481                 onion_routing_packet: onion_packet.clone(),
6482                 skimmed_fee_msat: None,
6483         };
6484
6485         for i in 0..50 {
6486                 msg.htlc_id = i as u64;
6487                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6488         }
6489         msg.htlc_id = (50) as u64;
6490         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6491
6492         assert!(nodes[1].node.list_channels().is_empty());
6493         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6494         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6495         check_added_monitors!(nodes[1], 1);
6496         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6497 }
6498
6499 #[test]
6500 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6501         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6502         let chanmon_cfgs = create_chanmon_cfgs(2);
6503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6505         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6506         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6507
6508         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6509         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6510                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6511         check_added_monitors!(nodes[0], 1);
6512         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6513         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;
6514         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6515
6516         assert!(nodes[1].node.list_channels().is_empty());
6517         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6518         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6519         check_added_monitors!(nodes[1], 1);
6520         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6521 }
6522
6523 #[test]
6524 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6525         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6526         let chanmon_cfgs = create_chanmon_cfgs(2);
6527         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530
6531         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6532         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6533         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6534                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6535         check_added_monitors!(nodes[0], 1);
6536         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6537         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6538         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6539
6540         assert!(nodes[1].node.list_channels().is_empty());
6541         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6542         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6543         check_added_monitors!(nodes[1], 1);
6544         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6545 }
6546
6547 #[test]
6548 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6549         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6550         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6551         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6552         let chanmon_cfgs = create_chanmon_cfgs(2);
6553         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6554         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6555         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6556
6557         create_announced_chan_between_nodes(&nodes, 0, 1);
6558         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6559         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6560                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6561         check_added_monitors!(nodes[0], 1);
6562         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6563         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6564
6565         //Disconnect and Reconnect
6566         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6567         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6568         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6569                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6570         }, true).unwrap();
6571         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6572         assert_eq!(reestablish_1.len(), 1);
6573         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6574                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6575         }, false).unwrap();
6576         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6577         assert_eq!(reestablish_2.len(), 1);
6578         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6579         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6580         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6581         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6582
6583         //Resend HTLC
6584         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6585         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6586         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6587         check_added_monitors!(nodes[1], 1);
6588         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6589
6590         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6591
6592         assert!(nodes[1].node.list_channels().is_empty());
6593         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6594         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6595         check_added_monitors!(nodes[1], 1);
6596         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6597 }
6598
6599 #[test]
6600 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6601         //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.
6602
6603         let chanmon_cfgs = create_chanmon_cfgs(2);
6604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6606         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6607         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6608         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6609         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6610                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6611
6612         check_added_monitors!(nodes[0], 1);
6613         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6614         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6615
6616         let update_msg = msgs::UpdateFulfillHTLC{
6617                 channel_id: chan.2,
6618                 htlc_id: 0,
6619                 payment_preimage: our_payment_preimage,
6620         };
6621
6622         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6623
6624         assert!(nodes[0].node.list_channels().is_empty());
6625         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6626         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()));
6627         check_added_monitors!(nodes[0], 1);
6628         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6629 }
6630
6631 #[test]
6632 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6633         //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.
6634
6635         let chanmon_cfgs = create_chanmon_cfgs(2);
6636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6639         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6640
6641         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6642         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6643                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6644         check_added_monitors!(nodes[0], 1);
6645         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6646         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6647
6648         let update_msg = msgs::UpdateFailHTLC{
6649                 channel_id: chan.2,
6650                 htlc_id: 0,
6651                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6652         };
6653
6654         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6655
6656         assert!(nodes[0].node.list_channels().is_empty());
6657         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6658         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()));
6659         check_added_monitors!(nodes[0], 1);
6660         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6661 }
6662
6663 #[test]
6664 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6665         //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.
6666
6667         let chanmon_cfgs = create_chanmon_cfgs(2);
6668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6670         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6671         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6672
6673         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6674         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6675                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6676         check_added_monitors!(nodes[0], 1);
6677         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6678         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6679         let update_msg = msgs::UpdateFailMalformedHTLC{
6680                 channel_id: chan.2,
6681                 htlc_id: 0,
6682                 sha256_of_onion: [1; 32],
6683                 failure_code: 0x8000,
6684         };
6685
6686         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6687
6688         assert!(nodes[0].node.list_channels().is_empty());
6689         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6690         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()));
6691         check_added_monitors!(nodes[0], 1);
6692         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6693 }
6694
6695 #[test]
6696 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6697         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6698
6699         let chanmon_cfgs = create_chanmon_cfgs(2);
6700         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6701         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6702         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6703         create_announced_chan_between_nodes(&nodes, 0, 1);
6704
6705         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6706
6707         nodes[1].node.claim_funds(our_payment_preimage);
6708         check_added_monitors!(nodes[1], 1);
6709         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6710
6711         let events = nodes[1].node.get_and_clear_pending_msg_events();
6712         assert_eq!(events.len(), 1);
6713         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6714                 match events[0] {
6715                         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, .. } } => {
6716                                 assert!(update_add_htlcs.is_empty());
6717                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6718                                 assert!(update_fail_htlcs.is_empty());
6719                                 assert!(update_fail_malformed_htlcs.is_empty());
6720                                 assert!(update_fee.is_none());
6721                                 update_fulfill_htlcs[0].clone()
6722                         },
6723                         _ => panic!("Unexpected event"),
6724                 }
6725         };
6726
6727         update_fulfill_msg.htlc_id = 1;
6728
6729         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6730
6731         assert!(nodes[0].node.list_channels().is_empty());
6732         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6733         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6734         check_added_monitors!(nodes[0], 1);
6735         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6736 }
6737
6738 #[test]
6739 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6740         //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.
6741
6742         let chanmon_cfgs = create_chanmon_cfgs(2);
6743         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6744         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6745         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6746         create_announced_chan_between_nodes(&nodes, 0, 1);
6747
6748         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6749
6750         nodes[1].node.claim_funds(our_payment_preimage);
6751         check_added_monitors!(nodes[1], 1);
6752         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6753
6754         let events = nodes[1].node.get_and_clear_pending_msg_events();
6755         assert_eq!(events.len(), 1);
6756         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6757                 match events[0] {
6758                         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, .. } } => {
6759                                 assert!(update_add_htlcs.is_empty());
6760                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6761                                 assert!(update_fail_htlcs.is_empty());
6762                                 assert!(update_fail_malformed_htlcs.is_empty());
6763                                 assert!(update_fee.is_none());
6764                                 update_fulfill_htlcs[0].clone()
6765                         },
6766                         _ => panic!("Unexpected event"),
6767                 }
6768         };
6769
6770         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6771
6772         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6773
6774         assert!(nodes[0].node.list_channels().is_empty());
6775         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6776         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6777         check_added_monitors!(nodes[0], 1);
6778         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6779 }
6780
6781 #[test]
6782 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6783         //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.
6784
6785         let chanmon_cfgs = create_chanmon_cfgs(2);
6786         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6787         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6788         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6789         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6790
6791         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6792         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6793                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6794         check_added_monitors!(nodes[0], 1);
6795
6796         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6797         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6798
6799         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6800         check_added_monitors!(nodes[1], 0);
6801         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6802
6803         let events = nodes[1].node.get_and_clear_pending_msg_events();
6804
6805         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6806                 match events[0] {
6807                         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, .. } } => {
6808                                 assert!(update_add_htlcs.is_empty());
6809                                 assert!(update_fulfill_htlcs.is_empty());
6810                                 assert!(update_fail_htlcs.is_empty());
6811                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6812                                 assert!(update_fee.is_none());
6813                                 update_fail_malformed_htlcs[0].clone()
6814                         },
6815                         _ => panic!("Unexpected event"),
6816                 }
6817         };
6818         update_msg.failure_code &= !0x8000;
6819         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6820
6821         assert!(nodes[0].node.list_channels().is_empty());
6822         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6823         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6824         check_added_monitors!(nodes[0], 1);
6825         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6826 }
6827
6828 #[test]
6829 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6830         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6831         //    * 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.
6832
6833         let chanmon_cfgs = create_chanmon_cfgs(3);
6834         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6835         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6836         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6837         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6838         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6839
6840         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6841
6842         //First hop
6843         let mut payment_event = {
6844                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6845                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6846                 check_added_monitors!(nodes[0], 1);
6847                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6848                 assert_eq!(events.len(), 1);
6849                 SendEvent::from_event(events.remove(0))
6850         };
6851         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6852         check_added_monitors!(nodes[1], 0);
6853         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6854         expect_pending_htlcs_forwardable!(nodes[1]);
6855         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6856         assert_eq!(events_2.len(), 1);
6857         check_added_monitors!(nodes[1], 1);
6858         payment_event = SendEvent::from_event(events_2.remove(0));
6859         assert_eq!(payment_event.msgs.len(), 1);
6860
6861         //Second Hop
6862         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6863         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6864         check_added_monitors!(nodes[2], 0);
6865         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6866
6867         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6868         assert_eq!(events_3.len(), 1);
6869         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6870                 match events_3[0] {
6871                         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 } } => {
6872                                 assert!(update_add_htlcs.is_empty());
6873                                 assert!(update_fulfill_htlcs.is_empty());
6874                                 assert!(update_fail_htlcs.is_empty());
6875                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6876                                 assert!(update_fee.is_none());
6877                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6878                         },
6879                         _ => panic!("Unexpected event"),
6880                 }
6881         };
6882
6883         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6884
6885         check_added_monitors!(nodes[1], 0);
6886         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6887         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 }]);
6888         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6889         assert_eq!(events_4.len(), 1);
6890
6891         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6892         match events_4[0] {
6893                 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, .. } } => {
6894                         assert!(update_add_htlcs.is_empty());
6895                         assert!(update_fulfill_htlcs.is_empty());
6896                         assert_eq!(update_fail_htlcs.len(), 1);
6897                         assert!(update_fail_malformed_htlcs.is_empty());
6898                         assert!(update_fee.is_none());
6899                 },
6900                 _ => panic!("Unexpected event"),
6901         };
6902
6903         check_added_monitors!(nodes[1], 1);
6904 }
6905
6906 #[test]
6907 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6908         let chanmon_cfgs = create_chanmon_cfgs(3);
6909         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6910         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6911         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6912         create_announced_chan_between_nodes(&nodes, 0, 1);
6913         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6914
6915         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6916
6917         // First hop
6918         let mut payment_event = {
6919                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6920                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6921                 check_added_monitors!(nodes[0], 1);
6922                 SendEvent::from_node(&nodes[0])
6923         };
6924
6925         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6926         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6927         expect_pending_htlcs_forwardable!(nodes[1]);
6928         check_added_monitors!(nodes[1], 1);
6929         payment_event = SendEvent::from_node(&nodes[1]);
6930         assert_eq!(payment_event.msgs.len(), 1);
6931
6932         // Second Hop
6933         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6934         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6935         check_added_monitors!(nodes[2], 0);
6936         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6937
6938         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6939         assert_eq!(events_3.len(), 1);
6940         match events_3[0] {
6941                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6942                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6943                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6944                         update_msg.failure_code |= 0x2000;
6945
6946                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6947                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6948                 },
6949                 _ => panic!("Unexpected event"),
6950         }
6951
6952         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6953                 vec![HTLCDestination::NextHopChannel {
6954                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6955         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6956         assert_eq!(events_4.len(), 1);
6957         check_added_monitors!(nodes[1], 1);
6958
6959         match events_4[0] {
6960                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6961                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6962                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6963                 },
6964                 _ => panic!("Unexpected event"),
6965         }
6966
6967         let events_5 = nodes[0].node.get_and_clear_pending_events();
6968         assert_eq!(events_5.len(), 2);
6969
6970         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6971         // the node originating the error to its next hop.
6972         match events_5[0] {
6973                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6974                 } => {
6975                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6976                         assert!(is_permanent);
6977                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6978                 },
6979                 _ => panic!("Unexpected event"),
6980         }
6981         match events_5[1] {
6982                 Event::PaymentFailed { payment_hash, .. } => {
6983                         assert_eq!(payment_hash, our_payment_hash);
6984                 },
6985                 _ => panic!("Unexpected event"),
6986         }
6987
6988         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6989 }
6990
6991 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6992         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6993         // 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
6994         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6995
6996         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6997         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6998         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6999         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7000         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7001         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7002
7003         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7004                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7005
7006         // We route 2 dust-HTLCs between A and B
7007         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7008         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7009         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7010
7011         // Cache one local commitment tx as previous
7012         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7013
7014         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7015         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7016         check_added_monitors!(nodes[1], 0);
7017         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7018         check_added_monitors!(nodes[1], 1);
7019
7020         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7021         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7022         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7023         check_added_monitors!(nodes[0], 1);
7024
7025         // Cache one local commitment tx as lastest
7026         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7027
7028         let events = nodes[0].node.get_and_clear_pending_msg_events();
7029         match events[0] {
7030                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7031                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7032                 },
7033                 _ => panic!("Unexpected event"),
7034         }
7035         match events[1] {
7036                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7037                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7038                 },
7039                 _ => panic!("Unexpected event"),
7040         }
7041
7042         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7043         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7044         if announce_latest {
7045                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7046         } else {
7047                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7048         }
7049
7050         check_closed_broadcast!(nodes[0], true);
7051         check_added_monitors!(nodes[0], 1);
7052         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7053
7054         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7055         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7056         let events = nodes[0].node.get_and_clear_pending_events();
7057         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7058         assert_eq!(events.len(), 4);
7059         let mut first_failed = false;
7060         for event in events {
7061                 match event {
7062                         Event::PaymentPathFailed { payment_hash, .. } => {
7063                                 if payment_hash == payment_hash_1 {
7064                                         assert!(!first_failed);
7065                                         first_failed = true;
7066                                 } else {
7067                                         assert_eq!(payment_hash, payment_hash_2);
7068                                 }
7069                         },
7070                         Event::PaymentFailed { .. } => {}
7071                         _ => panic!("Unexpected event"),
7072                 }
7073         }
7074 }
7075
7076 #[test]
7077 fn test_failure_delay_dust_htlc_local_commitment() {
7078         do_test_failure_delay_dust_htlc_local_commitment(true);
7079         do_test_failure_delay_dust_htlc_local_commitment(false);
7080 }
7081
7082 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7083         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7084         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7085         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7086         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7087         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7088         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7089
7090         let chanmon_cfgs = create_chanmon_cfgs(3);
7091         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7092         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7093         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7094         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7095
7096         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7097                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7098
7099         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7100         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7101
7102         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7103         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7104
7105         // We revoked bs_commitment_tx
7106         if revoked {
7107                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7108                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7109         }
7110
7111         let mut timeout_tx = Vec::new();
7112         if local {
7113                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7114                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7115                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7116                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7117                 expect_payment_failed!(nodes[0], dust_hash, false);
7118
7119                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7120                 check_closed_broadcast!(nodes[0], true);
7121                 check_added_monitors!(nodes[0], 1);
7122                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7123                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7124                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7125                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7126                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7127                 mine_transaction(&nodes[0], &timeout_tx[0]);
7128                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7129                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7130         } else {
7131                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7132                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7133                 check_closed_broadcast!(nodes[0], true);
7134                 check_added_monitors!(nodes[0], 1);
7135                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7136                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7137
7138                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7139                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7140                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7141                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7142                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7143                 // dust HTLC should have been failed.
7144                 expect_payment_failed!(nodes[0], dust_hash, false);
7145
7146                 if !revoked {
7147                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7148                 } else {
7149                         assert_eq!(timeout_tx[0].lock_time.0, 11);
7150                 }
7151                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7152                 mine_transaction(&nodes[0], &timeout_tx[0]);
7153                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7154                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7155                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7156         }
7157 }
7158
7159 #[test]
7160 fn test_sweep_outbound_htlc_failure_update() {
7161         do_test_sweep_outbound_htlc_failure_update(false, true);
7162         do_test_sweep_outbound_htlc_failure_update(false, false);
7163         do_test_sweep_outbound_htlc_failure_update(true, false);
7164 }
7165
7166 #[test]
7167 fn test_user_configurable_csv_delay() {
7168         // We test our channel constructors yield errors when we pass them absurd csv delay
7169
7170         let mut low_our_to_self_config = UserConfig::default();
7171         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7172         let mut high_their_to_self_config = UserConfig::default();
7173         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7174         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7175         let chanmon_cfgs = create_chanmon_cfgs(2);
7176         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7177         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7178         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7179
7180         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7181         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7182                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7183                 &low_our_to_self_config, 0, 42, None)
7184         {
7185                 match error {
7186                         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())); },
7187                         _ => panic!("Unexpected event"),
7188                 }
7189         } else { assert!(false) }
7190
7191         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7192         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7193         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7194         open_channel.to_self_delay = 200;
7195         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7196                 &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,
7197                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7198         {
7199                 match error {
7200                         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()));  },
7201                         _ => panic!("Unexpected event"),
7202                 }
7203         } else { assert!(false); }
7204
7205         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7206         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7207         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()));
7208         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7209         accept_channel.to_self_delay = 200;
7210         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7211         let reason_msg;
7212         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7213                 match action {
7214                         &ErrorAction::SendErrorMessage { ref msg } => {
7215                                 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()));
7216                                 reason_msg = msg.data.clone();
7217                         },
7218                         _ => { panic!(); }
7219                 }
7220         } else { panic!(); }
7221         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7222
7223         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7224         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7225         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7226         open_channel.to_self_delay = 200;
7227         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7228                 &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,
7229                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7230         {
7231                 match error {
7232                         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())); },
7233                         _ => panic!("Unexpected event"),
7234                 }
7235         } else { assert!(false); }
7236 }
7237
7238 #[test]
7239 fn test_check_htlc_underpaying() {
7240         // Send payment through A -> B but A is maliciously
7241         // sending a probe payment (i.e less than expected value0
7242         // to B, B should refuse payment.
7243
7244         let chanmon_cfgs = create_chanmon_cfgs(2);
7245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7247         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7248
7249         // Create some initial channels
7250         create_announced_chan_between_nodes(&nodes, 0, 1);
7251
7252         let scorer = test_utils::TestScorer::new();
7253         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7254         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7255                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7256         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7257         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7258                 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7259         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7260         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7261         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7262                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7263         check_added_monitors!(nodes[0], 1);
7264
7265         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7266         assert_eq!(events.len(), 1);
7267         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7268         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7269         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7270
7271         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7272         // and then will wait a second random delay before failing the HTLC back:
7273         expect_pending_htlcs_forwardable!(nodes[1]);
7274         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7275
7276         // Node 3 is expecting payment of 100_000 but received 10_000,
7277         // it should fail htlc like we didn't know the preimage.
7278         nodes[1].node.process_pending_htlc_forwards();
7279
7280         let events = nodes[1].node.get_and_clear_pending_msg_events();
7281         assert_eq!(events.len(), 1);
7282         let (update_fail_htlc, commitment_signed) = match events[0] {
7283                 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 } } => {
7284                         assert!(update_add_htlcs.is_empty());
7285                         assert!(update_fulfill_htlcs.is_empty());
7286                         assert_eq!(update_fail_htlcs.len(), 1);
7287                         assert!(update_fail_malformed_htlcs.is_empty());
7288                         assert!(update_fee.is_none());
7289                         (update_fail_htlcs[0].clone(), commitment_signed)
7290                 },
7291                 _ => panic!("Unexpected event"),
7292         };
7293         check_added_monitors!(nodes[1], 1);
7294
7295         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7296         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7297
7298         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7299         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7300         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7301         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7302 }
7303
7304 #[test]
7305 fn test_announce_disable_channels() {
7306         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7307         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7308
7309         let chanmon_cfgs = create_chanmon_cfgs(2);
7310         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7311         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7312         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7313
7314         create_announced_chan_between_nodes(&nodes, 0, 1);
7315         create_announced_chan_between_nodes(&nodes, 1, 0);
7316         create_announced_chan_between_nodes(&nodes, 0, 1);
7317
7318         // Disconnect peers
7319         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7320         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7321
7322         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7323                 nodes[0].node.timer_tick_occurred();
7324         }
7325         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7326         assert_eq!(msg_events.len(), 3);
7327         let mut chans_disabled = HashMap::new();
7328         for e in msg_events {
7329                 match e {
7330                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7331                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7332                                 // Check that each channel gets updated exactly once
7333                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7334                                         panic!("Generated ChannelUpdate for wrong chan!");
7335                                 }
7336                         },
7337                         _ => panic!("Unexpected event"),
7338                 }
7339         }
7340         // Reconnect peers
7341         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7342                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7343         }, true).unwrap();
7344         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7345         assert_eq!(reestablish_1.len(), 3);
7346         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7347                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7348         }, false).unwrap();
7349         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7350         assert_eq!(reestablish_2.len(), 3);
7351
7352         // Reestablish chan_1
7353         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7354         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7355         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7356         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7357         // Reestablish chan_2
7358         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7359         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7360         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7361         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7362         // Reestablish chan_3
7363         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7364         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7365         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7366         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7367
7368         for _ in 0..ENABLE_GOSSIP_TICKS {
7369                 nodes[0].node.timer_tick_occurred();
7370         }
7371         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7372         nodes[0].node.timer_tick_occurred();
7373         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7374         assert_eq!(msg_events.len(), 3);
7375         for e in msg_events {
7376                 match e {
7377                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7378                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7379                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7380                                         // Each update should have a higher timestamp than the previous one, replacing
7381                                         // the old one.
7382                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7383                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7384                                 }
7385                         },
7386                         _ => panic!("Unexpected event"),
7387                 }
7388         }
7389         // Check that each channel gets updated exactly once
7390         assert!(chans_disabled.is_empty());
7391 }
7392
7393 #[test]
7394 fn test_bump_penalty_txn_on_revoked_commitment() {
7395         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7396         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7397
7398         let chanmon_cfgs = create_chanmon_cfgs(2);
7399         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7400         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7401         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7402
7403         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7404
7405         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7406         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7407                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7408         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7409         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7410
7411         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7412         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7413         assert_eq!(revoked_txn[0].output.len(), 4);
7414         assert_eq!(revoked_txn[0].input.len(), 1);
7415         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7416         let revoked_txid = revoked_txn[0].txid();
7417
7418         let mut penalty_sum = 0;
7419         for outp in revoked_txn[0].output.iter() {
7420                 if outp.script_pubkey.is_v0_p2wsh() {
7421                         penalty_sum += outp.value;
7422                 }
7423         }
7424
7425         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7426         let header_114 = connect_blocks(&nodes[1], 14);
7427
7428         // Actually revoke tx by claiming a HTLC
7429         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7430         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7431         check_added_monitors!(nodes[1], 1);
7432
7433         // One or more justice tx should have been broadcast, check it
7434         let penalty_1;
7435         let feerate_1;
7436         {
7437                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7438                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7439                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7440                 assert_eq!(node_txn[0].output.len(), 1);
7441                 check_spends!(node_txn[0], revoked_txn[0]);
7442                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7443                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7444                 penalty_1 = node_txn[0].txid();
7445                 node_txn.clear();
7446         };
7447
7448         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7449         connect_blocks(&nodes[1], 15);
7450         let mut penalty_2 = penalty_1;
7451         let mut feerate_2 = 0;
7452         {
7453                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7454                 assert_eq!(node_txn.len(), 1);
7455                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7456                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7457                         assert_eq!(node_txn[0].output.len(), 1);
7458                         check_spends!(node_txn[0], revoked_txn[0]);
7459                         penalty_2 = node_txn[0].txid();
7460                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7461                         assert_ne!(penalty_2, penalty_1);
7462                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7463                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7464                         // Verify 25% bump heuristic
7465                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7466                         node_txn.clear();
7467                 }
7468         }
7469         assert_ne!(feerate_2, 0);
7470
7471         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7472         connect_blocks(&nodes[1], 1);
7473         let penalty_3;
7474         let mut feerate_3 = 0;
7475         {
7476                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7477                 assert_eq!(node_txn.len(), 1);
7478                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7479                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7480                         assert_eq!(node_txn[0].output.len(), 1);
7481                         check_spends!(node_txn[0], revoked_txn[0]);
7482                         penalty_3 = node_txn[0].txid();
7483                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7484                         assert_ne!(penalty_3, penalty_2);
7485                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7486                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7487                         // Verify 25% bump heuristic
7488                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7489                         node_txn.clear();
7490                 }
7491         }
7492         assert_ne!(feerate_3, 0);
7493
7494         nodes[1].node.get_and_clear_pending_events();
7495         nodes[1].node.get_and_clear_pending_msg_events();
7496 }
7497
7498 #[test]
7499 fn test_bump_penalty_txn_on_revoked_htlcs() {
7500         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7501         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7502
7503         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7504         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7507         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7508
7509         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7510         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7511         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();
7512         let scorer = test_utils::TestScorer::new();
7513         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7514         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7515         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7516                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7517         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7518         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7519                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7520         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7521         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7522                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7523         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7524
7525         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7526         assert_eq!(revoked_local_txn[0].input.len(), 1);
7527         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7528
7529         // Revoke local commitment tx
7530         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7531
7532         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7533         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7534         check_closed_broadcast!(nodes[1], true);
7535         check_added_monitors!(nodes[1], 1);
7536         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7537         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7538
7539         let revoked_htlc_txn = {
7540                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7541                 assert_eq!(txn.len(), 2);
7542
7543                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7544                 assert_eq!(txn[0].input.len(), 1);
7545                 check_spends!(txn[0], revoked_local_txn[0]);
7546
7547                 assert_eq!(txn[1].input.len(), 1);
7548                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7549                 assert_eq!(txn[1].output.len(), 1);
7550                 check_spends!(txn[1], revoked_local_txn[0]);
7551
7552                 txn
7553         };
7554
7555         // Broadcast set of revoked txn on A
7556         let hash_128 = connect_blocks(&nodes[0], 40);
7557         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7558         connect_block(&nodes[0], &block_11);
7559         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7560         connect_block(&nodes[0], &block_129);
7561         let events = nodes[0].node.get_and_clear_pending_events();
7562         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7563         match events.last().unwrap() {
7564                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7565                 _ => panic!("Unexpected event"),
7566         }
7567         let first;
7568         let feerate_1;
7569         let penalty_txn;
7570         {
7571                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7572                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7573                 // Verify claim tx are spending revoked HTLC txn
7574
7575                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7576                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7577                 // which are included in the same block (they are broadcasted because we scan the
7578                 // transactions linearly and generate claims as we go, they likely should be removed in the
7579                 // future).
7580                 assert_eq!(node_txn[0].input.len(), 1);
7581                 check_spends!(node_txn[0], revoked_local_txn[0]);
7582                 assert_eq!(node_txn[1].input.len(), 1);
7583                 check_spends!(node_txn[1], revoked_local_txn[0]);
7584                 assert_eq!(node_txn[2].input.len(), 1);
7585                 check_spends!(node_txn[2], revoked_local_txn[0]);
7586
7587                 // Each of the three justice transactions claim a separate (single) output of the three
7588                 // available, which we check here:
7589                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7590                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7591                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7592
7593                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7594                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7595
7596                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7597                 // output, checked above).
7598                 assert_eq!(node_txn[3].input.len(), 2);
7599                 assert_eq!(node_txn[3].output.len(), 1);
7600                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7601
7602                 first = node_txn[3].txid();
7603                 // Store both feerates for later comparison
7604                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7605                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7606                 penalty_txn = vec![node_txn[2].clone()];
7607                 node_txn.clear();
7608         }
7609
7610         // Connect one more block to see if bumped penalty are issued for HTLC txn
7611         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7612         connect_block(&nodes[0], &block_130);
7613         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7614         connect_block(&nodes[0], &block_131);
7615
7616         // Few more blocks to confirm penalty txn
7617         connect_blocks(&nodes[0], 4);
7618         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7619         let header_144 = connect_blocks(&nodes[0], 9);
7620         let node_txn = {
7621                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7622                 assert_eq!(node_txn.len(), 1);
7623
7624                 assert_eq!(node_txn[0].input.len(), 2);
7625                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7626                 // Verify bumped tx is different and 25% bump heuristic
7627                 assert_ne!(first, node_txn[0].txid());
7628                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7629                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7630                 assert!(feerate_2 * 100 > feerate_1 * 125);
7631                 let txn = vec![node_txn[0].clone()];
7632                 node_txn.clear();
7633                 txn
7634         };
7635         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7636         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7637         connect_blocks(&nodes[0], 20);
7638         {
7639                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7640                 // We verify than no new transaction has been broadcast because previously
7641                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7642                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7643                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7644                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7645                 // up bumped justice generation.
7646                 assert_eq!(node_txn.len(), 0);
7647                 node_txn.clear();
7648         }
7649         check_closed_broadcast!(nodes[0], true);
7650         check_added_monitors!(nodes[0], 1);
7651 }
7652
7653 #[test]
7654 fn test_bump_penalty_txn_on_remote_commitment() {
7655         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7656         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7657
7658         // Create 2 HTLCs
7659         // Provide preimage for one
7660         // Check aggregation
7661
7662         let chanmon_cfgs = create_chanmon_cfgs(2);
7663         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7664         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7665         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7666
7667         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7668         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7669         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7670
7671         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7672         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7673         assert_eq!(remote_txn[0].output.len(), 4);
7674         assert_eq!(remote_txn[0].input.len(), 1);
7675         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7676
7677         // Claim a HTLC without revocation (provide B monitor with preimage)
7678         nodes[1].node.claim_funds(payment_preimage);
7679         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7680         mine_transaction(&nodes[1], &remote_txn[0]);
7681         check_added_monitors!(nodes[1], 2);
7682         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7683
7684         // One or more claim tx should have been broadcast, check it
7685         let timeout;
7686         let preimage;
7687         let preimage_bump;
7688         let feerate_timeout;
7689         let feerate_preimage;
7690         {
7691                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7692                 // 3 transactions including:
7693                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7694                 assert_eq!(node_txn.len(), 3);
7695                 assert_eq!(node_txn[0].input.len(), 1);
7696                 assert_eq!(node_txn[1].input.len(), 1);
7697                 assert_eq!(node_txn[2].input.len(), 1);
7698                 check_spends!(node_txn[0], remote_txn[0]);
7699                 check_spends!(node_txn[1], remote_txn[0]);
7700                 check_spends!(node_txn[2], remote_txn[0]);
7701
7702                 preimage = node_txn[0].txid();
7703                 let index = node_txn[0].input[0].previous_output.vout;
7704                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7705                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7706
7707                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7708                         (node_txn[2].clone(), node_txn[1].clone())
7709                 } else {
7710                         (node_txn[1].clone(), node_txn[2].clone())
7711                 };
7712
7713                 preimage_bump = preimage_bump_tx;
7714                 check_spends!(preimage_bump, remote_txn[0]);
7715                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7716
7717                 timeout = timeout_tx.txid();
7718                 let index = timeout_tx.input[0].previous_output.vout;
7719                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7720                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7721
7722                 node_txn.clear();
7723         };
7724         assert_ne!(feerate_timeout, 0);
7725         assert_ne!(feerate_preimage, 0);
7726
7727         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7728         connect_blocks(&nodes[1], 1);
7729         {
7730                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7731                 assert_eq!(node_txn.len(), 1);
7732                 assert_eq!(node_txn[0].input.len(), 1);
7733                 assert_eq!(preimage_bump.input.len(), 1);
7734                 check_spends!(node_txn[0], remote_txn[0]);
7735                 check_spends!(preimage_bump, remote_txn[0]);
7736
7737                 let index = preimage_bump.input[0].previous_output.vout;
7738                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7739                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7740                 assert!(new_feerate * 100 > feerate_timeout * 125);
7741                 assert_ne!(timeout, preimage_bump.txid());
7742
7743                 let index = node_txn[0].input[0].previous_output.vout;
7744                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7745                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7746                 assert!(new_feerate * 100 > feerate_preimage * 125);
7747                 assert_ne!(preimage, node_txn[0].txid());
7748
7749                 node_txn.clear();
7750         }
7751
7752         nodes[1].node.get_and_clear_pending_events();
7753         nodes[1].node.get_and_clear_pending_msg_events();
7754 }
7755
7756 #[test]
7757 fn test_counterparty_raa_skip_no_crash() {
7758         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7759         // commitment transaction, we would have happily carried on and provided them the next
7760         // commitment transaction based on one RAA forward. This would probably eventually have led to
7761         // channel closure, but it would not have resulted in funds loss. Still, our
7762         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7763         // check simply that the channel is closed in response to such an RAA, but don't check whether
7764         // we decide to punish our counterparty for revoking their funds (as we don't currently
7765         // implement that).
7766         let chanmon_cfgs = create_chanmon_cfgs(2);
7767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7770         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7771
7772         let per_commitment_secret;
7773         let next_per_commitment_point;
7774         {
7775                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7776                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7777                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7778                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7779                 ).flatten().unwrap().get_signer();
7780
7781                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7782
7783                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7784                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7785                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7786
7787                 // Must revoke without gaps
7788                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7789                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7790
7791                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7792                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7793                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7794         }
7795
7796         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7797                 &msgs::RevokeAndACK {
7798                         channel_id,
7799                         per_commitment_secret,
7800                         next_per_commitment_point,
7801                         #[cfg(taproot)]
7802                         next_local_nonce: None,
7803                 });
7804         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7805         check_added_monitors!(nodes[1], 1);
7806         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7807                 , [nodes[0].node.get_our_node_id()], 100000);
7808 }
7809
7810 #[test]
7811 fn test_bump_txn_sanitize_tracking_maps() {
7812         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7813         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7814
7815         let chanmon_cfgs = create_chanmon_cfgs(2);
7816         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7817         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7818         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7819
7820         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7821         // Lock HTLC in both directions
7822         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7823         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7824
7825         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7826         assert_eq!(revoked_local_txn[0].input.len(), 1);
7827         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7828
7829         // Revoke local commitment tx
7830         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7831
7832         // Broadcast set of revoked txn on A
7833         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7834         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7835         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7836
7837         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7838         check_closed_broadcast!(nodes[0], true);
7839         check_added_monitors!(nodes[0], 1);
7840         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7841         let penalty_txn = {
7842                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7843                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7844                 check_spends!(node_txn[0], revoked_local_txn[0]);
7845                 check_spends!(node_txn[1], revoked_local_txn[0]);
7846                 check_spends!(node_txn[2], revoked_local_txn[0]);
7847                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7848                 node_txn.clear();
7849                 penalty_txn
7850         };
7851         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7852         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7853         {
7854                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7855                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7856                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7857         }
7858 }
7859
7860 #[test]
7861 fn test_channel_conf_timeout() {
7862         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7863         // confirm within 2016 blocks, as recommended by BOLT 2.
7864         let chanmon_cfgs = create_chanmon_cfgs(2);
7865         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7866         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7867         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7868
7869         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7870
7871         // The outbound node should wait forever for confirmation:
7872         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7873         // copied here instead of directly referencing the constant.
7874         connect_blocks(&nodes[0], 2016);
7875         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7876
7877         // The inbound node should fail the channel after exactly 2016 blocks
7878         connect_blocks(&nodes[1], 2015);
7879         check_added_monitors!(nodes[1], 0);
7880         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7881
7882         connect_blocks(&nodes[1], 1);
7883         check_added_monitors!(nodes[1], 1);
7884         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7885         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7886         assert_eq!(close_ev.len(), 1);
7887         match close_ev[0] {
7888                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7889                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7890                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7891                 },
7892                 _ => panic!("Unexpected event"),
7893         }
7894 }
7895
7896 #[test]
7897 fn test_override_channel_config() {
7898         let chanmon_cfgs = create_chanmon_cfgs(2);
7899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7901         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7902
7903         // Node0 initiates a channel to node1 using the override config.
7904         let mut override_config = UserConfig::default();
7905         override_config.channel_handshake_config.our_to_self_delay = 200;
7906
7907         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7908
7909         // Assert the channel created by node0 is using the override config.
7910         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7911         assert_eq!(res.channel_flags, 0);
7912         assert_eq!(res.to_self_delay, 200);
7913 }
7914
7915 #[test]
7916 fn test_override_0msat_htlc_minimum() {
7917         let mut zero_config = UserConfig::default();
7918         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7919         let chanmon_cfgs = create_chanmon_cfgs(2);
7920         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7921         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7922         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7923
7924         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7925         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7926         assert_eq!(res.htlc_minimum_msat, 1);
7927
7928         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7929         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7930         assert_eq!(res.htlc_minimum_msat, 1);
7931 }
7932
7933 #[test]
7934 fn test_channel_update_has_correct_htlc_maximum_msat() {
7935         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7936         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7937         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7938         // 90% of the `channel_value`.
7939         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7940
7941         let mut config_30_percent = UserConfig::default();
7942         config_30_percent.channel_handshake_config.announced_channel = true;
7943         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7944         let mut config_50_percent = UserConfig::default();
7945         config_50_percent.channel_handshake_config.announced_channel = true;
7946         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7947         let mut config_95_percent = UserConfig::default();
7948         config_95_percent.channel_handshake_config.announced_channel = true;
7949         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7950         let mut config_100_percent = UserConfig::default();
7951         config_100_percent.channel_handshake_config.announced_channel = true;
7952         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7953
7954         let chanmon_cfgs = create_chanmon_cfgs(4);
7955         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7956         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)]);
7957         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7958
7959         let channel_value_satoshis = 100000;
7960         let channel_value_msat = channel_value_satoshis * 1000;
7961         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7962         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7963         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7964
7965         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7966         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7967
7968         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7969         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7970         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7971         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7972         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7973         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7974
7975         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7976         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7977         // `channel_value`.
7978         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7979         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7980         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7981         // `channel_value`.
7982         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7983 }
7984
7985 #[test]
7986 fn test_manually_accept_inbound_channel_request() {
7987         let mut manually_accept_conf = UserConfig::default();
7988         manually_accept_conf.manually_accept_inbound_channels = true;
7989         let chanmon_cfgs = create_chanmon_cfgs(2);
7990         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7991         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7992         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7993
7994         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();
7995         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7996
7997         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7998
7999         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8000         // accepting the inbound channel request.
8001         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8002
8003         let events = nodes[1].node.get_and_clear_pending_events();
8004         match events[0] {
8005                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8006                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8007                 }
8008                 _ => panic!("Unexpected event"),
8009         }
8010
8011         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8012         assert_eq!(accept_msg_ev.len(), 1);
8013
8014         match accept_msg_ev[0] {
8015                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8016                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8017                 }
8018                 _ => panic!("Unexpected event"),
8019         }
8020
8021         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8022
8023         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8024         assert_eq!(close_msg_ev.len(), 1);
8025
8026         let events = nodes[1].node.get_and_clear_pending_events();
8027         match events[0] {
8028                 Event::ChannelClosed { user_channel_id, .. } => {
8029                         assert_eq!(user_channel_id, 23);
8030                 }
8031                 _ => panic!("Unexpected event"),
8032         }
8033 }
8034
8035 #[test]
8036 fn test_manually_reject_inbound_channel_request() {
8037         let mut manually_accept_conf = UserConfig::default();
8038         manually_accept_conf.manually_accept_inbound_channels = true;
8039         let chanmon_cfgs = create_chanmon_cfgs(2);
8040         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8041         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8042         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8043
8044         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8045         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8046
8047         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8048
8049         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8050         // rejecting the inbound channel request.
8051         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8052
8053         let events = nodes[1].node.get_and_clear_pending_events();
8054         match events[0] {
8055                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8056                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8057                 }
8058                 _ => panic!("Unexpected event"),
8059         }
8060
8061         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8062         assert_eq!(close_msg_ev.len(), 1);
8063
8064         match close_msg_ev[0] {
8065                 MessageSendEvent::HandleError { ref node_id, .. } => {
8066                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8067                 }
8068                 _ => panic!("Unexpected event"),
8069         }
8070
8071         // There should be no more events to process, as the channel was never opened.
8072         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8073 }
8074
8075 #[test]
8076 fn test_can_not_accept_inbound_channel_twice() {
8077         let mut manually_accept_conf = UserConfig::default();
8078         manually_accept_conf.manually_accept_inbound_channels = true;
8079         let chanmon_cfgs = create_chanmon_cfgs(2);
8080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8082         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8083
8084         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8085         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8086
8087         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8088
8089         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8090         // accepting the inbound channel request.
8091         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8092
8093         let events = nodes[1].node.get_and_clear_pending_events();
8094         match events[0] {
8095                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8096                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8097                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8098                         match api_res {
8099                                 Err(APIError::APIMisuseError { err }) => {
8100                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8101                                 },
8102                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8103                                 Err(e) => panic!("Unexpected Error {:?}", e),
8104                         }
8105                 }
8106                 _ => panic!("Unexpected event"),
8107         }
8108
8109         // Ensure that the channel wasn't closed after attempting to accept it twice.
8110         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8111         assert_eq!(accept_msg_ev.len(), 1);
8112
8113         match accept_msg_ev[0] {
8114                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8115                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8116                 }
8117                 _ => panic!("Unexpected event"),
8118         }
8119 }
8120
8121 #[test]
8122 fn test_can_not_accept_unknown_inbound_channel() {
8123         let chanmon_cfg = create_chanmon_cfgs(2);
8124         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8125         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8126         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8127
8128         let unknown_channel_id = ChannelId::new_zero();
8129         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8130         match api_res {
8131                 Err(APIError::APIMisuseError { err }) => {
8132                         assert_eq!(err, "No such channel awaiting to be accepted.");
8133                 },
8134                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8135                 Err(e) => panic!("Unexpected Error: {:?}", e),
8136         }
8137 }
8138
8139 #[test]
8140 fn test_onion_value_mpp_set_calculation() {
8141         // Test that we use the onion value `amt_to_forward` when
8142         // calculating whether we've reached the `total_msat` of an MPP
8143         // by having a routing node forward more than `amt_to_forward`
8144         // and checking that the receiving node doesn't generate
8145         // a PaymentClaimable event too early
8146         let node_count = 4;
8147         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8148         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8149         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8150         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8151
8152         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8153         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8154         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8155         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8156
8157         let total_msat = 100_000;
8158         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8159         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8160         let sample_path = route.paths.pop().unwrap();
8161
8162         let mut path_1 = sample_path.clone();
8163         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8164         path_1.hops[0].short_channel_id = chan_1_id;
8165         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8166         path_1.hops[1].short_channel_id = chan_3_id;
8167         path_1.hops[1].fee_msat = 100_000;
8168         route.paths.push(path_1);
8169
8170         let mut path_2 = sample_path.clone();
8171         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8172         path_2.hops[0].short_channel_id = chan_2_id;
8173         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8174         path_2.hops[1].short_channel_id = chan_4_id;
8175         path_2.hops[1].fee_msat = 1_000;
8176         route.paths.push(path_2);
8177
8178         // Send payment
8179         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8180         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8181                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8182         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8183                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8184         check_added_monitors!(nodes[0], expected_paths.len());
8185
8186         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8187         assert_eq!(events.len(), expected_paths.len());
8188
8189         // First path
8190         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8191         let mut payment_event = SendEvent::from_event(ev);
8192         let mut prev_node = &nodes[0];
8193
8194         for (idx, &node) in expected_paths[0].iter().enumerate() {
8195                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8196
8197                 if idx == 0 { // routing node
8198                         let session_priv = [3; 32];
8199                         let height = nodes[0].best_block_info().1;
8200                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8201                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8202                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8203                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8204                         // Edit amt_to_forward to simulate the sender having set
8205                         // the final amount and the routing node taking less fee
8206                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8207                                 *amt_msat = 99_000;
8208                         } else { panic!() }
8209                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8210                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8211                 }
8212
8213                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8214                 check_added_monitors!(node, 0);
8215                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8216                 expect_pending_htlcs_forwardable!(node);
8217
8218                 if idx == 0 {
8219                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8220                         assert_eq!(events_2.len(), 1);
8221                         check_added_monitors!(node, 1);
8222                         payment_event = SendEvent::from_event(events_2.remove(0));
8223                         assert_eq!(payment_event.msgs.len(), 1);
8224                 } else {
8225                         let events_2 = node.node.get_and_clear_pending_events();
8226                         assert!(events_2.is_empty());
8227                 }
8228
8229                 prev_node = node;
8230         }
8231
8232         // Second path
8233         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8234         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8235
8236         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8237 }
8238
8239 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8240
8241         let routing_node_count = msat_amounts.len();
8242         let node_count = routing_node_count + 2;
8243
8244         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8245         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8246         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8247         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8248
8249         let src_idx = 0;
8250         let dst_idx = 1;
8251
8252         // Create channels for each amount
8253         let mut expected_paths = Vec::with_capacity(routing_node_count);
8254         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8255         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8256         for i in 0..routing_node_count {
8257                 let routing_node = 2 + i;
8258                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8259                 src_chan_ids.push(src_chan_id);
8260                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8261                 dst_chan_ids.push(dst_chan_id);
8262                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8263                 expected_paths.push(path);
8264         }
8265         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8266
8267         // Create a route for each amount
8268         let example_amount = 100000;
8269         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);
8270         let sample_path = route.paths.pop().unwrap();
8271         for i in 0..routing_node_count {
8272                 let routing_node = 2 + i;
8273                 let mut path = sample_path.clone();
8274                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8275                 path.hops[0].short_channel_id = src_chan_ids[i];
8276                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8277                 path.hops[1].short_channel_id = dst_chan_ids[i];
8278                 path.hops[1].fee_msat = msat_amounts[i];
8279                 route.paths.push(path);
8280         }
8281
8282         // Send payment with manually set total_msat
8283         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8284         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8285                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8286         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8287                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8288         check_added_monitors!(nodes[src_idx], expected_paths.len());
8289
8290         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8291         assert_eq!(events.len(), expected_paths.len());
8292         let mut amount_received = 0;
8293         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8294                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8295
8296                 let current_path_amount = msat_amounts[path_idx];
8297                 amount_received += current_path_amount;
8298                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8299                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8300         }
8301
8302         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8303 }
8304
8305 #[test]
8306 fn test_overshoot_mpp() {
8307         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8308         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8309 }
8310
8311 #[test]
8312 fn test_simple_mpp() {
8313         // Simple test of sending a multi-path payment.
8314         let chanmon_cfgs = create_chanmon_cfgs(4);
8315         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8316         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8317         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8318
8319         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8320         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8321         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8322         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8323
8324         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8325         let path = route.paths[0].clone();
8326         route.paths.push(path);
8327         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8328         route.paths[0].hops[0].short_channel_id = chan_1_id;
8329         route.paths[0].hops[1].short_channel_id = chan_3_id;
8330         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8331         route.paths[1].hops[0].short_channel_id = chan_2_id;
8332         route.paths[1].hops[1].short_channel_id = chan_4_id;
8333         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8334         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8335 }
8336
8337 #[test]
8338 fn test_preimage_storage() {
8339         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8340         let chanmon_cfgs = create_chanmon_cfgs(2);
8341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8343         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8344
8345         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8346
8347         {
8348                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8349                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8350                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8351                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8352                 check_added_monitors!(nodes[0], 1);
8353                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8354                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8355                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8356                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8357         }
8358         // Note that after leaving the above scope we have no knowledge of any arguments or return
8359         // values from previous calls.
8360         expect_pending_htlcs_forwardable!(nodes[1]);
8361         let events = nodes[1].node.get_and_clear_pending_events();
8362         assert_eq!(events.len(), 1);
8363         match events[0] {
8364                 Event::PaymentClaimable { ref purpose, .. } => {
8365                         match &purpose {
8366                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8367                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8368                                 },
8369                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8370                         }
8371                 },
8372                 _ => panic!("Unexpected event"),
8373         }
8374 }
8375
8376 #[test]
8377 fn test_bad_secret_hash() {
8378         // Simple test of unregistered payment hash/invalid payment secret handling
8379         let chanmon_cfgs = create_chanmon_cfgs(2);
8380         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8381         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8382         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8383
8384         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8385
8386         let random_payment_hash = PaymentHash([42; 32]);
8387         let random_payment_secret = PaymentSecret([43; 32]);
8388         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8389         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8390
8391         // All the below cases should end up being handled exactly identically, so we macro the
8392         // resulting events.
8393         macro_rules! handle_unknown_invalid_payment_data {
8394                 ($payment_hash: expr) => {
8395                         check_added_monitors!(nodes[0], 1);
8396                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8397                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8398                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8399                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8400
8401                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8402                         // again to process the pending backwards-failure of the HTLC
8403                         expect_pending_htlcs_forwardable!(nodes[1]);
8404                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8405                         check_added_monitors!(nodes[1], 1);
8406
8407                         // We should fail the payment back
8408                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8409                         match events.pop().unwrap() {
8410                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8411                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8412                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8413                                 },
8414                                 _ => panic!("Unexpected event"),
8415                         }
8416                 }
8417         }
8418
8419         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8420         // Error data is the HTLC value (100,000) and current block height
8421         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8422
8423         // Send a payment with the right payment hash but the wrong payment secret
8424         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8425                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8426         handle_unknown_invalid_payment_data!(our_payment_hash);
8427         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8428
8429         // Send a payment with a random payment hash, but the right payment secret
8430         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8431                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8432         handle_unknown_invalid_payment_data!(random_payment_hash);
8433         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8434
8435         // Send a payment with a random payment hash and random payment secret
8436         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8437                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8438         handle_unknown_invalid_payment_data!(random_payment_hash);
8439         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8440 }
8441
8442 #[test]
8443 fn test_update_err_monitor_lockdown() {
8444         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8445         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8446         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8447         // error.
8448         //
8449         // This scenario may happen in a watchtower setup, where watchtower process a block height
8450         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8451         // commitment at same time.
8452
8453         let chanmon_cfgs = create_chanmon_cfgs(2);
8454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8456         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8457
8458         // Create some initial channel
8459         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8460         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8461
8462         // Rebalance the network to generate htlc in the two directions
8463         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8464
8465         // Route a HTLC from node 0 to node 1 (but don't settle)
8466         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8467
8468         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8469         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8470         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8471         let persister = test_utils::TestPersister::new();
8472         let watchtower = {
8473                 let new_monitor = {
8474                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8475                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8476                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8477                         assert!(new_monitor == *monitor);
8478                         new_monitor
8479                 };
8480                 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);
8481                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8482                 watchtower
8483         };
8484         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8485         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8486         // transaction lock time requirements here.
8487         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8488         watchtower.chain_monitor.block_connected(&block, 200);
8489
8490         // Try to update ChannelMonitor
8491         nodes[1].node.claim_funds(preimage);
8492         check_added_monitors!(nodes[1], 1);
8493         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8494
8495         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8496         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8497         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8498         {
8499                 let mut node_0_per_peer_lock;
8500                 let mut node_0_peer_state_lock;
8501                 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) {
8502                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8503                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8504                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8505                         } else { assert!(false); }
8506                 } else {
8507                         assert!(false);
8508                 }
8509         }
8510         // Our local monitor is in-sync and hasn't processed yet timeout
8511         check_added_monitors!(nodes[0], 1);
8512         let events = nodes[0].node.get_and_clear_pending_events();
8513         assert_eq!(events.len(), 1);
8514 }
8515
8516 #[test]
8517 fn test_concurrent_monitor_claim() {
8518         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8519         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8520         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8521         // state N+1 confirms. Alice claims output from state N+1.
8522
8523         let chanmon_cfgs = create_chanmon_cfgs(2);
8524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8526         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8527
8528         // Create some initial channel
8529         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8530         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8531
8532         // Rebalance the network to generate htlc in the two directions
8533         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8534
8535         // Route a HTLC from node 0 to node 1 (but don't settle)
8536         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8537
8538         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8539         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8540         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8541         let persister = test_utils::TestPersister::new();
8542         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8543                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8544         );
8545         let watchtower_alice = {
8546                 let new_monitor = {
8547                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8548                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8549                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8550                         assert!(new_monitor == *monitor);
8551                         new_monitor
8552                 };
8553                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8554                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8555                 watchtower
8556         };
8557         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8558         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8559         // requirements here.
8560         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8561         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8562         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8563
8564         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8565         let alice_state = {
8566                 let mut txn = alice_broadcaster.txn_broadcast();
8567                 assert_eq!(txn.len(), 2);
8568                 txn.remove(0)
8569         };
8570
8571         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8572         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8573         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8574         let persister = test_utils::TestPersister::new();
8575         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8576         let watchtower_bob = {
8577                 let new_monitor = {
8578                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8579                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8580                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8581                         assert!(new_monitor == *monitor);
8582                         new_monitor
8583                 };
8584                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8585                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8586                 watchtower
8587         };
8588         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8589
8590         // Route another payment to generate another update with still previous HTLC pending
8591         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8592         nodes[1].node.send_payment_with_route(&route, payment_hash,
8593                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8594         check_added_monitors!(nodes[1], 1);
8595
8596         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8597         assert_eq!(updates.update_add_htlcs.len(), 1);
8598         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8599         {
8600                 let mut node_0_per_peer_lock;
8601                 let mut node_0_peer_state_lock;
8602                 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) {
8603                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8604                                 // Watchtower Alice should already have seen the block and reject the update
8605                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8606                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8607                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8608                         } else { assert!(false); }
8609                 } else {
8610                         assert!(false);
8611                 }
8612         }
8613         // Our local monitor is in-sync and hasn't processed yet timeout
8614         check_added_monitors!(nodes[0], 1);
8615
8616         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8617         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8618
8619         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8620         let bob_state_y;
8621         {
8622                 let mut txn = bob_broadcaster.txn_broadcast();
8623                 assert_eq!(txn.len(), 2);
8624                 bob_state_y = txn.remove(0);
8625         };
8626
8627         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8628         let height = HTLC_TIMEOUT_BROADCAST + 1;
8629         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8630         check_closed_broadcast(&nodes[0], 1, true);
8631         check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8632                 [nodes[1].node.get_our_node_id()], 100000);
8633         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8634         check_added_monitors(&nodes[0], 1);
8635         {
8636                 let htlc_txn = alice_broadcaster.txn_broadcast();
8637                 assert_eq!(htlc_txn.len(), 2);
8638                 check_spends!(htlc_txn[0], bob_state_y);
8639                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8640                 // it. However, she should, because it now has an invalid parent.
8641                 check_spends!(htlc_txn[1], alice_state);
8642         }
8643 }
8644
8645 #[test]
8646 fn test_pre_lockin_no_chan_closed_update() {
8647         // Test that if a peer closes a channel in response to a funding_created message we don't
8648         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8649         // message).
8650         //
8651         // Doing so would imply a channel monitor update before the initial channel monitor
8652         // registration, violating our API guarantees.
8653         //
8654         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8655         // then opening a second channel with the same funding output as the first (which is not
8656         // rejected because the first channel does not exist in the ChannelManager) and closing it
8657         // before receiving funding_signed.
8658         let chanmon_cfgs = create_chanmon_cfgs(2);
8659         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8660         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8661         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8662
8663         // Create an initial channel
8664         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8665         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8666         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8667         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8668         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8669
8670         // Move the first channel through the funding flow...
8671         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8672
8673         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8674         check_added_monitors!(nodes[0], 0);
8675
8676         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8677         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8678         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8679         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8680         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8681                 [nodes[1].node.get_our_node_id()], 100000);
8682 }
8683
8684 #[test]
8685 fn test_htlc_no_detection() {
8686         // This test is a mutation to underscore the detection logic bug we had
8687         // before #653. HTLC value routed is above the remaining balance, thus
8688         // inverting HTLC and `to_remote` output. HTLC will come second and
8689         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8690         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8691         // outputs order detection for correct spending children filtring.
8692
8693         let chanmon_cfgs = create_chanmon_cfgs(2);
8694         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8695         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8696         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8697
8698         // Create some initial channels
8699         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8700
8701         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8702         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8703         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8704         assert_eq!(local_txn[0].input.len(), 1);
8705         assert_eq!(local_txn[0].output.len(), 3);
8706         check_spends!(local_txn[0], chan_1.3);
8707
8708         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8709         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8710         connect_block(&nodes[0], &block);
8711         // We deliberately connect the local tx twice as this should provoke a failure calling
8712         // this test before #653 fix.
8713         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8714         check_closed_broadcast!(nodes[0], true);
8715         check_added_monitors!(nodes[0], 1);
8716         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8717         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8718
8719         let htlc_timeout = {
8720                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8721                 assert_eq!(node_txn.len(), 1);
8722                 assert_eq!(node_txn[0].input.len(), 1);
8723                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8724                 check_spends!(node_txn[0], local_txn[0]);
8725                 node_txn[0].clone()
8726         };
8727
8728         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8729         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8730         expect_payment_failed!(nodes[0], our_payment_hash, false);
8731 }
8732
8733 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8734         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8735         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8736         // Carol, Alice would be the upstream node, and Carol the downstream.)
8737         //
8738         // Steps of the test:
8739         // 1) Alice sends a HTLC to Carol through Bob.
8740         // 2) Carol doesn't settle the HTLC.
8741         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8742         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8743         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8744         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8745         // 5) Carol release the preimage to Bob off-chain.
8746         // 6) Bob claims the offered output on the broadcasted commitment.
8747         let chanmon_cfgs = create_chanmon_cfgs(3);
8748         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8749         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8750         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8751
8752         // Create some initial channels
8753         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8754         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8755
8756         // Steps (1) and (2):
8757         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8758         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8759
8760         // Check that Alice's commitment transaction now contains an output for this HTLC.
8761         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8762         check_spends!(alice_txn[0], chan_ab.3);
8763         assert_eq!(alice_txn[0].output.len(), 2);
8764         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8765         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8766         assert_eq!(alice_txn.len(), 2);
8767
8768         // Steps (3) and (4):
8769         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8770         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8771         let mut force_closing_node = 0; // Alice force-closes
8772         let mut counterparty_node = 1; // Bob if Alice force-closes
8773
8774         // Bob force-closes
8775         if !broadcast_alice {
8776                 force_closing_node = 1;
8777                 counterparty_node = 0;
8778         }
8779         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8780         check_closed_broadcast!(nodes[force_closing_node], true);
8781         check_added_monitors!(nodes[force_closing_node], 1);
8782         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8783         if go_onchain_before_fulfill {
8784                 let txn_to_broadcast = match broadcast_alice {
8785                         true => alice_txn.clone(),
8786                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8787                 };
8788                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8789                 if broadcast_alice {
8790                         check_closed_broadcast!(nodes[1], true);
8791                         check_added_monitors!(nodes[1], 1);
8792                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8793                 }
8794         }
8795
8796         // Step (5):
8797         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8798         // process of removing the HTLC from their commitment transactions.
8799         nodes[2].node.claim_funds(payment_preimage);
8800         check_added_monitors!(nodes[2], 1);
8801         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8802
8803         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8804         assert!(carol_updates.update_add_htlcs.is_empty());
8805         assert!(carol_updates.update_fail_htlcs.is_empty());
8806         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8807         assert!(carol_updates.update_fee.is_none());
8808         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8809
8810         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8811         let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8812         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8813         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8814         if !go_onchain_before_fulfill && broadcast_alice {
8815                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8816                 assert_eq!(events.len(), 1);
8817                 match events[0] {
8818                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8819                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8820                         },
8821                         _ => panic!("Unexpected event"),
8822                 };
8823         }
8824         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8825         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8826         // Carol<->Bob's updated commitment transaction info.
8827         check_added_monitors!(nodes[1], 2);
8828
8829         let events = nodes[1].node.get_and_clear_pending_msg_events();
8830         assert_eq!(events.len(), 2);
8831         let bob_revocation = match events[0] {
8832                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8833                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8834                         (*msg).clone()
8835                 },
8836                 _ => panic!("Unexpected event"),
8837         };
8838         let bob_updates = match events[1] {
8839                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8840                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8841                         (*updates).clone()
8842                 },
8843                 _ => panic!("Unexpected event"),
8844         };
8845
8846         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8847         check_added_monitors!(nodes[2], 1);
8848         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8849         check_added_monitors!(nodes[2], 1);
8850
8851         let events = nodes[2].node.get_and_clear_pending_msg_events();
8852         assert_eq!(events.len(), 1);
8853         let carol_revocation = match events[0] {
8854                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8855                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8856                         (*msg).clone()
8857                 },
8858                 _ => panic!("Unexpected event"),
8859         };
8860         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8861         check_added_monitors!(nodes[1], 1);
8862
8863         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8864         // here's where we put said channel's commitment tx on-chain.
8865         let mut txn_to_broadcast = alice_txn.clone();
8866         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8867         if !go_onchain_before_fulfill {
8868                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8869                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8870                 if broadcast_alice {
8871                         check_closed_broadcast!(nodes[1], true);
8872                         check_added_monitors!(nodes[1], 1);
8873                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8874                 }
8875                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8876                 if broadcast_alice {
8877                         assert_eq!(bob_txn.len(), 1);
8878                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8879                 } else {
8880                         assert_eq!(bob_txn.len(), 2);
8881                         check_spends!(bob_txn[0], chan_ab.3);
8882                 }
8883         }
8884
8885         // Step (6):
8886         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8887         // broadcasted commitment transaction.
8888         {
8889                 let script_weight = match broadcast_alice {
8890                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8891                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8892                 };
8893                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8894                 // Bob force-closed and broadcasts the commitment transaction along with a
8895                 // HTLC-output-claiming transaction.
8896                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8897                 if broadcast_alice {
8898                         assert_eq!(bob_txn.len(), 1);
8899                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8900                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8901                 } else {
8902                         assert_eq!(bob_txn.len(), 2);
8903                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8904                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8905                 }
8906         }
8907 }
8908
8909 #[test]
8910 fn test_onchain_htlc_settlement_after_close() {
8911         do_test_onchain_htlc_settlement_after_close(true, true);
8912         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8913         do_test_onchain_htlc_settlement_after_close(true, false);
8914         do_test_onchain_htlc_settlement_after_close(false, false);
8915 }
8916
8917 #[test]
8918 fn test_duplicate_temporary_channel_id_from_different_peers() {
8919         // Tests that we can accept two different `OpenChannel` requests with the same
8920         // `temporary_channel_id`, as long as they are from different peers.
8921         let chanmon_cfgs = create_chanmon_cfgs(3);
8922         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8923         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8924         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8925
8926         // Create an first channel channel
8927         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8928         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8929
8930         // Create an second channel
8931         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8932         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8933
8934         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8935         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8936         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8937
8938         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8939         // `temporary_channel_id` as they are from different peers.
8940         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8941         {
8942                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8943                 assert_eq!(events.len(), 1);
8944                 match &events[0] {
8945                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8946                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8947                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8948                         },
8949                         _ => panic!("Unexpected event"),
8950                 }
8951         }
8952
8953         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_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[2].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
8967 #[test]
8968 fn test_duplicate_chan_id() {
8969         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8970         // already open we reject it and keep the old channel.
8971         //
8972         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8973         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8974         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8975         // updating logic for the existing channel.
8976         let chanmon_cfgs = create_chanmon_cfgs(2);
8977         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8978         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8979         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8980
8981         // Create an initial channel
8982         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8983         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8984         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8985         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()));
8986
8987         // Try to create a second channel with the same temporary_channel_id as the first and check
8988         // that it is rejected.
8989         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8990         {
8991                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8992                 assert_eq!(events.len(), 1);
8993                 match events[0] {
8994                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8995                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8996                                 // first (valid) and second (invalid) channels are closed, given they both have
8997                                 // the same non-temporary channel_id. However, currently we do not, so we just
8998                                 // move forward with it.
8999                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9000                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9001                         },
9002                         _ => panic!("Unexpected event"),
9003                 }
9004         }
9005
9006         // Move the first channel through the funding flow...
9007         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9008
9009         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9010         check_added_monitors!(nodes[0], 0);
9011
9012         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9013         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9014         {
9015                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9016                 assert_eq!(added_monitors.len(), 1);
9017                 assert_eq!(added_monitors[0].0, funding_output);
9018                 added_monitors.clear();
9019         }
9020         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9021
9022         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9023
9024         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9025         let channel_id = funding_outpoint.to_channel_id();
9026
9027         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9028         // temporary one).
9029
9030         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9031         // Technically this is allowed by the spec, but we don't support it and there's little reason
9032         // to. Still, it shouldn't cause any other issues.
9033         open_chan_msg.temporary_channel_id = channel_id;
9034         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9035         {
9036                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9037                 assert_eq!(events.len(), 1);
9038                 match events[0] {
9039                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9040                                 // Technically, at this point, nodes[1] would be justified in thinking both
9041                                 // channels are closed, but currently we do not, so we just move forward with it.
9042                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9043                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9044                         },
9045                         _ => panic!("Unexpected event"),
9046                 }
9047         }
9048
9049         // Now try to create a second channel which has a duplicate funding output.
9050         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9051         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9052         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9053         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()));
9054         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9055
9056         let (_, funding_created) = {
9057                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9058                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9059                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9060                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9061                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9062                 // channelmanager in a possibly nonsense state instead).
9063                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9064                         ChannelPhase::UnfundedOutboundV1(chan) => {
9065                                 let logger = test_utils::TestLogger::new();
9066                                 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9067                         },
9068                         _ => panic!("Unexpected ChannelPhase variant"),
9069                 }
9070         };
9071         check_added_monitors!(nodes[0], 0);
9072         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created.unwrap());
9073         // At this point we'll look up if the channel_id is present and immediately fail the channel
9074         // without trying to persist the `ChannelMonitor`.
9075         check_added_monitors!(nodes[1], 0);
9076
9077         // ...still, nodes[1] will reject the duplicate channel.
9078         {
9079                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9080                 assert_eq!(events.len(), 1);
9081                 match events[0] {
9082                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9083                                 // Technically, at this point, nodes[1] would be justified in thinking both
9084                                 // channels are closed, but currently we do not, so we just move forward with it.
9085                                 assert_eq!(msg.channel_id, channel_id);
9086                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9087                         },
9088                         _ => panic!("Unexpected event"),
9089                 }
9090         }
9091
9092         // finally, finish creating the original channel and send a payment over it to make sure
9093         // everything is functional.
9094         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9095         {
9096                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9097                 assert_eq!(added_monitors.len(), 1);
9098                 assert_eq!(added_monitors[0].0, funding_output);
9099                 added_monitors.clear();
9100         }
9101         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9102
9103         let events_4 = nodes[0].node.get_and_clear_pending_events();
9104         assert_eq!(events_4.len(), 0);
9105         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9106         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9107
9108         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9109         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9110         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9111
9112         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9113 }
9114
9115 #[test]
9116 fn test_error_chans_closed() {
9117         // Test that we properly handle error messages, closing appropriate channels.
9118         //
9119         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9120         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9121         // we can test various edge cases around it to ensure we don't regress.
9122         let chanmon_cfgs = create_chanmon_cfgs(3);
9123         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9124         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9125         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9126
9127         // Create some initial channels
9128         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9129         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9130         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9131
9132         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9133         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9134         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9135
9136         // Closing a channel from a different peer has no effect
9137         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9138         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9139
9140         // Closing one channel doesn't impact others
9141         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9142         check_added_monitors!(nodes[0], 1);
9143         check_closed_broadcast!(nodes[0], false);
9144         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9145                 [nodes[1].node.get_our_node_id()], 100000);
9146         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9147         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9148         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);
9149         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);
9150
9151         // A null channel ID should close all channels
9152         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9153         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9154         check_added_monitors!(nodes[0], 2);
9155         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9156                 [nodes[1].node.get_our_node_id(); 2], 100000);
9157         let events = nodes[0].node.get_and_clear_pending_msg_events();
9158         assert_eq!(events.len(), 2);
9159         match events[0] {
9160                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9161                         assert_eq!(msg.contents.flags & 2, 2);
9162                 },
9163                 _ => panic!("Unexpected event"),
9164         }
9165         match events[1] {
9166                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9167                         assert_eq!(msg.contents.flags & 2, 2);
9168                 },
9169                 _ => panic!("Unexpected event"),
9170         }
9171         // Note that at this point users of a standard PeerHandler will end up calling
9172         // peer_disconnected.
9173         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9174         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9175
9176         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9177         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9178         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9179 }
9180
9181 #[test]
9182 fn test_invalid_funding_tx() {
9183         // Test that we properly handle invalid funding transactions sent to us from a peer.
9184         //
9185         // Previously, all other major lightning implementations had failed to properly sanitize
9186         // funding transactions from their counterparties, leading to a multi-implementation critical
9187         // security vulnerability (though we always sanitized properly, we've previously had
9188         // un-released crashes in the sanitization process).
9189         //
9190         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9191         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9192         // gave up on it. We test this here by generating such a transaction.
9193         let chanmon_cfgs = create_chanmon_cfgs(2);
9194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9196         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9197
9198         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9199         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()));
9200         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()));
9201
9202         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9203
9204         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9205         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9206         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9207         // its length.
9208         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9209         let wit_program_script: Script = wit_program.into();
9210         for output in tx.output.iter_mut() {
9211                 // Make the confirmed funding transaction have a bogus script_pubkey
9212                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9213         }
9214
9215         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9216         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()));
9217         check_added_monitors!(nodes[1], 1);
9218         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9219
9220         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()));
9221         check_added_monitors!(nodes[0], 1);
9222         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9223
9224         let events_1 = nodes[0].node.get_and_clear_pending_events();
9225         assert_eq!(events_1.len(), 0);
9226
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         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9230
9231         let expected_err = "funding tx had wrong script/value or output index";
9232         confirm_transaction_at(&nodes[1], &tx, 1);
9233         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9234                 [nodes[0].node.get_our_node_id()], 100000);
9235         check_added_monitors!(nodes[1], 1);
9236         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9237         assert_eq!(events_2.len(), 1);
9238         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9239                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9240                 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9241                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9242                 } else { panic!(); }
9243         } else { panic!(); }
9244         assert_eq!(nodes[1].node.list_channels().len(), 0);
9245
9246         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9247         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9248         // as its not 32 bytes long.
9249         let mut spend_tx = Transaction {
9250                 version: 2i32, lock_time: PackedLockTime::ZERO,
9251                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9252                         previous_output: BitcoinOutPoint {
9253                                 txid: tx.txid(),
9254                                 vout: idx as u32,
9255                         },
9256                         script_sig: Script::new(),
9257                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9258                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9259                 }).collect(),
9260                 output: vec![TxOut {
9261                         value: 1000,
9262                         script_pubkey: Script::new(),
9263                 }]
9264         };
9265         check_spends!(spend_tx, tx);
9266         mine_transaction(&nodes[1], &spend_tx);
9267 }
9268
9269 #[test]
9270 fn test_coinbase_funding_tx() {
9271         // Miners are able to fund channels directly from coinbase transactions, however
9272         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9273         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9274         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9275         //
9276         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9277         // immediately operational after opening.
9278         let chanmon_cfgs = create_chanmon_cfgs(2);
9279         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9280         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9281         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9282
9283         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9284         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9285
9286         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9287         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9288
9289         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9290
9291         // Create the coinbase funding transaction.
9292         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9293
9294         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9295         check_added_monitors!(nodes[0], 0);
9296         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9297
9298         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9299         check_added_monitors!(nodes[1], 1);
9300         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9301
9302         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9303
9304         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9305         check_added_monitors!(nodes[0], 1);
9306
9307         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9308         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9309
9310         // Starting at height 0, we "confirm" the coinbase at height 1.
9311         confirm_transaction_at(&nodes[0], &tx, 1);
9312         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9313         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9314         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9315         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9316         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9317         connect_blocks(&nodes[0], 1);
9318         // There should now be a `channel_ready` which can be handled.
9319         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()));
9320
9321         confirm_transaction_at(&nodes[1], &tx, 1);
9322         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9323         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9324         connect_blocks(&nodes[1], 1);
9325         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9326         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9327 }
9328
9329 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9330         // In the first version of the chain::Confirm interface, after a refactor was made to not
9331         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9332         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9333         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9334         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9335         // spending transaction until height N+1 (or greater). This was due to the way
9336         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9337         // spending transaction at the height the input transaction was confirmed at, not whether we
9338         // should broadcast a spending transaction at the current height.
9339         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9340         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9341         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9342         // until we learned about an additional block.
9343         //
9344         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9345         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9346         let chanmon_cfgs = create_chanmon_cfgs(3);
9347         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9348         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9349         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9350         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9351
9352         create_announced_chan_between_nodes(&nodes, 0, 1);
9353         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9354         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9355         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9356         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9357
9358         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9359         check_closed_broadcast!(nodes[1], true);
9360         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9361         check_added_monitors!(nodes[1], 1);
9362         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9363         assert_eq!(node_txn.len(), 1);
9364
9365         let conf_height = nodes[1].best_block_info().1;
9366         if !test_height_before_timelock {
9367                 connect_blocks(&nodes[1], 24 * 6);
9368         }
9369         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9370                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9371         if test_height_before_timelock {
9372                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9373                 // generate any events or broadcast any transactions
9374                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9375                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9376         } else {
9377                 // We should broadcast an HTLC transaction spending our funding transaction first
9378                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9379                 assert_eq!(spending_txn.len(), 2);
9380                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9381                 check_spends!(spending_txn[1], node_txn[0]);
9382                 // We should also generate a SpendableOutputs event with the to_self output (as its
9383                 // timelock is up).
9384                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9385                 assert_eq!(descriptor_spend_txn.len(), 1);
9386
9387                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9388                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9389                 // additional block built on top of the current chain.
9390                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9391                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9392                 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 }]);
9393                 check_added_monitors!(nodes[1], 1);
9394
9395                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9396                 assert!(updates.update_add_htlcs.is_empty());
9397                 assert!(updates.update_fulfill_htlcs.is_empty());
9398                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9399                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9400                 assert!(updates.update_fee.is_none());
9401                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9402                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9403                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9404         }
9405 }
9406
9407 #[test]
9408 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9409         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9410         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9411 }
9412
9413 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9414         let chanmon_cfgs = create_chanmon_cfgs(2);
9415         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9416         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9417         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9418
9419         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9420
9421         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9422                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9423         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9424
9425         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9426
9427         {
9428                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9429                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9430                 check_added_monitors!(nodes[0], 1);
9431                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9432                 assert_eq!(events.len(), 1);
9433                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9434                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9435                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9436         }
9437         expect_pending_htlcs_forwardable!(nodes[1]);
9438         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9439
9440         {
9441                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9442                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9443                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9444                 check_added_monitors!(nodes[0], 1);
9445                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9446                 assert_eq!(events.len(), 1);
9447                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9448                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9449                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9450                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9451                 // assume the second is a privacy attack (no longer particularly relevant
9452                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9453                 // the first HTLC delivered above.
9454         }
9455
9456         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9457         nodes[1].node.process_pending_htlc_forwards();
9458
9459         if test_for_second_fail_panic {
9460                 // Now we go fail back the first HTLC from the user end.
9461                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9462
9463                 let expected_destinations = vec![
9464                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9465                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9466                 ];
9467                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9468                 nodes[1].node.process_pending_htlc_forwards();
9469
9470                 check_added_monitors!(nodes[1], 1);
9471                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9472                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9473
9474                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9475                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9476                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9477
9478                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9479                 assert_eq!(failure_events.len(), 4);
9480                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9481                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9482                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9483                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9484         } else {
9485                 // Let the second HTLC fail and claim the first
9486                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9487                 nodes[1].node.process_pending_htlc_forwards();
9488
9489                 check_added_monitors!(nodes[1], 1);
9490                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9491                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9492                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9493
9494                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9495
9496                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9497         }
9498 }
9499
9500 #[test]
9501 fn test_dup_htlc_second_fail_panic() {
9502         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9503         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9504         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9505         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9506         do_test_dup_htlc_second_rejected(true);
9507 }
9508
9509 #[test]
9510 fn test_dup_htlc_second_rejected() {
9511         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9512         // simply reject the second HTLC but are still able to claim the first HTLC.
9513         do_test_dup_htlc_second_rejected(false);
9514 }
9515
9516 #[test]
9517 fn test_inconsistent_mpp_params() {
9518         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9519         // such HTLC and allow the second to stay.
9520         let chanmon_cfgs = create_chanmon_cfgs(4);
9521         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9522         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9523         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9524
9525         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9526         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9527         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9528         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9529
9530         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9531                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9532         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9533         assert_eq!(route.paths.len(), 2);
9534         route.paths.sort_by(|path_a, _| {
9535                 // Sort the path so that the path through nodes[1] comes first
9536                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9537                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9538         });
9539
9540         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9541
9542         let cur_height = nodes[0].best_block_info().1;
9543         let payment_id = PaymentId([42; 32]);
9544
9545         let session_privs = {
9546                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9547                 // ultimately have, just not right away.
9548                 let mut dup_route = route.clone();
9549                 dup_route.paths.push(route.paths[1].clone());
9550                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9551                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9552         };
9553         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9554                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9555                 &None, session_privs[0]).unwrap();
9556         check_added_monitors!(nodes[0], 1);
9557
9558         {
9559                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9560                 assert_eq!(events.len(), 1);
9561                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9562         }
9563         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9564
9565         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9566                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9567         check_added_monitors!(nodes[0], 1);
9568
9569         {
9570                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9571                 assert_eq!(events.len(), 1);
9572                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9573
9574                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9575                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9576
9577                 expect_pending_htlcs_forwardable!(nodes[2]);
9578                 check_added_monitors!(nodes[2], 1);
9579
9580                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9581                 assert_eq!(events.len(), 1);
9582                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9583
9584                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9585                 check_added_monitors!(nodes[3], 0);
9586                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9587
9588                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9589                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9590                 // post-payment_secrets) and fail back the new HTLC.
9591         }
9592         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9593         nodes[3].node.process_pending_htlc_forwards();
9594         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9595         nodes[3].node.process_pending_htlc_forwards();
9596
9597         check_added_monitors!(nodes[3], 1);
9598
9599         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9600         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9601         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9602
9603         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 }]);
9604         check_added_monitors!(nodes[2], 1);
9605
9606         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9607         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9608         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9609
9610         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9611
9612         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9613                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9614                 &None, session_privs[2]).unwrap();
9615         check_added_monitors!(nodes[0], 1);
9616
9617         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9618         assert_eq!(events.len(), 1);
9619         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9620
9621         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9622         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9623 }
9624
9625 #[test]
9626 fn test_double_partial_claim() {
9627         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9628         // time out, the sender resends only some of the MPP parts, then the user processes the
9629         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9630         // amount.
9631         let chanmon_cfgs = create_chanmon_cfgs(4);
9632         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9633         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9634         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9635
9636         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9637         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9638         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9639         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9640
9641         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9642         assert_eq!(route.paths.len(), 2);
9643         route.paths.sort_by(|path_a, _| {
9644                 // Sort the path so that the path through nodes[1] comes first
9645                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9646                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9647         });
9648
9649         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9650         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9651         // amount of time to respond to.
9652
9653         // Connect some blocks to time out the payment
9654         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9655         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9656
9657         let failed_destinations = vec![
9658                 HTLCDestination::FailedPayment { payment_hash },
9659                 HTLCDestination::FailedPayment { payment_hash },
9660         ];
9661         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9662
9663         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9664
9665         // nodes[1] now retries one of the two paths...
9666         nodes[0].node.send_payment_with_route(&route, payment_hash,
9667                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9668         check_added_monitors!(nodes[0], 2);
9669
9670         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9671         assert_eq!(events.len(), 2);
9672         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9673         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9674
9675         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9676         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9677         nodes[3].node.claim_funds(payment_preimage);
9678         check_added_monitors!(nodes[3], 0);
9679         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9680 }
9681
9682 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9683 #[derive(Clone, Copy, PartialEq)]
9684 enum ExposureEvent {
9685         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9686         AtHTLCForward,
9687         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9688         AtHTLCReception,
9689         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9690         AtUpdateFeeOutbound,
9691 }
9692
9693 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9694         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9695         // policy.
9696         //
9697         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9698         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9699         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9700         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9701         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9702         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9703         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9704         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9705
9706         let chanmon_cfgs = create_chanmon_cfgs(2);
9707         let mut config = test_default_channel_config();
9708         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9709                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9710                 // to get roughly the same initial value as the default setting when this test was
9711                 // originally written.
9712                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9713         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9716         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9717
9718         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9719         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9720         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9721         open_channel.max_accepted_htlcs = 60;
9722         if on_holder_tx {
9723                 open_channel.dust_limit_satoshis = 546;
9724         }
9725         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9726         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9727         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9728
9729         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9730
9731         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9732
9733         if on_holder_tx {
9734                 let mut node_0_per_peer_lock;
9735                 let mut node_0_peer_state_lock;
9736                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9737                         ChannelPhase::UnfundedOutboundV1(chan) => {
9738                                 chan.context.holder_dust_limit_satoshis = 546;
9739                         },
9740                         _ => panic!("Unexpected ChannelPhase variant"),
9741                 }
9742         }
9743
9744         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9745         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()));
9746         check_added_monitors!(nodes[1], 1);
9747         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9748
9749         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()));
9750         check_added_monitors!(nodes[0], 1);
9751         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9752
9753         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9754         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9755         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9756
9757         // Fetch a route in advance as we will be unable to once we're unable to send.
9758         let (mut route, payment_hash, _, payment_secret) =
9759                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9760
9761         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9762                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9763                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9764                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9765                 (chan.context().get_dust_buffer_feerate(None) as u64,
9766                 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9767         };
9768         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;
9769         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9770
9771         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;
9772         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9773
9774         let dust_htlc_on_counterparty_tx: u64 = 4;
9775         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9776
9777         if on_holder_tx {
9778                 if dust_outbound_balance {
9779                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9780                         // Outbound dust balance: 4372 sats
9781                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9782                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9783                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9784                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9785                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9786                         }
9787                 } else {
9788                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9789                         // Inbound dust balance: 4372 sats
9790                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9791                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9792                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9793                         }
9794                 }
9795         } else {
9796                 if dust_outbound_balance {
9797                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9798                         // Outbound dust balance: 5000 sats
9799                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9800                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9801                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9802                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9803                         }
9804                 } else {
9805                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9806                         // Inbound dust balance: 5000 sats
9807                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9808                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9809                         }
9810                 }
9811         }
9812
9813         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9814                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9815                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9816                 // With default dust exposure: 5000 sats
9817                 if on_holder_tx {
9818                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9819                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9820                                 ), true, APIError::ChannelUnavailable { .. }, {});
9821                 } else {
9822                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9823                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9824                                 ), true, APIError::ChannelUnavailable { .. }, {});
9825                 }
9826         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9827                 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 });
9828                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9829                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9830                 check_added_monitors!(nodes[1], 1);
9831                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9832                 assert_eq!(events.len(), 1);
9833                 let payment_event = SendEvent::from_event(events.remove(0));
9834                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9835                 // With default dust exposure: 5000 sats
9836                 if on_holder_tx {
9837                         // Outbound dust balance: 6399 sats
9838                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9839                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9840                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), 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);
9841                 } else {
9842                         // Outbound dust balance: 5200 sats
9843                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9844                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9845                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9846                                         max_dust_htlc_exposure_msat), 1);
9847                 }
9848         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9849                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9850                 // For the multiplier dust exposure limit, since it scales with feerate,
9851                 // we need to add a lot of HTLCs that will become dust at the new feerate
9852                 // to cross the threshold.
9853                 for _ in 0..20 {
9854                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9855                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9856                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9857                 }
9858                 {
9859                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9860                         *feerate_lock = *feerate_lock * 10;
9861                 }
9862                 nodes[0].node.timer_tick_occurred();
9863                 check_added_monitors!(nodes[0], 1);
9864                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9865         }
9866
9867         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9868         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9869         added_monitors.clear();
9870 }
9871
9872 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9873         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9874         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9875         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9876         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9877         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9878         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9879         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9880         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9881         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9882         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9883         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9884         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9885 }
9886
9887 #[test]
9888 fn test_max_dust_htlc_exposure() {
9889         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9890         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9891 }
9892
9893 #[test]
9894 fn test_non_final_funding_tx() {
9895         let chanmon_cfgs = create_chanmon_cfgs(2);
9896         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9897         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9898         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9899
9900         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9901         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9902         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9903         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9904         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9905
9906         let best_height = nodes[0].node.best_block.read().unwrap().height();
9907
9908         let chan_id = *nodes[0].network_chan_count.borrow();
9909         let events = nodes[0].node.get_and_clear_pending_events();
9910         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9911         assert_eq!(events.len(), 1);
9912         let mut tx = match events[0] {
9913                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9914                         // Timelock the transaction _beyond_ the best client height + 1.
9915                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9916                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9917                         }]}
9918                 },
9919                 _ => panic!("Unexpected event"),
9920         };
9921         // Transaction should fail as it's evaluated as non-final for propagation.
9922         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9923                 Err(APIError::APIMisuseError { err }) => {
9924                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9925                 },
9926                 _ => panic!()
9927         }
9928         let events = nodes[0].node.get_and_clear_pending_events();
9929         assert_eq!(events.len(), 1);
9930         match events[0] {
9931                 Event::ChannelClosed { channel_id, .. } => {
9932                         assert_eq!(channel_id, temp_channel_id);
9933                 },
9934                 _ => panic!("Unexpected event"),
9935         }
9936 }
9937
9938 #[test]
9939 fn test_non_final_funding_tx_within_headroom() {
9940         let chanmon_cfgs = create_chanmon_cfgs(2);
9941         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9942         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9943         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9944
9945         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9946         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9947         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9948         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9949         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9950
9951         let best_height = nodes[0].node.best_block.read().unwrap().height();
9952
9953         let chan_id = *nodes[0].network_chan_count.borrow();
9954         let events = nodes[0].node.get_and_clear_pending_events();
9955         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9956         assert_eq!(events.len(), 1);
9957         let mut tx = match events[0] {
9958                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9959                         // Timelock the transaction within a +1 headroom from the best block.
9960                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 1), input: vec![input], output: vec![TxOut {
9961                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9962                         }]}
9963                 },
9964                 _ => panic!("Unexpected event"),
9965         };
9966
9967         // Transaction should be accepted if it's in a +1 headroom from best block.
9968         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9969         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9970 }
9971
9972 #[test]
9973 fn accept_busted_but_better_fee() {
9974         // If a peer sends us a fee update that is too low, but higher than our previous channel
9975         // feerate, we should accept it. In the future we may want to consider closing the channel
9976         // later, but for now we only accept the update.
9977         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9978         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9979         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9980         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9981
9982         create_chan_between_nodes(&nodes[0], &nodes[1]);
9983
9984         // Set nodes[1] to expect 5,000 sat/kW.
9985         {
9986                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9987                 *feerate_lock = 5000;
9988         }
9989
9990         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9991         {
9992                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9993                 *feerate_lock = 1000;
9994         }
9995         nodes[0].node.timer_tick_occurred();
9996         check_added_monitors!(nodes[0], 1);
9997
9998         let events = nodes[0].node.get_and_clear_pending_msg_events();
9999         assert_eq!(events.len(), 1);
10000         match events[0] {
10001                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10002                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10003                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10004                 },
10005                 _ => panic!("Unexpected event"),
10006         };
10007
10008         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10009         // it.
10010         {
10011                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10012                 *feerate_lock = 2000;
10013         }
10014         nodes[0].node.timer_tick_occurred();
10015         check_added_monitors!(nodes[0], 1);
10016
10017         let events = nodes[0].node.get_and_clear_pending_msg_events();
10018         assert_eq!(events.len(), 1);
10019         match events[0] {
10020                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10021                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10022                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10023                 },
10024                 _ => panic!("Unexpected event"),
10025         };
10026
10027         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10028         // channel.
10029         {
10030                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10031                 *feerate_lock = 1000;
10032         }
10033         nodes[0].node.timer_tick_occurred();
10034         check_added_monitors!(nodes[0], 1);
10035
10036         let events = nodes[0].node.get_and_clear_pending_msg_events();
10037         assert_eq!(events.len(), 1);
10038         match events[0] {
10039                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10040                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10041                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10042                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10043                                 [nodes[0].node.get_our_node_id()], 100000);
10044                         check_closed_broadcast!(nodes[1], true);
10045                         check_added_monitors!(nodes[1], 1);
10046                 },
10047                 _ => panic!("Unexpected event"),
10048         };
10049 }
10050
10051 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10052         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10053         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10054         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10055         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10056         let min_final_cltv_expiry_delta = 120;
10057         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10058                 min_final_cltv_expiry_delta - 2 };
10059         let recv_value = 100_000;
10060
10061         create_chan_between_nodes(&nodes[0], &nodes[1]);
10062
10063         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10064         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10065                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10066                         Some(recv_value), Some(min_final_cltv_expiry_delta));
10067                 (payment_hash, payment_preimage, payment_secret)
10068         } else {
10069                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10070                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10071         };
10072         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10073         nodes[0].node.send_payment_with_route(&route, payment_hash,
10074                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10075         check_added_monitors!(nodes[0], 1);
10076         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10077         assert_eq!(events.len(), 1);
10078         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10079         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10080         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10081         expect_pending_htlcs_forwardable!(nodes[1]);
10082
10083         if valid_delta {
10084                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10085                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10086
10087                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10088         } else {
10089                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10090
10091                 check_added_monitors!(nodes[1], 1);
10092
10093                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10094                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10095                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10096
10097                 expect_payment_failed!(nodes[0], payment_hash, true);
10098         }
10099 }
10100
10101 #[test]
10102 fn test_payment_with_custom_min_cltv_expiry_delta() {
10103         do_payment_with_custom_min_final_cltv_expiry(false, false);
10104         do_payment_with_custom_min_final_cltv_expiry(false, true);
10105         do_payment_with_custom_min_final_cltv_expiry(true, false);
10106         do_payment_with_custom_min_final_cltv_expiry(true, true);
10107 }
10108
10109 #[test]
10110 fn test_disconnects_peer_awaiting_response_ticks() {
10111         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10112         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10113         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10116         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10117
10118         // Asserts a disconnect event is queued to the user.
10119         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10120                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10121                         if let MessageSendEvent::HandleError { action, .. } = event {
10122                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10123                                         Some(())
10124                                 } else {
10125                                         None
10126                                 }
10127                         } else {
10128                                 None
10129                         }
10130                 );
10131                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10132         };
10133
10134         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10135         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10136         let check_disconnect = |node: &Node| {
10137                 // No disconnect without any timer ticks.
10138                 check_disconnect_event(node, false);
10139
10140                 // No disconnect with 1 timer tick less than required.
10141                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10142                         node.node.timer_tick_occurred();
10143                         check_disconnect_event(node, false);
10144                 }
10145
10146                 // Disconnect after reaching the required ticks.
10147                 node.node.timer_tick_occurred();
10148                 check_disconnect_event(node, true);
10149
10150                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10151                 node.node.timer_tick_occurred();
10152                 check_disconnect_event(node, true);
10153         };
10154
10155         create_chan_between_nodes(&nodes[0], &nodes[1]);
10156
10157         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10158         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10159         nodes[0].node.timer_tick_occurred();
10160         check_added_monitors!(&nodes[0], 1);
10161         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10162         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10163         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10164         check_added_monitors!(&nodes[1], 1);
10165
10166         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10167         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10168         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10169         check_added_monitors!(&nodes[0], 1);
10170         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10171         check_added_monitors(&nodes[0], 1);
10172
10173         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10174         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10175         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10176         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10177         check_disconnect(&nodes[1]);
10178
10179         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10180         //
10181         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10182         // final `RevokeAndACK` to Bob to complete it.
10183         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10184         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10185         let bob_init = msgs::Init {
10186                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10187         };
10188         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10189         let alice_init = msgs::Init {
10190                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10191         };
10192         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10193
10194         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10195         // received Bob's yet, so she should disconnect him after reaching
10196         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10197         let alice_channel_reestablish = get_event_msg!(
10198                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10199         );
10200         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10201         check_disconnect(&nodes[0]);
10202
10203         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10204         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10205                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10206                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10207                         Some(msg.clone())
10208                 } else {
10209                         None
10210                 }
10211         ).unwrap();
10212         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10213
10214         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10215         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10216                 nodes[0].node.timer_tick_occurred();
10217                 check_disconnect_event(&nodes[0], false);
10218         }
10219
10220         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10221         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10222         check_disconnect(&nodes[1]);
10223
10224         // Finally, have Bob process the last message.
10225         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10226         check_added_monitors(&nodes[1], 1);
10227
10228         // At this point, neither node should attempt to disconnect each other, since they aren't
10229         // waiting on any messages.
10230         for node in &nodes {
10231                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10232                         node.node.timer_tick_occurred();
10233                         check_disconnect_event(node, false);
10234                 }
10235         }
10236 }
10237
10238 #[test]
10239 fn test_remove_expired_outbound_unfunded_channels() {
10240         let chanmon_cfgs = create_chanmon_cfgs(2);
10241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10243         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10244
10245         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10246         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10247         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10248         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10249         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10250
10251         let events = nodes[0].node.get_and_clear_pending_events();
10252         assert_eq!(events.len(), 1);
10253         match events[0] {
10254                 Event::FundingGenerationReady { .. } => (),
10255                 _ => panic!("Unexpected event"),
10256         };
10257
10258         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10259         let check_outbound_channel_existence = |should_exist: bool| {
10260                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10261                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10262                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10263         };
10264
10265         // Channel should exist without any timer ticks.
10266         check_outbound_channel_existence(true);
10267
10268         // Channel should exist with 1 timer tick less than required.
10269         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10270                 nodes[0].node.timer_tick_occurred();
10271                 check_outbound_channel_existence(true)
10272         }
10273
10274         // Remove channel after reaching the required ticks.
10275         nodes[0].node.timer_tick_occurred();
10276         check_outbound_channel_existence(false);
10277
10278         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10279         assert_eq!(msg_events.len(), 1);
10280         match msg_events[0] {
10281                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10282                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10283                 },
10284                 _ => panic!("Unexpected event"),
10285         }
10286         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10287 }
10288
10289 #[test]
10290 fn test_remove_expired_inbound_unfunded_channels() {
10291         let chanmon_cfgs = create_chanmon_cfgs(2);
10292         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10293         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10294         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10295
10296         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10297         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10298         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10299         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10300         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10301
10302         let events = nodes[0].node.get_and_clear_pending_events();
10303         assert_eq!(events.len(), 1);
10304         match events[0] {
10305                 Event::FundingGenerationReady { .. } => (),
10306                 _ => panic!("Unexpected event"),
10307         };
10308
10309         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10310         let check_inbound_channel_existence = |should_exist: bool| {
10311                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10312                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10313                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10314         };
10315
10316         // Channel should exist without any timer ticks.
10317         check_inbound_channel_existence(true);
10318
10319         // Channel should exist with 1 timer tick less than required.
10320         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10321                 nodes[1].node.timer_tick_occurred();
10322                 check_inbound_channel_existence(true)
10323         }
10324
10325         // Remove channel after reaching the required ticks.
10326         nodes[1].node.timer_tick_occurred();
10327         check_inbound_channel_existence(false);
10328
10329         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10330         assert_eq!(msg_events.len(), 1);
10331         match msg_events[0] {
10332                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10333                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10334                 },
10335                 _ => panic!("Unexpected event"),
10336         }
10337         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10338 }
10339
10340 fn do_test_multi_post_event_actions(do_reload: bool) {
10341         // Tests handling multiple post-Event actions at once.
10342         // There is specific code in ChannelManager to handle channels where multiple post-Event
10343         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10344         //
10345         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10346         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10347         // - one from an RAA and one from an inbound commitment_signed.
10348         let chanmon_cfgs = create_chanmon_cfgs(3);
10349         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10350         let (persister, chain_monitor);
10351         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10352         let nodes_0_deserialized;
10353         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10354
10355         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10356         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10357
10358         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10359         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10360
10361         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10362         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10363
10364         nodes[1].node.claim_funds(our_payment_preimage);
10365         check_added_monitors!(nodes[1], 1);
10366         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10367
10368         nodes[2].node.claim_funds(payment_preimage_2);
10369         check_added_monitors!(nodes[2], 1);
10370         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10371
10372         for dest in &[1, 2] {
10373                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10374                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10375                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10376                 check_added_monitors(&nodes[0], 0);
10377         }
10378
10379         let (route, payment_hash_3, _, payment_secret_3) =
10380                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10381         let payment_id = PaymentId(payment_hash_3.0);
10382         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10383                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10384         check_added_monitors(&nodes[1], 1);
10385
10386         let send_event = SendEvent::from_node(&nodes[1]);
10387         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10388         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10389         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10390
10391         if do_reload {
10392                 let nodes_0_serialized = nodes[0].node.encode();
10393                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10394                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10395                 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);
10396
10397                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10398                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10399
10400                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10401                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10402         }
10403
10404         let events = nodes[0].node.get_and_clear_pending_events();
10405         assert_eq!(events.len(), 4);
10406         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10407                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10408         } else { panic!(); }
10409         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10410                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10411         } else { panic!(); }
10412         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10413         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10414
10415         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10416         // completion, we'll respond to nodes[1] with an RAA + CS.
10417         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10418         check_added_monitors(&nodes[0], 3);
10419 }
10420
10421 #[test]
10422 fn test_multi_post_event_actions() {
10423         do_test_multi_post_event_actions(true);
10424         do_test_multi_post_event_actions(false);
10425 }
10426
10427 #[test]
10428 fn test_batch_channel_open() {
10429         let chanmon_cfgs = create_chanmon_cfgs(3);
10430         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10431         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10432         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10433
10434         // Initiate channel opening and create the batch channel funding transaction.
10435         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10436                 (&nodes[1], 100_000, 0, 42, None),
10437                 (&nodes[2], 200_000, 0, 43, None),
10438         ]);
10439
10440         // Go through the funding_created and funding_signed flow with node 1.
10441         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10442         check_added_monitors(&nodes[1], 1);
10443         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10444
10445         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10446         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10447         check_added_monitors(&nodes[0], 1);
10448
10449         // The transaction should not have been broadcast before all channels are ready.
10450         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10451
10452         // Go through the funding_created and funding_signed flow with node 2.
10453         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10454         check_added_monitors(&nodes[2], 1);
10455         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10456
10457         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10458         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10459         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10460         check_added_monitors(&nodes[0], 1);
10461
10462         // The transaction should not have been broadcast before persisting all monitors has been
10463         // completed.
10464         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10465         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10466
10467         // Complete the persistence of the monitor.
10468         nodes[0].chain_monitor.complete_sole_pending_chan_update(
10469                 &OutPoint { txid: tx.txid(), index: 1 }.to_channel_id()
10470         );
10471         let events = nodes[0].node.get_and_clear_pending_events();
10472
10473         // The transaction should only have been broadcast now.
10474         let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10475         assert_eq!(broadcasted_txs.len(), 1);
10476         assert_eq!(broadcasted_txs[0], tx);
10477
10478         assert_eq!(events.len(), 2);
10479         assert!(events.iter().any(|e| matches!(
10480                 *e,
10481                 crate::events::Event::ChannelPending {
10482                         ref counterparty_node_id,
10483                         ..
10484                 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10485         )));
10486         assert!(events.iter().any(|e| matches!(
10487                 *e,
10488                 crate::events::Event::ChannelPending {
10489                         ref counterparty_node_id,
10490                         ..
10491                 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10492         )));
10493 }
10494
10495 #[test]
10496 fn test_disconnect_in_funding_batch() {
10497         let chanmon_cfgs = create_chanmon_cfgs(3);
10498         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10499         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10500         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10501
10502         // Initiate channel opening and create the batch channel funding transaction.
10503         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10504                 (&nodes[1], 100_000, 0, 42, None),
10505                 (&nodes[2], 200_000, 0, 43, None),
10506         ]);
10507
10508         // Go through the funding_created and funding_signed flow with node 1.
10509         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10510         check_added_monitors(&nodes[1], 1);
10511         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10512
10513         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10514         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10515         check_added_monitors(&nodes[0], 1);
10516
10517         // The transaction should not have been broadcast before all channels are ready.
10518         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10519
10520         // The remaining peer in the batch disconnects.
10521         nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
10522
10523         // The channels in the batch will close immediately.
10524         let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10525         let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10526         check_closed_events(&nodes[0], &[
10527                 ExpectedCloseEvent {
10528                         channel_id: Some(channel_id_1),
10529                         discard_funding: true,
10530                         ..Default::default()
10531                 },
10532                 ExpectedCloseEvent {
10533                         channel_id: Some(channel_id_2),
10534                         discard_funding: true,
10535                         ..Default::default()
10536                 },
10537         ]);
10538
10539         // The monitor should become closed.
10540         check_added_monitors(&nodes[0], 1);
10541         {
10542                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10543                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10544                 assert_eq!(monitor_updates_1.len(), 1);
10545                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10546         }
10547
10548         // The funding transaction should not have been broadcast, and therefore, we don't need
10549         // to broadcast a force-close transaction for the closed monitor.
10550         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10551
10552         // Ensure the channels don't exist anymore.
10553         assert!(nodes[0].node.list_channels().is_empty());
10554 }
10555
10556 #[test]
10557 fn test_batch_funding_close_after_funding_signed() {
10558         let chanmon_cfgs = create_chanmon_cfgs(3);
10559         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10560         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10561         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10562
10563         // Initiate channel opening and create the batch channel funding transaction.
10564         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10565                 (&nodes[1], 100_000, 0, 42, None),
10566                 (&nodes[2], 200_000, 0, 43, None),
10567         ]);
10568
10569         // Go through the funding_created and funding_signed flow with node 1.
10570         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10571         check_added_monitors(&nodes[1], 1);
10572         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10573
10574         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10575         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10576         check_added_monitors(&nodes[0], 1);
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 all channels are ready.
10589         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10590
10591         // Force-close the channel for which we've completed the initial monitor.
10592         let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10593         let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10594         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10595         check_added_monitors(&nodes[0], 2);
10596         {
10597                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10598                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10599                 assert_eq!(monitor_updates_1.len(), 1);
10600                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10601                 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10602                 assert_eq!(monitor_updates_2.len(), 1);
10603                 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10604         }
10605         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10606         match msg_events[0] {
10607                 MessageSendEvent::HandleError { .. } => (),
10608                 _ => panic!("Unexpected message."),
10609         }
10610
10611         // We broadcast the commitment transaction as part of the force-close.
10612         {
10613                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10614                 assert_eq!(broadcasted_txs.len(), 1);
10615                 assert!(broadcasted_txs[0].txid() != tx.txid());
10616                 assert_eq!(broadcasted_txs[0].input.len(), 1);
10617                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10618         }
10619
10620         // All channels in the batch should close immediately.
10621         check_closed_events(&nodes[0], &[
10622                 ExpectedCloseEvent {
10623                         channel_id: Some(channel_id_1),
10624                         discard_funding: true,
10625                         ..Default::default()
10626                 },
10627                 ExpectedCloseEvent {
10628                         channel_id: Some(channel_id_2),
10629                         discard_funding: true,
10630                         ..Default::default()
10631                 },
10632         ]);
10633
10634         // Ensure the channels don't exist anymore.
10635         assert!(nodes[0].node.list_channels().is_empty());
10636 }
10637
10638 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10639         // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10640         // funding and commitment transaction confirm in the same block.
10641         let chanmon_cfgs = create_chanmon_cfgs(2);
10642         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10643         let mut min_depth_1_block_cfg = test_default_channel_config();
10644         min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10646         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10647
10648         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10649         let chan_id = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 }.to_channel_id();
10650
10651         assert_eq!(nodes[0].node.list_channels().len(), 1);
10652         assert_eq!(nodes[1].node.list_channels().len(), 1);
10653
10654         let (closing_node, other_node) = if confirm_remote_commitment {
10655                 (&nodes[1], &nodes[0])
10656         } else {
10657                 (&nodes[0], &nodes[1])
10658         };
10659
10660         closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10661         let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10662         assert_eq!(msg_events.len(), 1);
10663         match msg_events.pop().unwrap() {
10664                 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10665                 _ => panic!("Unexpected event"),
10666         }
10667         check_added_monitors(closing_node, 1);
10668         check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10669
10670         let commitment_tx = {
10671                 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10672                 assert_eq!(txn.len(), 1);
10673                 let commitment_tx = txn.pop().unwrap();
10674                 check_spends!(commitment_tx, funding_tx);
10675                 commitment_tx
10676         };
10677
10678         mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10679         mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10680
10681         check_closed_broadcast(other_node, 1, true);
10682         check_added_monitors(other_node, 1);
10683         check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10684
10685         assert!(nodes[0].node.list_channels().is_empty());
10686         assert!(nodes[1].node.list_channels().is_empty());
10687 }
10688
10689 #[test]
10690 fn test_funding_and_commitment_tx_confirm_same_block() {
10691         do_test_funding_and_commitment_tx_confirm_same_block(false);
10692         do_test_funding_and_commitment_tx_confirm_same_block(true);
10693 }