]> git.bitcoin.ninja Git - rust-lightning/blob - lightning/src/ln/functional_tests.rs
5b1420e3d6b55b073ff790046831ebd68ad5b56c
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, OutputSpender, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::types::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::locktime::absolute::LockTime;
42 use bitcoin::blockdata::script::{Builder, ScriptBuf};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{Sequence, Transaction, TxIn, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
51
52 use crate::io;
53 use crate::prelude::*;
54 use alloc::collections::BTreeSet;
55 use core::iter::repeat;
56 use bitcoin::hashes::Hash;
57 use crate::sync::{Arc, Mutex, RwLock};
58
59 use crate::ln::functional_test_utils::*;
60 use crate::ln::chan_utils::CommitmentTransaction;
61
62 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
63
64 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         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.common_fields.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.common_fields.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.common_fields.funding_satoshis + 1; msg });
111
112         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.common_fields.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.common_fields.dust_limit_satoshis = msg.common_fields.funding_satoshis + 1 ; msg });
115
116         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.common_fields.htlc_minimum_msat = (msg.common_fields.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
117
118         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.common_fields.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.common_fields.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.common_fields.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         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();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
177         {
178                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180                 let mut sender_node_per_peer_lock;
181                 let mut sender_node_peer_state_lock;
182
183                 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
184                 match channel_phase {
185                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
186                                 let chan_context = channel_phase.context_mut();
187                                 chan_context.holder_selected_channel_reserve_satoshis = 0;
188                                 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
189                         },
190                         _ => assert!(false),
191                 }
192         }
193
194         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
195         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
196         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
197
198         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
199         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
200         if send_from_initiator {
201                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
202                         // Note that for outbound channels we have to consider the commitment tx fee and the
203                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
204                         // well as an additional HTLC.
205                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
206         } else {
207                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
208         }
209 }
210
211 #[test]
212 fn test_counterparty_no_reserve() {
213         do_test_counterparty_no_reserve(true);
214         do_test_counterparty_no_reserve(false);
215 }
216
217 #[test]
218 fn test_async_inbound_update_fee() {
219         let chanmon_cfgs = create_chanmon_cfgs(2);
220         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
221         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
222         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
223         create_announced_chan_between_nodes(&nodes, 0, 1);
224
225         // balancing
226         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
227
228         // A                                        B
229         // update_fee                            ->
230         // send (1) commitment_signed            -.
231         //                                       <- update_add_htlc/commitment_signed
232         // send (2) RAA (awaiting remote revoke) -.
233         // (1) commitment_signed is delivered    ->
234         //                                       .- send (3) RAA (awaiting remote revoke)
235         // (2) RAA is delivered                  ->
236         //                                       .- send (4) commitment_signed
237         //                                       <- (3) RAA is delivered
238         // send (5) commitment_signed            -.
239         //                                       <- (4) commitment_signed is delivered
240         // send (6) RAA                          -.
241         // (5) commitment_signed is delivered    ->
242         //                                       <- RAA
243         // (6) RAA is delivered                  ->
244
245         // First nodes[0] generates an update_fee
246         {
247                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
248                 *feerate_lock += 20;
249         }
250         nodes[0].node.timer_tick_occurred();
251         check_added_monitors!(nodes[0], 1);
252
253         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
254         assert_eq!(events_0.len(), 1);
255         let (update_msg, commitment_signed) = match events_0[0] { // (1)
256                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
257                         (update_fee.as_ref(), commitment_signed)
258                 },
259                 _ => panic!("Unexpected event"),
260         };
261
262         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
263
264         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
265         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
266         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
267                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
268         check_added_monitors!(nodes[1], 1);
269
270         let payment_event = {
271                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
272                 assert_eq!(events_1.len(), 1);
273                 SendEvent::from_event(events_1.remove(0))
274         };
275         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
276         assert_eq!(payment_event.msgs.len(), 1);
277
278         // ...now when the messages get delivered everyone should be happy
279         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
280         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
281         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
282         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
283         check_added_monitors!(nodes[0], 1);
284
285         // deliver(1), generate (3):
286         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
287         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
288         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
289         check_added_monitors!(nodes[1], 1);
290
291         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
292         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
293         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
294         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
295         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
296         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fee.is_none()); // (4)
298         check_added_monitors!(nodes[1], 1);
299
300         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
301         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
302         assert!(as_update.update_add_htlcs.is_empty()); // (5)
303         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
304         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
305         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fee.is_none()); // (5)
307         check_added_monitors!(nodes[0], 1);
308
309         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
310         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
311         // only (6) so get_event_msg's assert(len == 1) passes
312         check_added_monitors!(nodes[0], 1);
313
314         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
315         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
316         check_added_monitors!(nodes[1], 1);
317
318         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
319         check_added_monitors!(nodes[0], 1);
320
321         let events_2 = nodes[0].node.get_and_clear_pending_events();
322         assert_eq!(events_2.len(), 1);
323         match events_2[0] {
324                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
325                 _ => panic!("Unexpected event"),
326         }
327
328         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
329         check_added_monitors!(nodes[1], 1);
330 }
331
332 #[test]
333 fn test_update_fee_unordered_raa() {
334         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
335         // crash in an earlier version of the update_fee patch)
336         let chanmon_cfgs = create_chanmon_cfgs(2);
337         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
338         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
339         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
340         create_announced_chan_between_nodes(&nodes, 0, 1);
341
342         // balancing
343         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
344
345         // First nodes[0] generates an update_fee
346         {
347                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
348                 *feerate_lock += 20;
349         }
350         nodes[0].node.timer_tick_occurred();
351         check_added_monitors!(nodes[0], 1);
352
353         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
354         assert_eq!(events_0.len(), 1);
355         let update_msg = match events_0[0] { // (1)
356                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
357                         update_fee.as_ref()
358                 },
359                 _ => panic!("Unexpected event"),
360         };
361
362         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
363
364         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
365         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
366         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
367                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
368         check_added_monitors!(nodes[1], 1);
369
370         let payment_event = {
371                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
372                 assert_eq!(events_1.len(), 1);
373                 SendEvent::from_event(events_1.remove(0))
374         };
375         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
376         assert_eq!(payment_event.msgs.len(), 1);
377
378         // ...now when the messages get delivered everyone should be happy
379         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
380         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
381         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
382         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
383         check_added_monitors!(nodes[0], 1);
384
385         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
386         check_added_monitors!(nodes[1], 1);
387
388         // We can't continue, sadly, because our (1) now has a bogus signature
389 }
390
391 #[test]
392 fn test_multi_flight_update_fee() {
393         let chanmon_cfgs = create_chanmon_cfgs(2);
394         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
395         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
396         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
397         create_announced_chan_between_nodes(&nodes, 0, 1);
398
399         // A                                        B
400         // update_fee/commitment_signed          ->
401         //                                       .- send (1) RAA and (2) commitment_signed
402         // update_fee (never committed)          ->
403         // (3) update_fee                        ->
404         // We have to manually generate the above update_fee, it is allowed by the protocol but we
405         // don't track which updates correspond to which revoke_and_ack responses so we're in
406         // AwaitingRAA mode and will not generate the update_fee yet.
407         //                                       <- (1) RAA delivered
408         // (3) is generated and send (4) CS      -.
409         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
410         // know the per_commitment_point to use for it.
411         //                                       <- (2) commitment_signed delivered
412         // revoke_and_ack                        ->
413         //                                          B should send no response here
414         // (4) commitment_signed delivered       ->
415         //                                       <- RAA/commitment_signed delivered
416         // revoke_and_ack                        ->
417
418         // First nodes[0] generates an update_fee
419         let initial_feerate;
420         {
421                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
422                 initial_feerate = *feerate_lock;
423                 *feerate_lock = initial_feerate + 20;
424         }
425         nodes[0].node.timer_tick_occurred();
426         check_added_monitors!(nodes[0], 1);
427
428         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
429         assert_eq!(events_0.len(), 1);
430         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
431                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
432                         (update_fee.as_ref().unwrap(), commitment_signed)
433                 },
434                 _ => panic!("Unexpected event"),
435         };
436
437         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
438         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
439         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
440         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
441         check_added_monitors!(nodes[1], 1);
442
443         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
444         // transaction:
445         {
446                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
447                 *feerate_lock = initial_feerate + 40;
448         }
449         nodes[0].node.timer_tick_occurred();
450         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
451         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
452
453         // Create the (3) update_fee message that nodes[0] will generate before it does...
454         let mut update_msg_2 = msgs::UpdateFee {
455                 channel_id: update_msg_1.channel_id.clone(),
456                 feerate_per_kw: (initial_feerate + 30) as u32,
457         };
458
459         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
460
461         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
462         // Deliver (3)
463         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
464
465         // Deliver (1), generating (3) and (4)
466         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
467         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
468         check_added_monitors!(nodes[0], 1);
469         assert!(as_second_update.update_add_htlcs.is_empty());
470         assert!(as_second_update.update_fulfill_htlcs.is_empty());
471         assert!(as_second_update.update_fail_htlcs.is_empty());
472         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
473         // Check that the update_fee newly generated matches what we delivered:
474         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
475         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
476
477         // Deliver (2) commitment_signed
478         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
479         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
480         check_added_monitors!(nodes[0], 1);
481         // No commitment_signed so get_event_msg's assert(len == 1) passes
482
483         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
484         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
485         check_added_monitors!(nodes[1], 1);
486
487         // Delever (4)
488         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
489         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
490         check_added_monitors!(nodes[1], 1);
491
492         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
493         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
494         check_added_monitors!(nodes[0], 1);
495
496         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
497         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
498         // No commitment_signed so get_event_msg's assert(len == 1) passes
499         check_added_monitors!(nodes[0], 1);
500
501         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
502         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
503         check_added_monitors!(nodes[1], 1);
504 }
505
506 fn do_test_sanity_on_in_flight_opens(steps: u8) {
507         // Previously, we had issues deserializing channels when we hadn't connected the first block
508         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
509         // serialization round-trips and simply do steps towards opening a channel and then drop the
510         // Node objects.
511
512         let chanmon_cfgs = create_chanmon_cfgs(2);
513         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
514         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
515         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
516
517         if steps & 0b1000_0000 != 0{
518                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
519                 connect_block(&nodes[0], &block);
520                 connect_block(&nodes[1], &block);
521         }
522
523         if steps & 0x0f == 0 { return; }
524         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
525         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
526
527         if steps & 0x0f == 1 { return; }
528         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
529         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
530
531         if steps & 0x0f == 2 { return; }
532         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
533
534         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
535
536         if steps & 0x0f == 3 { return; }
537         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
538         check_added_monitors!(nodes[0], 0);
539         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
540
541         if steps & 0x0f == 4 { return; }
542         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
543         {
544                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
545                 assert_eq!(added_monitors.len(), 1);
546                 assert_eq!(added_monitors[0].0, funding_output);
547                 added_monitors.clear();
548         }
549         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
550
551         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
552
553         if steps & 0x0f == 5 { return; }
554         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
555         {
556                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
557                 assert_eq!(added_monitors.len(), 1);
558                 assert_eq!(added_monitors[0].0, funding_output);
559                 added_monitors.clear();
560         }
561
562         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
563         let events_4 = nodes[0].node.get_and_clear_pending_events();
564         assert_eq!(events_4.len(), 0);
565
566         if steps & 0x0f == 6 { return; }
567         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
568
569         if steps & 0x0f == 7 { return; }
570         confirm_transaction_at(&nodes[0], &tx, 2);
571         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
572         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
573         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
574 }
575
576 #[test]
577 fn test_sanity_on_in_flight_opens() {
578         do_test_sanity_on_in_flight_opens(0);
579         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
580         do_test_sanity_on_in_flight_opens(1);
581         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
582         do_test_sanity_on_in_flight_opens(2);
583         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
584         do_test_sanity_on_in_flight_opens(3);
585         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
586         do_test_sanity_on_in_flight_opens(4);
587         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
588         do_test_sanity_on_in_flight_opens(5);
589         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
590         do_test_sanity_on_in_flight_opens(6);
591         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
592         do_test_sanity_on_in_flight_opens(7);
593         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
594         do_test_sanity_on_in_flight_opens(8);
595         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
596 }
597
598 #[test]
599 fn test_update_fee_vanilla() {
600         let chanmon_cfgs = create_chanmon_cfgs(2);
601         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
602         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
603         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
604         create_announced_chan_between_nodes(&nodes, 0, 1);
605
606         {
607                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
608                 *feerate_lock += 25;
609         }
610         nodes[0].node.timer_tick_occurred();
611         check_added_monitors!(nodes[0], 1);
612
613         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
614         assert_eq!(events_0.len(), 1);
615         let (update_msg, commitment_signed) = match events_0[0] {
616                         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 } } => {
617                         (update_fee.as_ref(), commitment_signed)
618                 },
619                 _ => panic!("Unexpected event"),
620         };
621         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
622
623         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
624         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
625         check_added_monitors!(nodes[1], 1);
626
627         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
628         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
629         check_added_monitors!(nodes[0], 1);
630
631         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
632         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
633         // No commitment_signed so get_event_msg's assert(len == 1) passes
634         check_added_monitors!(nodes[0], 1);
635
636         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
637         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
638         check_added_monitors!(nodes[1], 1);
639 }
640
641 #[test]
642 fn test_update_fee_that_funder_cannot_afford() {
643         let chanmon_cfgs = create_chanmon_cfgs(2);
644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
646         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
647         let channel_value = 5000;
648         let push_sats = 700;
649         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
650         let channel_id = chan.2;
651         let secp_ctx = Secp256k1::new();
652         let default_config = UserConfig::default();
653         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
654
655         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
656
657         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
658         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
659         // calculate two different feerates here - the expected local limit as well as the expected
660         // remote limit.
661         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;
662         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
663         {
664                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
665                 *feerate_lock = feerate;
666         }
667         nodes[0].node.timer_tick_occurred();
668         check_added_monitors!(nodes[0], 1);
669         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
670
671         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
672
673         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
674
675         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
676         {
677                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
678
679                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
680                 assert_eq!(commitment_tx.output.len(), 2);
681                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
682                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
683                 actual_fee = channel_value - actual_fee;
684                 assert_eq!(total_fee, actual_fee);
685         }
686
687         {
688                 // Increment the feerate by a small constant, accounting for rounding errors
689                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
690                 *feerate_lock += 4;
691         }
692         nodes[0].node.timer_tick_occurred();
693         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
694         check_added_monitors!(nodes[0], 0);
695
696         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
697
698         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
699         // needed to sign the new commitment tx and (2) sign the new commitment tx.
700         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
701                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
702                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
703                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
704                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
705                 ).flatten().unwrap();
706                 let chan_signer = local_chan.get_signer();
707                 let pubkeys = chan_signer.as_ref().pubkeys();
708                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
709                  pubkeys.funding_pubkey)
710         };
711         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
712                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
713                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
714                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
715                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
716                 ).flatten().unwrap();
717                 let chan_signer = remote_chan.get_signer();
718                 let pubkeys = chan_signer.as_ref().pubkeys();
719                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
720                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
721                  pubkeys.funding_pubkey)
722         };
723
724         // Assemble the set of keys we can use for signatures for our commitment_signed message.
725         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
726                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
727
728         let res = {
729                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
730                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
731                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
732                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
733                 ).flatten().unwrap();
734                 let local_chan_signer = local_chan.get_signer();
735                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
736                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
737                         INITIAL_COMMITMENT_NUMBER - 1,
738                         push_sats,
739                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
740                         local_funding, remote_funding,
741                         commit_tx_keys.clone(),
742                         non_buffer_feerate + 4,
743                         &mut htlcs,
744                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
745                 );
746                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
747         };
748
749         let commit_signed_msg = msgs::CommitmentSigned {
750                 channel_id: chan.2,
751                 signature: res.0,
752                 htlc_signatures: res.1,
753                 #[cfg(taproot)]
754                 partial_signature_with_nonce: None,
755         };
756
757         let update_fee = msgs::UpdateFee {
758                 channel_id: chan.2,
759                 feerate_per_kw: non_buffer_feerate + 4,
760         };
761
762         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
763
764         //While producing the commitment_signed response after handling a received update_fee request the
765         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
766         //Should produce and error.
767         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
768         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee", 3);
769         check_added_monitors!(nodes[1], 1);
770         check_closed_broadcast!(nodes[1], true);
771         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
772                 [nodes[0].node.get_our_node_id()], channel_value);
773 }
774
775 #[test]
776 fn test_update_fee_with_fundee_update_add_htlc() {
777         let chanmon_cfgs = create_chanmon_cfgs(2);
778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
780         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
781         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
782
783         // balancing
784         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
785
786         {
787                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
788                 *feerate_lock += 20;
789         }
790         nodes[0].node.timer_tick_occurred();
791         check_added_monitors!(nodes[0], 1);
792
793         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
794         assert_eq!(events_0.len(), 1);
795         let (update_msg, commitment_signed) = match events_0[0] {
796                         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 } } => {
797                         (update_fee.as_ref(), commitment_signed)
798                 },
799                 _ => panic!("Unexpected event"),
800         };
801         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
802         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
803         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
804         check_added_monitors!(nodes[1], 1);
805
806         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
807
808         // nothing happens since node[1] is in AwaitingRemoteRevoke
809         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
810                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
811         {
812                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
813                 assert_eq!(added_monitors.len(), 0);
814                 added_monitors.clear();
815         }
816         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
817         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
818         // node[1] has nothing to do
819
820         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
821         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
822         check_added_monitors!(nodes[0], 1);
823
824         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
825         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
826         // No commitment_signed so get_event_msg's assert(len == 1) passes
827         check_added_monitors!(nodes[0], 1);
828         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
829         check_added_monitors!(nodes[1], 1);
830         // AwaitingRemoteRevoke ends here
831
832         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
833         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
834         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
835         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
836         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
837         assert_eq!(commitment_update.update_fee.is_none(), true);
838
839         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
840         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
841         check_added_monitors!(nodes[0], 1);
842         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
843
844         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
845         check_added_monitors!(nodes[1], 1);
846         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
847
848         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
849         check_added_monitors!(nodes[1], 1);
850         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
851         // No commitment_signed so get_event_msg's assert(len == 1) passes
852
853         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
854         check_added_monitors!(nodes[0], 1);
855         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
856
857         expect_pending_htlcs_forwardable!(nodes[0]);
858
859         let events = nodes[0].node.get_and_clear_pending_events();
860         assert_eq!(events.len(), 1);
861         match events[0] {
862                 Event::PaymentClaimable { .. } => { },
863                 _ => panic!("Unexpected event"),
864         };
865
866         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
867
868         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
869         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
870         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
871         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
872         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
873 }
874
875 #[test]
876 fn test_update_fee() {
877         let chanmon_cfgs = create_chanmon_cfgs(2);
878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
880         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
881         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
882         let channel_id = chan.2;
883
884         // A                                        B
885         // (1) update_fee/commitment_signed      ->
886         //                                       <- (2) revoke_and_ack
887         //                                       .- send (3) commitment_signed
888         // (4) update_fee/commitment_signed      ->
889         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
890         //                                       <- (3) commitment_signed delivered
891         // send (6) revoke_and_ack               -.
892         //                                       <- (5) deliver revoke_and_ack
893         // (6) deliver revoke_and_ack            ->
894         //                                       .- send (7) commitment_signed in response to (4)
895         //                                       <- (7) deliver commitment_signed
896         // revoke_and_ack                        ->
897
898         // Create and deliver (1)...
899         let feerate;
900         {
901                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
902                 feerate = *feerate_lock;
903                 *feerate_lock = feerate + 20;
904         }
905         nodes[0].node.timer_tick_occurred();
906         check_added_monitors!(nodes[0], 1);
907
908         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
909         assert_eq!(events_0.len(), 1);
910         let (update_msg, commitment_signed) = match events_0[0] {
911                         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 } } => {
912                         (update_fee.as_ref(), commitment_signed)
913                 },
914                 _ => panic!("Unexpected event"),
915         };
916         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
917
918         // Generate (2) and (3):
919         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
920         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
921         check_added_monitors!(nodes[1], 1);
922
923         // Deliver (2):
924         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
925         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
926         check_added_monitors!(nodes[0], 1);
927
928         // Create and deliver (4)...
929         {
930                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
931                 *feerate_lock = feerate + 30;
932         }
933         nodes[0].node.timer_tick_occurred();
934         check_added_monitors!(nodes[0], 1);
935         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
936         assert_eq!(events_0.len(), 1);
937         let (update_msg, commitment_signed) = match events_0[0] {
938                         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 } } => {
939                         (update_fee.as_ref(), commitment_signed)
940                 },
941                 _ => panic!("Unexpected event"),
942         };
943
944         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
945         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
946         check_added_monitors!(nodes[1], 1);
947         // ... creating (5)
948         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
949         // No commitment_signed so get_event_msg's assert(len == 1) passes
950
951         // Handle (3), creating (6):
952         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
953         check_added_monitors!(nodes[0], 1);
954         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
955         // No commitment_signed so get_event_msg's assert(len == 1) passes
956
957         // Deliver (5):
958         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
959         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
960         check_added_monitors!(nodes[0], 1);
961
962         // Deliver (6), creating (7):
963         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
964         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
965         assert!(commitment_update.update_add_htlcs.is_empty());
966         assert!(commitment_update.update_fulfill_htlcs.is_empty());
967         assert!(commitment_update.update_fail_htlcs.is_empty());
968         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
969         assert!(commitment_update.update_fee.is_none());
970         check_added_monitors!(nodes[1], 1);
971
972         // Deliver (7)
973         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
974         check_added_monitors!(nodes[0], 1);
975         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
976         // No commitment_signed so get_event_msg's assert(len == 1) passes
977
978         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
979         check_added_monitors!(nodes[1], 1);
980         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
981
982         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
983         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
984         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
985         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
986         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
987 }
988
989 #[test]
990 fn fake_network_test() {
991         // Simple test which builds a network of ChannelManagers, connects them to each other, and
992         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
993         let chanmon_cfgs = create_chanmon_cfgs(4);
994         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
995         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
996         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
997
998         // Create some initial channels
999         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1000         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1001         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1002
1003         // Rebalance the network a bit by relaying one payment through all the channels...
1004         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1005         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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
1009         // Send some more payments
1010         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1011         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1012         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1013
1014         // Test failure packets
1015         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1016         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1017
1018         // Add a new channel that skips 3
1019         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1020
1021         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1022         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1023         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1024         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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
1029         // Do some rebalance loop payments, simultaneously
1030         let mut hops = Vec::with_capacity(3);
1031         hops.push(RouteHop {
1032                 pubkey: nodes[2].node.get_our_node_id(),
1033                 node_features: NodeFeatures::empty(),
1034                 short_channel_id: chan_2.0.contents.short_channel_id,
1035                 channel_features: ChannelFeatures::empty(),
1036                 fee_msat: 0,
1037                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1038                 maybe_announced_channel: true,
1039         });
1040         hops.push(RouteHop {
1041                 pubkey: nodes[3].node.get_our_node_id(),
1042                 node_features: NodeFeatures::empty(),
1043                 short_channel_id: chan_3.0.contents.short_channel_id,
1044                 channel_features: ChannelFeatures::empty(),
1045                 fee_msat: 0,
1046                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1047                 maybe_announced_channel: true,
1048         });
1049         hops.push(RouteHop {
1050                 pubkey: nodes[1].node.get_our_node_id(),
1051                 node_features: nodes[1].node.node_features(),
1052                 short_channel_id: chan_4.0.contents.short_channel_id,
1053                 channel_features: nodes[1].node.channel_features(),
1054                 fee_msat: 1000000,
1055                 cltv_expiry_delta: TEST_FINAL_CLTV,
1056                 maybe_announced_channel: true,
1057         });
1058         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;
1059         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;
1060         let payment_preimage_1 = send_along_route(&nodes[1],
1061                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1062                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1063
1064         let mut hops = Vec::with_capacity(3);
1065         hops.push(RouteHop {
1066                 pubkey: nodes[3].node.get_our_node_id(),
1067                 node_features: NodeFeatures::empty(),
1068                 short_channel_id: chan_4.0.contents.short_channel_id,
1069                 channel_features: ChannelFeatures::empty(),
1070                 fee_msat: 0,
1071                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1072                 maybe_announced_channel: true,
1073         });
1074         hops.push(RouteHop {
1075                 pubkey: nodes[2].node.get_our_node_id(),
1076                 node_features: NodeFeatures::empty(),
1077                 short_channel_id: chan_3.0.contents.short_channel_id,
1078                 channel_features: ChannelFeatures::empty(),
1079                 fee_msat: 0,
1080                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1081                 maybe_announced_channel: true,
1082         });
1083         hops.push(RouteHop {
1084                 pubkey: nodes[1].node.get_our_node_id(),
1085                 node_features: nodes[1].node.node_features(),
1086                 short_channel_id: chan_2.0.contents.short_channel_id,
1087                 channel_features: nodes[1].node.channel_features(),
1088                 fee_msat: 1000000,
1089                 cltv_expiry_delta: TEST_FINAL_CLTV,
1090                 maybe_announced_channel: true,
1091         });
1092         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;
1093         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;
1094         let payment_hash_2 = send_along_route(&nodes[1],
1095                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1096                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1097
1098         // Claim the rebalances...
1099         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1100         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1101
1102         // Close down the channels...
1103         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1104         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1105         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1106         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1107         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1108         check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1109         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1110         check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1111         check_closed_event!(nodes[3], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1112         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1113         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1114         check_closed_event!(nodes[3], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1115 }
1116
1117 #[test]
1118 fn holding_cell_htlc_counting() {
1119         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1120         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1121         // commitment dance rounds.
1122         let chanmon_cfgs = create_chanmon_cfgs(3);
1123         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1124         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1125         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1126         create_announced_chan_between_nodes(&nodes, 0, 1);
1127         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1128
1129         // Fetch a route in advance as we will be unable to once we're unable to send.
1130         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1131
1132         let mut payments = Vec::new();
1133         for _ in 0..50 {
1134                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1135                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1136                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1137                 payments.push((payment_preimage, payment_hash));
1138         }
1139         check_added_monitors!(nodes[1], 1);
1140
1141         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1142         assert_eq!(events.len(), 1);
1143         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1144         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1145
1146         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1147         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1148         // another HTLC.
1149         {
1150                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1151                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1152                         ), true, APIError::ChannelUnavailable { .. }, {});
1153                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1154         }
1155
1156         // This should also be true if we try to forward a payment.
1157         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1158         {
1159                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1160                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1161                 check_added_monitors!(nodes[0], 1);
1162         }
1163
1164         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1165         assert_eq!(events.len(), 1);
1166         let payment_event = SendEvent::from_event(events.pop().unwrap());
1167         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1168
1169         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1170         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1171         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1172         // fails), the second will process the resulting failure and fail the HTLC backward.
1173         expect_pending_htlcs_forwardable!(nodes[1]);
1174         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 }]);
1175         check_added_monitors!(nodes[1], 1);
1176
1177         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1178         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1179         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1180
1181         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1182
1183         // Now forward all the pending HTLCs and claim them back
1184         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1185         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1186         check_added_monitors!(nodes[2], 1);
1187
1188         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1189         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1190         check_added_monitors!(nodes[1], 1);
1191         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1192
1193         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1194         check_added_monitors!(nodes[1], 1);
1195         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1196
1197         for ref update in as_updates.update_add_htlcs.iter() {
1198                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1199         }
1200         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1201         check_added_monitors!(nodes[2], 1);
1202         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1203         check_added_monitors!(nodes[2], 1);
1204         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1205
1206         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1207         check_added_monitors!(nodes[1], 1);
1208         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1209         check_added_monitors!(nodes[1], 1);
1210         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1211
1212         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1213         check_added_monitors!(nodes[2], 1);
1214
1215         expect_pending_htlcs_forwardable!(nodes[2]);
1216
1217         let events = nodes[2].node.get_and_clear_pending_events();
1218         assert_eq!(events.len(), payments.len());
1219         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1220                 match event {
1221                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1222                                 assert_eq!(*payment_hash, *hash);
1223                         },
1224                         _ => panic!("Unexpected event"),
1225                 };
1226         }
1227
1228         for (preimage, _) in payments.drain(..) {
1229                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1230         }
1231
1232         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1233 }
1234
1235 #[test]
1236 fn duplicate_htlc_test() {
1237         // Test that we accept duplicate payment_hash HTLCs across the network and that
1238         // claiming/failing them are all separate and don't affect each other
1239         let chanmon_cfgs = create_chanmon_cfgs(6);
1240         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1241         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1242         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1243
1244         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1245         create_announced_chan_between_nodes(&nodes, 0, 3);
1246         create_announced_chan_between_nodes(&nodes, 1, 3);
1247         create_announced_chan_between_nodes(&nodes, 2, 3);
1248         create_announced_chan_between_nodes(&nodes, 3, 4);
1249         create_announced_chan_between_nodes(&nodes, 3, 5);
1250
1251         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1252
1253         *nodes[0].network_payment_count.borrow_mut() -= 1;
1254         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1255
1256         *nodes[0].network_payment_count.borrow_mut() -= 1;
1257         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1258
1259         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1260         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1261         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1262 }
1263
1264 #[test]
1265 fn test_duplicate_htlc_different_direction_onchain() {
1266         // Test that ChannelMonitor doesn't generate 2 preimage txn
1267         // when we have 2 HTLCs with same preimage that go across a node
1268         // in opposite directions, even with the same payment secret.
1269         let chanmon_cfgs = create_chanmon_cfgs(2);
1270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1272         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1273
1274         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1275
1276         // balancing
1277         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1278
1279         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1280
1281         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1282         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1283         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1284
1285         // Provide preimage to node 0 by claiming payment
1286         nodes[0].node.claim_funds(payment_preimage);
1287         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1288         check_added_monitors!(nodes[0], 1);
1289
1290         // Broadcast node 1 commitment txn
1291         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1292
1293         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1294         let mut has_both_htlcs = 0; // check htlcs match ones committed
1295         for outp in remote_txn[0].output.iter() {
1296                 if outp.value == 800_000 / 1000 {
1297                         has_both_htlcs += 1;
1298                 } else if outp.value == 900_000 / 1000 {
1299                         has_both_htlcs += 1;
1300                 }
1301         }
1302         assert_eq!(has_both_htlcs, 2);
1303
1304         mine_transaction(&nodes[0], &remote_txn[0]);
1305         check_added_monitors!(nodes[0], 1);
1306         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1307         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1308
1309         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1310         assert_eq!(claim_txn.len(), 3);
1311
1312         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1313         check_spends!(claim_txn[1], remote_txn[0]);
1314         check_spends!(claim_txn[2], remote_txn[0]);
1315         let preimage_tx = &claim_txn[0];
1316         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1317                 (&claim_txn[1], &claim_txn[2])
1318         } else {
1319                 (&claim_txn[2], &claim_txn[1])
1320         };
1321
1322         assert_eq!(preimage_tx.input.len(), 1);
1323         assert_eq!(preimage_bump_tx.input.len(), 1);
1324
1325         assert_eq!(preimage_tx.input.len(), 1);
1326         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1327         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1328
1329         assert_eq!(timeout_tx.input.len(), 1);
1330         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1331         check_spends!(timeout_tx, remote_txn[0]);
1332         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1333
1334         let events = nodes[0].node.get_and_clear_pending_msg_events();
1335         assert_eq!(events.len(), 3);
1336         for e in events {
1337                 match e {
1338                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1339                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1340                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1341                                 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1342                         },
1343                         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, .. } } => {
1344                                 assert!(update_add_htlcs.is_empty());
1345                                 assert!(update_fail_htlcs.is_empty());
1346                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1347                                 assert!(update_fail_malformed_htlcs.is_empty());
1348                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1349                         },
1350                         _ => panic!("Unexpected event"),
1351                 }
1352         }
1353 }
1354
1355 #[test]
1356 fn test_basic_channel_reserve() {
1357         let chanmon_cfgs = create_chanmon_cfgs(2);
1358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1361         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1362
1363         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1364         let channel_reserve = chan_stat.channel_reserve_msat;
1365
1366         // The 2* and +1 are for the fee spike reserve.
1367         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));
1368         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1369         let (mut route, our_payment_hash, _, our_payment_secret) =
1370                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1371         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1372         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1373                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1374         match err {
1375                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1376                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1377                         else { panic!("Unexpected error variant"); }
1378                 },
1379                 _ => panic!("Unexpected error variant"),
1380         }
1381         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1382
1383         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1384 }
1385
1386 #[test]
1387 fn test_fee_spike_violation_fails_htlc() {
1388         let chanmon_cfgs = create_chanmon_cfgs(2);
1389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1391         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1392         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1393
1394         let (mut route, payment_hash, _, payment_secret) =
1395                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1396         route.paths[0].hops[0].fee_msat += 1;
1397         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1398         let secp_ctx = Secp256k1::new();
1399         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1400
1401         let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;
1402
1403         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1404         let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1405         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1406                 3460001, &recipient_onion_fields, cur_height, &None).unwrap();
1407         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1408         let msg = msgs::UpdateAddHTLC {
1409                 channel_id: chan.2,
1410                 htlc_id: 0,
1411                 amount_msat: htlc_msat,
1412                 payment_hash: payment_hash,
1413                 cltv_expiry: htlc_cltv,
1414                 onion_routing_packet: onion_packet,
1415                 skimmed_fee_msat: None,
1416                 blinding_point: 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(), 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",
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 recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1603         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1604                 700_000, &recipient_onion_fields, cur_height, &None).unwrap();
1605         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1606         let msg = msgs::UpdateAddHTLC {
1607                 channel_id: chan.2,
1608                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1609                 amount_msat: htlc_msat,
1610                 payment_hash: payment_hash,
1611                 cltv_expiry: htlc_cltv,
1612                 onion_routing_packet: onion_packet,
1613                 skimmed_fee_msat: None,
1614                 blinding_point: None,
1615         };
1616
1617         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1618         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1619         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value", 3);
1620         assert_eq!(nodes[0].node.list_channels().len(), 0);
1621         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1622         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1623         check_added_monitors!(nodes[0], 1);
1624         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() },
1625                 [nodes[1].node.get_our_node_id()], 100000);
1626 }
1627
1628 #[test]
1629 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1630         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1631         // calculating our commitment transaction fee (this was previously broken).
1632         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1633         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1634
1635         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1636         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1637         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1638         let default_config = UserConfig::default();
1639         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1640
1641         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1642         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1643         // transaction fee with 0 HTLCs (183 sats)).
1644         let mut push_amt = 100_000_000;
1645         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1646         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1647         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1648
1649         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1650                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1651         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1652         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1653         // commitment transaction fee.
1654         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1655
1656         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1657         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1658                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1659         }
1660
1661         // One more than the dust amt should fail, however.
1662         let (mut route, our_payment_hash, _, our_payment_secret) =
1663                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1664         route.paths[0].hops[0].fee_msat += 1;
1665         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1666                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1667                 ), true, APIError::ChannelUnavailable { .. }, {});
1668 }
1669
1670 #[test]
1671 fn test_chan_init_feerate_unaffordability() {
1672         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1673         // channel reserve and feerate requirements.
1674         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1675         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1678         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1679         let default_config = UserConfig::default();
1680         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1681
1682         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1683         // HTLC.
1684         let mut push_amt = 100_000_000;
1685         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1686         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1687                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1688
1689         // During open, we don't have a "counterparty channel reserve" to check against, so that
1690         // requirement only comes into play on the open_channel handling side.
1691         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1692         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1693         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1694         open_channel_msg.push_msat += 1;
1695         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1696
1697         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1698         assert_eq!(msg_events.len(), 1);
1699         match msg_events[0] {
1700                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1701                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1702                 },
1703                 _ => panic!("Unexpected event"),
1704         }
1705 }
1706
1707 #[test]
1708 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1709         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1710         // calculating our counterparty's commitment transaction fee (this was previously broken).
1711         let chanmon_cfgs = create_chanmon_cfgs(2);
1712         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1713         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1714         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1715         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1716
1717         let payment_amt = 46000; // Dust amount
1718         // In the previous code, these first four payments would succeed.
1719         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1720         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1722         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1723
1724         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1729         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1730
1731         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1732         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1733         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1734         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1735 }
1736
1737 #[test]
1738 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1739         let chanmon_cfgs = create_chanmon_cfgs(3);
1740         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1741         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1742         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1743         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1744         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1745
1746         let feemsat = 239;
1747         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1748         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1749         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1750         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1751
1752         // Add a 2* and +1 for the fee spike reserve.
1753         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1754         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;
1755         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1756
1757         // Add a pending HTLC.
1758         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1759         let payment_event_1 = {
1760                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1761                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1762                 check_added_monitors!(nodes[0], 1);
1763
1764                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1765                 assert_eq!(events.len(), 1);
1766                 SendEvent::from_event(events.remove(0))
1767         };
1768         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1769
1770         // Attempt to trigger a channel reserve violation --> payment failure.
1771         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1772         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;
1773         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1774         let mut route_2 = route_1.clone();
1775         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1776
1777         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1778         let secp_ctx = Secp256k1::new();
1779         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1780         let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
1781         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1782         let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
1783         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1784                 &route_2.paths[0], recv_value_2, &recipient_onion_fields, cur_height, &None).unwrap();
1785         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1786         let msg = msgs::UpdateAddHTLC {
1787                 channel_id: chan.2,
1788                 htlc_id: 1,
1789                 amount_msat: htlc_msat + 1,
1790                 payment_hash: our_payment_hash_1,
1791                 cltv_expiry: htlc_cltv,
1792                 onion_routing_packet: onion_packet,
1793                 skimmed_fee_msat: None,
1794                 blinding_point: None,
1795         };
1796
1797         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1798         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1799         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value", 3);
1800         assert_eq!(nodes[1].node.list_channels().len(), 1);
1801         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1802         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1803         check_added_monitors!(nodes[1], 1);
1804         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1805                 [nodes[0].node.get_our_node_id()], 100000);
1806 }
1807
1808 #[test]
1809 fn test_inbound_outbound_capacity_is_not_zero() {
1810         let chanmon_cfgs = create_chanmon_cfgs(2);
1811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1814         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1815         let channels0 = node_chanmgrs[0].list_channels();
1816         let channels1 = node_chanmgrs[1].list_channels();
1817         let default_config = UserConfig::default();
1818         assert_eq!(channels0.len(), 1);
1819         assert_eq!(channels1.len(), 1);
1820
1821         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1822         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1823         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1824
1825         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1826         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1827 }
1828
1829 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1830         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1831 }
1832
1833 #[test]
1834 fn test_channel_reserve_holding_cell_htlcs() {
1835         let chanmon_cfgs = create_chanmon_cfgs(3);
1836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837         // When this test was written, the default base fee floated based on the HTLC count.
1838         // It is now fixed, so we simply set the fee to the expected value here.
1839         let mut config = test_default_channel_config();
1840         config.channel_config.forwarding_fee_base_msat = 239;
1841         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1842         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1843         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1844         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1845
1846         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1847         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1848
1849         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1850         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1851
1852         macro_rules! expect_forward {
1853                 ($node: expr) => {{
1854                         let mut events = $node.node.get_and_clear_pending_msg_events();
1855                         assert_eq!(events.len(), 1);
1856                         check_added_monitors!($node, 1);
1857                         let payment_event = SendEvent::from_event(events.remove(0));
1858                         payment_event
1859                 }}
1860         }
1861
1862         let feemsat = 239; // set above
1863         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1864         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1865         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1866
1867         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1868
1869         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1870         {
1871                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1872                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1873                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1874                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1875                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1876
1877                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1878                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1879                         ), true, APIError::ChannelUnavailable { .. }, {});
1880                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1881         }
1882
1883         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1884         // nodes[0]'s wealth
1885         loop {
1886                 let amt_msat = recv_value_0 + total_fee_msat;
1887                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1888                 // Also, ensure that each payment has enough to be over the dust limit to
1889                 // ensure it'll be included in each commit tx fee calculation.
1890                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1891                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1892                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1893                         break;
1894                 }
1895
1896                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1897                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1898                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1899                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1900                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1901
1902                 let (stat01_, stat11_, stat12_, stat22_) = (
1903                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1904                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1905                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1906                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1907                 );
1908
1909                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1910                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1911                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1912                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1913                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1914         }
1915
1916         // adding pending output.
1917         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1918         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1919         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1920         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1921         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1922         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1923         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1924         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1925         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1926         // policy.
1927         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1928         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1929         let amt_msat_1 = recv_value_1 + total_fee_msat;
1930
1931         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1932         let payment_event_1 = {
1933                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1934                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1935                 check_added_monitors!(nodes[0], 1);
1936
1937                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1938                 assert_eq!(events.len(), 1);
1939                 SendEvent::from_event(events.remove(0))
1940         };
1941         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1942
1943         // channel reserve test with htlc pending output > 0
1944         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1945         {
1946                 let mut route = route_1.clone();
1947                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1948                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1949                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1950                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1951                         ), true, APIError::ChannelUnavailable { .. }, {});
1952                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1953         }
1954
1955         // split the rest to test holding cell
1956         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1957         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1958         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1959         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1960         {
1961                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1962                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1963         }
1964
1965         // now see if they go through on both sides
1966         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1967         // but this will stuck in the holding cell
1968         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1969                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1970         check_added_monitors!(nodes[0], 0);
1971         let events = nodes[0].node.get_and_clear_pending_events();
1972         assert_eq!(events.len(), 0);
1973
1974         // test with outbound holding cell amount > 0
1975         {
1976                 let (mut route, our_payment_hash, _, our_payment_secret) =
1977                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1978                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1979                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1980                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1981                         ), true, APIError::ChannelUnavailable { .. }, {});
1982                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1983         }
1984
1985         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1986         // this will also stuck in the holding cell
1987         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1988                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1989         check_added_monitors!(nodes[0], 0);
1990         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1991         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1992
1993         // flush the pending htlc
1994         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1995         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1996         check_added_monitors!(nodes[1], 1);
1997
1998         // the pending htlc should be promoted to committed
1999         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2000         check_added_monitors!(nodes[0], 1);
2001         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2002
2003         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2004         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2005         // No commitment_signed so get_event_msg's assert(len == 1) passes
2006         check_added_monitors!(nodes[0], 1);
2007
2008         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2009         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2010         check_added_monitors!(nodes[1], 1);
2011
2012         expect_pending_htlcs_forwardable!(nodes[1]);
2013
2014         let ref payment_event_11 = expect_forward!(nodes[1]);
2015         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2016         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2017
2018         expect_pending_htlcs_forwardable!(nodes[2]);
2019         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2020
2021         // flush the htlcs in the holding cell
2022         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2023         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2024         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2025         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2026         expect_pending_htlcs_forwardable!(nodes[1]);
2027
2028         let ref payment_event_3 = expect_forward!(nodes[1]);
2029         assert_eq!(payment_event_3.msgs.len(), 2);
2030         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2031         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2032
2033         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2034         expect_pending_htlcs_forwardable!(nodes[2]);
2035
2036         let events = nodes[2].node.get_and_clear_pending_events();
2037         assert_eq!(events.len(), 2);
2038         match events[0] {
2039                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2040                         assert_eq!(our_payment_hash_21, *payment_hash);
2041                         assert_eq!(recv_value_21, amount_msat);
2042                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2043                         assert_eq!(via_channel_id, Some(chan_2.2));
2044                         match &purpose {
2045                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
2046                                         assert!(payment_preimage.is_none());
2047                                         assert_eq!(our_payment_secret_21, *payment_secret);
2048                                 },
2049                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
2050                         }
2051                 },
2052                 _ => panic!("Unexpected event"),
2053         }
2054         match events[1] {
2055                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2056                         assert_eq!(our_payment_hash_22, *payment_hash);
2057                         assert_eq!(recv_value_22, amount_msat);
2058                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2059                         assert_eq!(via_channel_id, Some(chan_2.2));
2060                         match &purpose {
2061                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
2062                                         assert!(payment_preimage.is_none());
2063                                         assert_eq!(our_payment_secret_22, *payment_secret);
2064                                 },
2065                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
2066                         }
2067                 },
2068                 _ => panic!("Unexpected event"),
2069         }
2070
2071         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2072         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2073         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2074
2075         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2076         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2077         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2078
2079         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2080         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2081         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2082         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2083         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2084
2085         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2086         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2087 }
2088
2089 #[test]
2090 fn channel_reserve_in_flight_removes() {
2091         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2092         // can send to its counterparty, but due to update ordering, the other side may not yet have
2093         // considered those HTLCs fully removed.
2094         // This tests that we don't count HTLCs which will not be included in the next remote
2095         // commitment transaction towards the reserve value (as it implies no commitment transaction
2096         // will be generated which violates the remote reserve value).
2097         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2098         // To test this we:
2099         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2100         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2101         //    you only consider the value of the first HTLC, it may not),
2102         //  * start routing a third HTLC from A to B,
2103         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2104         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2105         //  * deliver the first fulfill from B
2106         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2107         //    claim,
2108         //  * deliver A's response CS and RAA.
2109         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2110         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2111         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2112         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2113         let chanmon_cfgs = create_chanmon_cfgs(2);
2114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2116         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2117         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2118
2119         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2120         // Route the first two HTLCs.
2121         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2122         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2123         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2124
2125         // Start routing the third HTLC (this is just used to get everyone in the right state).
2126         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2127         let send_1 = {
2128                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2129                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2130                 check_added_monitors!(nodes[0], 1);
2131                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2132                 assert_eq!(events.len(), 1);
2133                 SendEvent::from_event(events.remove(0))
2134         };
2135
2136         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2137         // initial fulfill/CS.
2138         nodes[1].node.claim_funds(payment_preimage_1);
2139         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2140         check_added_monitors!(nodes[1], 1);
2141         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2142
2143         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2144         // remove the second HTLC when we send the HTLC back from B to A.
2145         nodes[1].node.claim_funds(payment_preimage_2);
2146         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2147         check_added_monitors!(nodes[1], 1);
2148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2149
2150         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2151         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2152         check_added_monitors!(nodes[0], 1);
2153         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2154         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2155
2156         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2157         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2158         check_added_monitors!(nodes[1], 1);
2159         // B is already AwaitingRAA, so cant generate a CS here
2160         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2161
2162         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2163         check_added_monitors!(nodes[1], 1);
2164         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2165
2166         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2167         check_added_monitors!(nodes[0], 1);
2168         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2169
2170         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2171         check_added_monitors!(nodes[1], 1);
2172         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2173
2174         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2175         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2176         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2177         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2178         // on-chain as necessary).
2179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2180         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2181         check_added_monitors!(nodes[0], 1);
2182         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2183         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2184
2185         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2186         check_added_monitors!(nodes[1], 1);
2187         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2188
2189         expect_pending_htlcs_forwardable!(nodes[1]);
2190         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2191
2192         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2193         // resolve the second HTLC from A's point of view.
2194         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2195         check_added_monitors!(nodes[0], 1);
2196         expect_payment_path_successful!(nodes[0]);
2197         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2198
2199         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2200         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2201         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2202         let send_2 = {
2203                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2204                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2205                 check_added_monitors!(nodes[1], 1);
2206                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2207                 assert_eq!(events.len(), 1);
2208                 SendEvent::from_event(events.remove(0))
2209         };
2210
2211         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2212         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2213         check_added_monitors!(nodes[0], 1);
2214         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2215
2216         // Now just resolve all the outstanding messages/HTLCs for completeness...
2217
2218         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2219         check_added_monitors!(nodes[1], 1);
2220         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2221
2222         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2223         check_added_monitors!(nodes[1], 1);
2224
2225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2226         check_added_monitors!(nodes[0], 1);
2227         expect_payment_path_successful!(nodes[0]);
2228         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2229
2230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2231         check_added_monitors!(nodes[1], 1);
2232         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2233
2234         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2235         check_added_monitors!(nodes[0], 1);
2236
2237         expect_pending_htlcs_forwardable!(nodes[0]);
2238         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2239
2240         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2241         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2242 }
2243
2244 #[test]
2245 fn channel_monitor_network_test() {
2246         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2247         // tests that ChannelMonitor is able to recover from various states.
2248         let chanmon_cfgs = create_chanmon_cfgs(5);
2249         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2250         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2251         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2252
2253         // Create some initial channels
2254         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2255         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2256         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2257         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2258
2259         // Make sure all nodes are at the same starting height
2260         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2261         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2262         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2263         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2264         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2265
2266         // Rebalance the network a bit by relaying one payment through all the channels...
2267         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2268         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2269         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2270         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2271
2272         // Simple case with no pending HTLCs:
2273         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2274         check_added_monitors!(nodes[1], 1);
2275         check_closed_broadcast!(nodes[1], true);
2276         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2277         {
2278                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2279                 assert_eq!(node_txn.len(), 1);
2280                 mine_transaction(&nodes[1], &node_txn[0]);
2281                 if nodes[1].connect_style.borrow().updates_best_block_first() {
2282                         let _ = nodes[1].tx_broadcaster.txn_broadcast();
2283                 }
2284
2285                 mine_transaction(&nodes[0], &node_txn[0]);
2286                 check_added_monitors!(nodes[0], 1);
2287                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2288         }
2289         check_closed_broadcast!(nodes[0], true);
2290         assert_eq!(nodes[0].node.list_channels().len(), 0);
2291         assert_eq!(nodes[1].node.list_channels().len(), 1);
2292         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2293
2294         // One pending HTLC is discarded by the force-close:
2295         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2296
2297         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2298         // broadcasted until we reach the timelock time).
2299         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2300         check_closed_broadcast!(nodes[1], true);
2301         check_added_monitors!(nodes[1], 1);
2302         {
2303                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2304                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2305                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2306                 mine_transaction(&nodes[2], &node_txn[0]);
2307                 check_added_monitors!(nodes[2], 1);
2308                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2309         }
2310         check_closed_broadcast!(nodes[2], true);
2311         assert_eq!(nodes[1].node.list_channels().len(), 0);
2312         assert_eq!(nodes[2].node.list_channels().len(), 1);
2313         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2314         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2315
2316         macro_rules! claim_funds {
2317                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2318                         {
2319                                 $node.node.claim_funds($preimage);
2320                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2321                                 check_added_monitors!($node, 1);
2322
2323                                 let events = $node.node.get_and_clear_pending_msg_events();
2324                                 assert_eq!(events.len(), 1);
2325                                 match events[0] {
2326                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2327                                                 assert!(update_add_htlcs.is_empty());
2328                                                 assert!(update_fail_htlcs.is_empty());
2329                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2330                                         },
2331                                         _ => panic!("Unexpected event"),
2332                                 };
2333                         }
2334                 }
2335         }
2336
2337         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2338         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2339         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2340         check_added_monitors!(nodes[2], 1);
2341         check_closed_broadcast!(nodes[2], true);
2342         let node2_commitment_txid;
2343         {
2344                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2345                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2346                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2347                 node2_commitment_txid = node_txn[0].txid();
2348
2349                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2350                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2351                 mine_transaction(&nodes[3], &node_txn[0]);
2352                 check_added_monitors!(nodes[3], 1);
2353                 check_preimage_claim(&nodes[3], &node_txn);
2354         }
2355         check_closed_broadcast!(nodes[3], true);
2356         assert_eq!(nodes[2].node.list_channels().len(), 0);
2357         assert_eq!(nodes[3].node.list_channels().len(), 1);
2358         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2359         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2360
2361         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2362         // confusing us in the following tests.
2363         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2364
2365         // One pending HTLC to time out:
2366         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2367         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2368         // buffer space).
2369
2370         let (close_chan_update_1, close_chan_update_2) = {
2371                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2372                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2373                 assert_eq!(events.len(), 2);
2374                 let close_chan_update_1 = match events[1] {
2375                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2376                                 msg.clone()
2377                         },
2378                         _ => panic!("Unexpected event"),
2379                 };
2380                 match events[0] {
2381                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2382                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2383                         },
2384                         _ => panic!("Unexpected event"),
2385                 }
2386                 check_added_monitors!(nodes[3], 1);
2387
2388                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2389                 {
2390                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2391                         node_txn.retain(|tx| {
2392                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2393                                         false
2394                                 } else { true }
2395                         });
2396                 }
2397
2398                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2399
2400                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2401                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2402
2403                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2404                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2405                 assert_eq!(events.len(), 2);
2406                 let close_chan_update_2 = match events[1] {
2407                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2408                                 msg.clone()
2409                         },
2410                         _ => panic!("Unexpected event"),
2411                 };
2412                 match events[0] {
2413                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2414                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2415                         },
2416                         _ => panic!("Unexpected event"),
2417                 }
2418                 check_added_monitors!(nodes[4], 1);
2419                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2420                 check_closed_event!(nodes[4], 1, ClosureReason::HTLCsTimedOut, [nodes[3].node.get_our_node_id()], 100000);
2421
2422                 mine_transaction(&nodes[4], &node_txn[0]);
2423                 check_preimage_claim(&nodes[4], &node_txn);
2424                 (close_chan_update_1, close_chan_update_2)
2425         };
2426         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2427         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2428         assert_eq!(nodes[3].node.list_channels().len(), 0);
2429         assert_eq!(nodes[4].node.list_channels().len(), 0);
2430
2431         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2432                 Ok(ChannelMonitorUpdateStatus::Completed));
2433         check_closed_event!(nodes[3], 1, ClosureReason::HTLCsTimedOut, [nodes[4].node.get_our_node_id()], 100000);
2434 }
2435
2436 #[test]
2437 fn test_justice_tx_htlc_timeout() {
2438         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2439         let mut alice_config = test_default_channel_config();
2440         alice_config.channel_handshake_config.announced_channel = true;
2441         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2442         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2443         let mut bob_config = test_default_channel_config();
2444         bob_config.channel_handshake_config.announced_channel = true;
2445         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2446         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2447         let user_cfgs = [Some(alice_config), Some(bob_config)];
2448         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2449         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2450         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2453         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2454         // Create some new channels:
2455         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2456
2457         // A pending HTLC which will be revoked:
2458         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2459         // Get the will-be-revoked local txn from nodes[0]
2460         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2461         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2462         assert_eq!(revoked_local_txn[0].input.len(), 1);
2463         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2464         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2465         assert_eq!(revoked_local_txn[1].input.len(), 1);
2466         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2467         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2468         // Revoke the old state
2469         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2470
2471         {
2472                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2473                 {
2474                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2475                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2476                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2477                         check_spends!(node_txn[0], revoked_local_txn[0]);
2478                         node_txn.swap_remove(0);
2479                 }
2480                 check_added_monitors!(nodes[1], 1);
2481                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2482                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2483
2484                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2485                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2486                 // Verify broadcast of revoked HTLC-timeout
2487                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2488                 check_added_monitors!(nodes[0], 1);
2489                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2490                 // Broadcast revoked HTLC-timeout on node 1
2491                 mine_transaction(&nodes[1], &node_txn[1]);
2492                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2493         }
2494         get_announce_close_broadcast_events(&nodes, 0, 1);
2495         assert_eq!(nodes[0].node.list_channels().len(), 0);
2496         assert_eq!(nodes[1].node.list_channels().len(), 0);
2497 }
2498
2499 #[test]
2500 fn test_justice_tx_htlc_success() {
2501         // Test justice txn built on revoked HTLC-Success tx, against both sides
2502         let mut alice_config = test_default_channel_config();
2503         alice_config.channel_handshake_config.announced_channel = true;
2504         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2505         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2506         let mut bob_config = test_default_channel_config();
2507         bob_config.channel_handshake_config.announced_channel = true;
2508         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2509         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2510         let user_cfgs = [Some(alice_config), Some(bob_config)];
2511         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2512         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2513         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2516         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2517         // Create some new channels:
2518         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2519
2520         // A pending HTLC which will be revoked:
2521         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2522         // Get the will-be-revoked local txn from B
2523         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2524         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2525         assert_eq!(revoked_local_txn[0].input.len(), 1);
2526         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2527         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2528         // Revoke the old state
2529         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2530         {
2531                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532                 {
2533                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2534                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2535                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2536
2537                         check_spends!(node_txn[0], revoked_local_txn[0]);
2538                         node_txn.swap_remove(0);
2539                 }
2540                 check_added_monitors!(nodes[0], 1);
2541                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2542
2543                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2544                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2545                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2546                 check_added_monitors!(nodes[1], 1);
2547                 mine_transaction(&nodes[0], &node_txn[1]);
2548                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2549                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2550         }
2551         get_announce_close_broadcast_events(&nodes, 0, 1);
2552         assert_eq!(nodes[0].node.list_channels().len(), 0);
2553         assert_eq!(nodes[1].node.list_channels().len(), 0);
2554 }
2555
2556 #[test]
2557 fn revoked_output_claim() {
2558         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2559         // transaction is broadcast by its counterparty
2560         let chanmon_cfgs = create_chanmon_cfgs(2);
2561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2563         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2564         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2565         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2566         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2567         assert_eq!(revoked_local_txn.len(), 1);
2568         // Only output is the full channel value back to nodes[0]:
2569         assert_eq!(revoked_local_txn[0].output.len(), 1);
2570         // Send a payment through, updating everyone's latest commitment txn
2571         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2572
2573         // Inform nodes[1] that nodes[0] broadcast a stale tx
2574         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2575         check_added_monitors!(nodes[1], 1);
2576         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2577         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2578         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2579
2580         check_spends!(node_txn[0], revoked_local_txn[0]);
2581
2582         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2583         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2584         get_announce_close_broadcast_events(&nodes, 0, 1);
2585         check_added_monitors!(nodes[0], 1);
2586         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2587 }
2588
2589 #[test]
2590 fn test_forming_justice_tx_from_monitor_updates() {
2591         do_test_forming_justice_tx_from_monitor_updates(true);
2592         do_test_forming_justice_tx_from_monitor_updates(false);
2593 }
2594
2595 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2596         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2597         // is properly formed and can be broadcasted/confirmed successfully in the event
2598         // that a revoked commitment transaction is broadcasted
2599         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2600         let chanmon_cfgs = create_chanmon_cfgs(2);
2601         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2602         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2603         let persisters = vec![WatchtowerPersister::new(destination_script0),
2604                 WatchtowerPersister::new(destination_script1)];
2605         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2606         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2607         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2608         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2609         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2610
2611         if !broadcast_initial_commitment {
2612                 // Send a payment to move the channel forward
2613                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2614         }
2615
2616         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2617         // We'll keep this commitment transaction to broadcast once it's revoked.
2618         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2619         assert_eq!(revoked_local_txn.len(), 1);
2620         let revoked_commitment_tx = &revoked_local_txn[0];
2621
2622         // Send another payment, now revoking the previous commitment tx
2623         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2624
2625         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2626         check_spends!(justice_tx, revoked_commitment_tx);
2627
2628         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2629         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2630
2631         check_added_monitors!(nodes[1], 1);
2632         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2633                 &[nodes[0].node.get_our_node_id()], 100_000);
2634         get_announce_close_broadcast_events(&nodes, 1, 0);
2635
2636         check_added_monitors!(nodes[0], 1);
2637         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2638                 &[nodes[1].node.get_our_node_id()], 100_000);
2639
2640         // Check that the justice tx has sent the revoked output value to nodes[1]
2641         let monitor = get_monitor!(nodes[1], channel_id);
2642         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2643                 match balance {
2644                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2645                         _ => panic!("Unexpected balance type"),
2646                 }
2647         });
2648         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2649         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2650         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2651         assert_eq!(total_claimable_balance, expected_claimable_balance);
2652 }
2653
2654
2655 #[test]
2656 fn claim_htlc_outputs_shared_tx() {
2657         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2658         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2659         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2660         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2661         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2662         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2663
2664         // Create some new channel:
2665         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2666
2667         // Rebalance the network to generate htlc in the two directions
2668         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2669         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2670         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2671         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2672
2673         // Get the will-be-revoked local txn from node[0]
2674         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2675         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2676         assert_eq!(revoked_local_txn[0].input.len(), 1);
2677         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2678         assert_eq!(revoked_local_txn[1].input.len(), 1);
2679         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2680         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2681         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2682
2683         //Revoke the old state
2684         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2685
2686         {
2687                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2688                 check_added_monitors!(nodes[0], 1);
2689                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2690                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2691                 check_added_monitors!(nodes[1], 1);
2692                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2693                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2694                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2695
2696                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2697                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2698
2699                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2700                 check_spends!(node_txn[0], revoked_local_txn[0]);
2701
2702                 let mut witness_lens = BTreeSet::new();
2703                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2704                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2705                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2706                 assert_eq!(witness_lens.len(), 3);
2707                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2708                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2709                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2710
2711                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2712                 // ANTI_REORG_DELAY confirmations.
2713                 mine_transaction(&nodes[1], &node_txn[0]);
2714                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2715                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2716         }
2717         get_announce_close_broadcast_events(&nodes, 0, 1);
2718         assert_eq!(nodes[0].node.list_channels().len(), 0);
2719         assert_eq!(nodes[1].node.list_channels().len(), 0);
2720 }
2721
2722 #[test]
2723 fn claim_htlc_outputs_single_tx() {
2724         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2725         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2726         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2729         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2730
2731         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2732
2733         // Rebalance the network to generate htlc in the two directions
2734         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2735         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2736         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2737         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2738         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2739
2740         // Get the will-be-revoked local txn from node[0]
2741         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2742
2743         //Revoke the old state
2744         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2745
2746         {
2747                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2748                 check_added_monitors!(nodes[0], 1);
2749                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2750                 check_added_monitors!(nodes[1], 1);
2751                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2752                 let mut events = nodes[0].node.get_and_clear_pending_events();
2753                 expect_pending_htlcs_forwardable_conditions(events[0..2].to_vec(), &[HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
2754                 match events.last().unwrap() {
2755                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2756                         _ => panic!("Unexpected event"),
2757                 }
2758
2759                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2760                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2761
2762                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2763
2764                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2765                 assert_eq!(node_txn[0].input.len(), 1);
2766                 check_spends!(node_txn[0], chan_1.3);
2767                 assert_eq!(node_txn[1].input.len(), 1);
2768                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2769                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2770                 check_spends!(node_txn[1], node_txn[0]);
2771
2772                 // Filter out any non justice transactions.
2773                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2774                 assert!(node_txn.len() > 3);
2775
2776                 assert_eq!(node_txn[0].input.len(), 1);
2777                 assert_eq!(node_txn[1].input.len(), 1);
2778                 assert_eq!(node_txn[2].input.len(), 1);
2779
2780                 check_spends!(node_txn[0], revoked_local_txn[0]);
2781                 check_spends!(node_txn[1], revoked_local_txn[0]);
2782                 check_spends!(node_txn[2], revoked_local_txn[0]);
2783
2784                 let mut witness_lens = BTreeSet::new();
2785                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2786                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2787                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2788                 assert_eq!(witness_lens.len(), 3);
2789                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2790                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2791                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2792
2793                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2794                 // ANTI_REORG_DELAY confirmations.
2795                 mine_transaction(&nodes[1], &node_txn[0]);
2796                 mine_transaction(&nodes[1], &node_txn[1]);
2797                 mine_transaction(&nodes[1], &node_txn[2]);
2798                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2799                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2800         }
2801         get_announce_close_broadcast_events(&nodes, 0, 1);
2802         assert_eq!(nodes[0].node.list_channels().len(), 0);
2803         assert_eq!(nodes[1].node.list_channels().len(), 0);
2804 }
2805
2806 #[test]
2807 fn test_htlc_on_chain_success() {
2808         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2809         // the preimage backward accordingly. So here we test that ChannelManager is
2810         // broadcasting the right event to other nodes in payment path.
2811         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2812         // A --------------------> B ----------------------> C (preimage)
2813         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2814         // commitment transaction was broadcast.
2815         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2816         // towards B.
2817         // B should be able to claim via preimage if A then broadcasts its local tx.
2818         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2819         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2820         // PaymentSent event).
2821
2822         let chanmon_cfgs = create_chanmon_cfgs(3);
2823         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2824         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2825         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2826
2827         // Create some initial channels
2828         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2829         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2830
2831         // Ensure all nodes are at the same height
2832         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2833         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2834         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2835         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2836
2837         // Rebalance the network a bit by relaying one payment through all the channels...
2838         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2839         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2840
2841         let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2842         let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2843
2844         // Broadcast legit commitment tx from C on B's chain
2845         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2846         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2847         assert_eq!(commitment_tx.len(), 1);
2848         check_spends!(commitment_tx[0], chan_2.3);
2849         nodes[2].node.claim_funds(our_payment_preimage);
2850         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2851         nodes[2].node.claim_funds(our_payment_preimage_2);
2852         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2853         check_added_monitors!(nodes[2], 2);
2854         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2855         assert!(updates.update_add_htlcs.is_empty());
2856         assert!(updates.update_fail_htlcs.is_empty());
2857         assert!(updates.update_fail_malformed_htlcs.is_empty());
2858         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2859
2860         mine_transaction(&nodes[2], &commitment_tx[0]);
2861         check_closed_broadcast!(nodes[2], true);
2862         check_added_monitors!(nodes[2], 1);
2863         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2864         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2865         assert_eq!(node_txn.len(), 2);
2866         check_spends!(node_txn[0], commitment_tx[0]);
2867         check_spends!(node_txn[1], commitment_tx[0]);
2868         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2869         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2870         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2871         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2872         assert_eq!(node_txn[0].lock_time, LockTime::ZERO);
2873         assert_eq!(node_txn[1].lock_time, LockTime::ZERO);
2874
2875         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2876         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2877         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2878         {
2879                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2880                 assert_eq!(added_monitors.len(), 1);
2881                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2882                 added_monitors.clear();
2883         }
2884         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2885         assert_eq!(forwarded_events.len(), 3);
2886         match forwarded_events[0] {
2887                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2888                 _ => panic!("Unexpected event"),
2889         }
2890         let chan_id = Some(chan_1.2);
2891         match forwarded_events[1] {
2892                 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2893                         next_channel_id, outbound_amount_forwarded_msat, ..
2894                 } => {
2895                         assert_eq!(total_fee_earned_msat, Some(1000));
2896                         assert_eq!(prev_channel_id, chan_id);
2897                         assert_eq!(claim_from_onchain_tx, true);
2898                         assert_eq!(next_channel_id, Some(chan_2.2));
2899                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2900                 },
2901                 _ => panic!()
2902         }
2903         match forwarded_events[2] {
2904                 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2905                         next_channel_id, outbound_amount_forwarded_msat, ..
2906                 } => {
2907                         assert_eq!(total_fee_earned_msat, Some(1000));
2908                         assert_eq!(prev_channel_id, chan_id);
2909                         assert_eq!(claim_from_onchain_tx, true);
2910                         assert_eq!(next_channel_id, Some(chan_2.2));
2911                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2912                 },
2913                 _ => panic!()
2914         }
2915         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2916         {
2917                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2918                 assert_eq!(added_monitors.len(), 2);
2919                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2920                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2921                 added_monitors.clear();
2922         }
2923         assert_eq!(events.len(), 3);
2924
2925         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2926         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2927
2928         match nodes_2_event {
2929                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2930                 _ => panic!("Unexpected event"),
2931         }
2932
2933         match nodes_0_event {
2934                 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, .. } } => {
2935                         assert!(update_add_htlcs.is_empty());
2936                         assert!(update_fail_htlcs.is_empty());
2937                         assert_eq!(update_fulfill_htlcs.len(), 1);
2938                         assert!(update_fail_malformed_htlcs.is_empty());
2939                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2940                 },
2941                 _ => panic!("Unexpected event"),
2942         };
2943
2944         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2945         match events[0] {
2946                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2947                 _ => panic!("Unexpected event"),
2948         }
2949
2950         macro_rules! check_tx_local_broadcast {
2951                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2952                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2953                         assert_eq!(node_txn.len(), 2);
2954                         // Node[1]: 2 * HTLC-timeout tx
2955                         // Node[0]: 2 * HTLC-timeout tx
2956                         check_spends!(node_txn[0], $commitment_tx);
2957                         check_spends!(node_txn[1], $commitment_tx);
2958                         assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2959                         assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2960                         if $htlc_offered {
2961                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2962                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2963                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2964                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2965                         } else {
2966                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2967                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2968                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2969                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2970                         }
2971                         node_txn.clear();
2972                 } }
2973         }
2974         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2975         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2976
2977         // Broadcast legit commitment tx from A on B's chain
2978         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2979         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2980         check_spends!(node_a_commitment_tx[0], chan_1.3);
2981         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2982         check_closed_broadcast!(nodes[1], true);
2983         check_added_monitors!(nodes[1], 1);
2984         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2985         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2986         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2987         let commitment_spend =
2988                 if node_txn.len() == 1 {
2989                         &node_txn[0]
2990                 } else {
2991                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2992                         // FullBlockViaListen
2993                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2994                                 check_spends!(node_txn[1], commitment_tx[0]);
2995                                 check_spends!(node_txn[2], commitment_tx[0]);
2996                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2997                                 &node_txn[0]
2998                         } else {
2999                                 check_spends!(node_txn[0], commitment_tx[0]);
3000                                 check_spends!(node_txn[1], commitment_tx[0]);
3001                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
3002                                 &node_txn[2]
3003                         }
3004                 };
3005
3006         check_spends!(commitment_spend, node_a_commitment_tx[0]);
3007         assert_eq!(commitment_spend.input.len(), 2);
3008         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3009         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3010         assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3011         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3012         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3013         // we already checked the same situation with A.
3014
3015         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3016         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3017         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3018         check_closed_broadcast!(nodes[0], true);
3019         check_added_monitors!(nodes[0], 1);
3020         let events = nodes[0].node.get_and_clear_pending_events();
3021         assert_eq!(events.len(), 5);
3022         let mut first_claimed = false;
3023         for event in events {
3024                 match event {
3025                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3026                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3027                                         assert!(!first_claimed);
3028                                         first_claimed = true;
3029                                 } else {
3030                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3031                                         assert_eq!(payment_hash, payment_hash_2);
3032                                 }
3033                         },
3034                         Event::PaymentPathSuccessful { .. } => {},
3035                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3036                         _ => panic!("Unexpected event"),
3037                 }
3038         }
3039         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3040 }
3041
3042 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3043         // Test that in case of a unilateral close onchain, we detect the state of output and
3044         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3045         // broadcasting the right event to other nodes in payment path.
3046         // A ------------------> B ----------------------> C (timeout)
3047         //    B's commitment tx                 C's commitment tx
3048         //            \                                  \
3049         //         B's HTLC timeout tx               B's timeout tx
3050
3051         let chanmon_cfgs = create_chanmon_cfgs(3);
3052         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3053         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3054         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3055         *nodes[0].connect_style.borrow_mut() = connect_style;
3056         *nodes[1].connect_style.borrow_mut() = connect_style;
3057         *nodes[2].connect_style.borrow_mut() = connect_style;
3058
3059         // Create some intial channels
3060         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3061         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3062
3063         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3064         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3065         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3066
3067         let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3068
3069         // Broadcast legit commitment tx from C on B's chain
3070         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3071         check_spends!(commitment_tx[0], chan_2.3);
3072         nodes[2].node.fail_htlc_backwards(&payment_hash);
3073         check_added_monitors!(nodes[2], 0);
3074         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3075         check_added_monitors!(nodes[2], 1);
3076
3077         let events = nodes[2].node.get_and_clear_pending_msg_events();
3078         assert_eq!(events.len(), 1);
3079         match events[0] {
3080                 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, .. } } => {
3081                         assert!(update_add_htlcs.is_empty());
3082                         assert!(!update_fail_htlcs.is_empty());
3083                         assert!(update_fulfill_htlcs.is_empty());
3084                         assert!(update_fail_malformed_htlcs.is_empty());
3085                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3086                 },
3087                 _ => panic!("Unexpected event"),
3088         };
3089         mine_transaction(&nodes[2], &commitment_tx[0]);
3090         check_closed_broadcast!(nodes[2], true);
3091         check_added_monitors!(nodes[2], 1);
3092         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3093         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3094         assert_eq!(node_txn.len(), 0);
3095
3096         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3097         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3098         mine_transaction(&nodes[1], &commitment_tx[0]);
3099         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3100                 , [nodes[2].node.get_our_node_id()], 100000);
3101         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3102         let timeout_tx = {
3103                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3104                 if nodes[1].connect_style.borrow().skips_blocks() {
3105                         assert_eq!(txn.len(), 1);
3106                 } else {
3107                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3108                 }
3109                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3110                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3111                 txn.remove(0)
3112         };
3113
3114         mine_transaction(&nodes[1], &timeout_tx);
3115         check_added_monitors!(nodes[1], 1);
3116         check_closed_broadcast!(nodes[1], true);
3117
3118         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3119
3120         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 }]);
3121         check_added_monitors!(nodes[1], 1);
3122         let events = nodes[1].node.get_and_clear_pending_msg_events();
3123         assert_eq!(events.len(), 1);
3124         match events[0] {
3125                 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, .. } } => {
3126                         assert!(update_add_htlcs.is_empty());
3127                         assert!(!update_fail_htlcs.is_empty());
3128                         assert!(update_fulfill_htlcs.is_empty());
3129                         assert!(update_fail_malformed_htlcs.is_empty());
3130                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3131                 },
3132                 _ => panic!("Unexpected event"),
3133         };
3134
3135         // Broadcast legit commitment tx from B on A's chain
3136         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3137         check_spends!(commitment_tx[0], chan_1.3);
3138
3139         mine_transaction(&nodes[0], &commitment_tx[0]);
3140         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3141
3142         check_closed_broadcast!(nodes[0], true);
3143         check_added_monitors!(nodes[0], 1);
3144         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3145         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3146         assert_eq!(node_txn.len(), 1);
3147         check_spends!(node_txn[0], commitment_tx[0]);
3148         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3149 }
3150
3151 #[test]
3152 fn test_htlc_on_chain_timeout() {
3153         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3154         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3155         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3156 }
3157
3158 #[test]
3159 fn test_simple_commitment_revoked_fail_backward() {
3160         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3161         // and fail backward accordingly.
3162
3163         let chanmon_cfgs = create_chanmon_cfgs(3);
3164         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3165         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3166         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3167
3168         // Create some initial channels
3169         create_announced_chan_between_nodes(&nodes, 0, 1);
3170         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3171
3172         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3173         // Get the will-be-revoked local txn from nodes[2]
3174         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3175         // Revoke the old state
3176         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3177
3178         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3179
3180         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3181         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3182         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3183         check_added_monitors!(nodes[1], 1);
3184         check_closed_broadcast!(nodes[1], true);
3185
3186         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 }]);
3187         check_added_monitors!(nodes[1], 1);
3188         let events = nodes[1].node.get_and_clear_pending_msg_events();
3189         assert_eq!(events.len(), 1);
3190         match events[0] {
3191                 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, .. } } => {
3192                         assert!(update_add_htlcs.is_empty());
3193                         assert_eq!(update_fail_htlcs.len(), 1);
3194                         assert!(update_fulfill_htlcs.is_empty());
3195                         assert!(update_fail_malformed_htlcs.is_empty());
3196                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3197
3198                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3199                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3200                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3201                 },
3202                 _ => panic!("Unexpected event"),
3203         }
3204 }
3205
3206 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3207         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3208         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3209         // commitment transaction anymore.
3210         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3211         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3212         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3213         // technically disallowed and we should probably handle it reasonably.
3214         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3215         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3216         // transactions:
3217         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3218         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3219         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3220         //   and once they revoke the previous commitment transaction (allowing us to send a new
3221         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3222         let chanmon_cfgs = create_chanmon_cfgs(3);
3223         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3224         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3225         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3226
3227         // Create some initial channels
3228         create_announced_chan_between_nodes(&nodes, 0, 1);
3229         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3230
3231         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3232         // Get the will-be-revoked local txn from nodes[2]
3233         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3234         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3235         // Revoke the old state
3236         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3237
3238         let value = if use_dust {
3239                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3240                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3241                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3242                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3243         } else { 3000000 };
3244
3245         let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3246         let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3247         let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3248
3249         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3250         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_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         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3260         // Drop the last RAA from 3 -> 2
3261
3262         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3263         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3264         check_added_monitors!(nodes[2], 1);
3265         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3266         assert!(updates.update_add_htlcs.is_empty());
3267         assert!(updates.update_fulfill_htlcs.is_empty());
3268         assert!(updates.update_fail_malformed_htlcs.is_empty());
3269         assert_eq!(updates.update_fail_htlcs.len(), 1);
3270         assert!(updates.update_fee.is_none());
3271         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3272         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3273         check_added_monitors!(nodes[1], 1);
3274         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3275         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3276         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3277         check_added_monitors!(nodes[2], 1);
3278
3279         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3280         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3281         check_added_monitors!(nodes[2], 1);
3282         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3283         assert!(updates.update_add_htlcs.is_empty());
3284         assert!(updates.update_fulfill_htlcs.is_empty());
3285         assert!(updates.update_fail_malformed_htlcs.is_empty());
3286         assert_eq!(updates.update_fail_htlcs.len(), 1);
3287         assert!(updates.update_fee.is_none());
3288         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3289         // At this point first_payment_hash has dropped out of the latest two commitment
3290         // transactions that nodes[1] is tracking...
3291         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3292         check_added_monitors!(nodes[1], 1);
3293         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3294         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3295         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3296         check_added_monitors!(nodes[2], 1);
3297
3298         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3299         // on nodes[2]'s RAA.
3300         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3301         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3302                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3303         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3304         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3305         check_added_monitors!(nodes[1], 0);
3306
3307         if deliver_bs_raa {
3308                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3309                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3310                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3311                 check_added_monitors!(nodes[1], 1);
3312                 let events = nodes[1].node.get_and_clear_pending_events();
3313                 assert_eq!(events.len(), 2);
3314                 match events[0] {
3315                         Event::HTLCHandlingFailed { .. } => { },
3316                         _ => panic!("Unexpected event"),
3317                 }
3318                 match events[1] {
3319                         Event::PendingHTLCsForwardable { .. } => { },
3320                         _ => panic!("Unexpected event"),
3321                 };
3322                 // Deliberately don't process the pending fail-back so they all fail back at once after
3323                 // block connection just like the !deliver_bs_raa case
3324         }
3325
3326         let mut failed_htlcs = new_hash_set();
3327         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3328
3329         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3330         check_added_monitors!(nodes[1], 1);
3331         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3332
3333         let events = nodes[1].node.get_and_clear_pending_events();
3334         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3335         assert!(events.iter().any(|ev| matches!(
3336                 ev,
3337                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. }
3338         )));
3339         assert!(events.iter().any(|ev| matches!(
3340                 ev,
3341                 Event::PaymentPathFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3342         )));
3343         assert!(events.iter().any(|ev| matches!(
3344                 ev,
3345                 Event::PaymentFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3346         )));
3347
3348         nodes[1].node.process_pending_htlc_forwards();
3349         check_added_monitors!(nodes[1], 1);
3350
3351         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3352         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3353
3354         if deliver_bs_raa {
3355                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3356                 match nodes_2_event {
3357                         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, .. } } => {
3358                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3359                                 assert_eq!(update_add_htlcs.len(), 1);
3360                                 assert!(update_fulfill_htlcs.is_empty());
3361                                 assert!(update_fail_htlcs.is_empty());
3362                                 assert!(update_fail_malformed_htlcs.is_empty());
3363                         },
3364                         _ => panic!("Unexpected event"),
3365                 }
3366         }
3367
3368         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3369         match nodes_2_event {
3370                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3371                         assert_eq!(channel_id, chan_2.2);
3372                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3373                 },
3374                 _ => panic!("Unexpected event"),
3375         }
3376
3377         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3378         match nodes_0_event {
3379                 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, .. } } => {
3380                         assert!(update_add_htlcs.is_empty());
3381                         assert_eq!(update_fail_htlcs.len(), 3);
3382                         assert!(update_fulfill_htlcs.is_empty());
3383                         assert!(update_fail_malformed_htlcs.is_empty());
3384                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3385
3386                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3387                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3388                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3389
3390                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3391
3392                         let events = nodes[0].node.get_and_clear_pending_events();
3393                         assert_eq!(events.len(), 6);
3394                         match events[0] {
3395                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3396                                         assert!(failed_htlcs.insert(payment_hash.0));
3397                                         // If we delivered B's RAA we got an unknown preimage error, not something
3398                                         // that we should update our routing table for.
3399                                         if !deliver_bs_raa {
3400                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3401                                         }
3402                                 },
3403                                 _ => panic!("Unexpected event"),
3404                         }
3405                         match events[1] {
3406                                 Event::PaymentFailed { ref payment_hash, .. } => {
3407                                         assert_eq!(*payment_hash, first_payment_hash);
3408                                 },
3409                                 _ => panic!("Unexpected event"),
3410                         }
3411                         match events[2] {
3412                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3413                                         assert!(failed_htlcs.insert(payment_hash.0));
3414                                 },
3415                                 _ => panic!("Unexpected event"),
3416                         }
3417                         match events[3] {
3418                                 Event::PaymentFailed { ref payment_hash, .. } => {
3419                                         assert_eq!(*payment_hash, second_payment_hash);
3420                                 },
3421                                 _ => panic!("Unexpected event"),
3422                         }
3423                         match events[4] {
3424                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3425                                         assert!(failed_htlcs.insert(payment_hash.0));
3426                                 },
3427                                 _ => panic!("Unexpected event"),
3428                         }
3429                         match events[5] {
3430                                 Event::PaymentFailed { ref payment_hash, .. } => {
3431                                         assert_eq!(*payment_hash, third_payment_hash);
3432                                 },
3433                                 _ => panic!("Unexpected event"),
3434                         }
3435                 },
3436                 _ => panic!("Unexpected event"),
3437         }
3438
3439         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3440         match events[0] {
3441                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3442                 _ => panic!("Unexpected event"),
3443         }
3444
3445         assert!(failed_htlcs.contains(&first_payment_hash.0));
3446         assert!(failed_htlcs.contains(&second_payment_hash.0));
3447         assert!(failed_htlcs.contains(&third_payment_hash.0));
3448 }
3449
3450 #[test]
3451 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3452         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3453         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3454         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3455         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3456 }
3457
3458 #[test]
3459 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3460         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3461         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3462         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3463         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3464 }
3465
3466 #[test]
3467 fn fail_backward_pending_htlc_upon_channel_failure() {
3468         let chanmon_cfgs = create_chanmon_cfgs(2);
3469         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3470         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3471         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3472         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3473
3474         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3475         {
3476                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3477                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3478                         PaymentId(payment_hash.0)).unwrap();
3479                 check_added_monitors!(nodes[0], 1);
3480
3481                 let payment_event = {
3482                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3483                         assert_eq!(events.len(), 1);
3484                         SendEvent::from_event(events.remove(0))
3485                 };
3486                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3487                 assert_eq!(payment_event.msgs.len(), 1);
3488         }
3489
3490         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3491         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3492         {
3493                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3494                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3495                 check_added_monitors!(nodes[0], 0);
3496
3497                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3498         }
3499
3500         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3501         {
3502                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3503
3504                 let secp_ctx = Secp256k1::new();
3505                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3506                 let current_height = nodes[1].node.best_block.read().unwrap().height + 1;
3507                 let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
3508                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3509                         &route.paths[0], 50_000, &recipient_onion_fields, current_height, &None).unwrap();
3510                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3511                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3512
3513                 // Send a 0-msat update_add_htlc to fail the channel.
3514                 let update_add_htlc = msgs::UpdateAddHTLC {
3515                         channel_id: chan.2,
3516                         htlc_id: 0,
3517                         amount_msat: 0,
3518                         payment_hash,
3519                         cltv_expiry,
3520                         onion_routing_packet,
3521                         skimmed_fee_msat: None,
3522                         blinding_point: None,
3523                 };
3524                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3525         }
3526         let events = nodes[0].node.get_and_clear_pending_events();
3527         assert_eq!(events.len(), 3);
3528         // Check that Alice fails backward the pending HTLC from the second payment.
3529         match events[0] {
3530                 Event::PaymentPathFailed { payment_hash, .. } => {
3531                         assert_eq!(payment_hash, failed_payment_hash);
3532                 },
3533                 _ => panic!("Unexpected event"),
3534         }
3535         match events[1] {
3536                 Event::PaymentFailed { payment_hash, .. } => {
3537                         assert_eq!(payment_hash, failed_payment_hash);
3538                 },
3539                 _ => panic!("Unexpected event"),
3540         }
3541         match events[2] {
3542                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3543                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3544                 },
3545                 _ => panic!("Unexpected event {:?}", events[1]),
3546         }
3547         check_closed_broadcast!(nodes[0], true);
3548         check_added_monitors!(nodes[0], 1);
3549 }
3550
3551 #[test]
3552 fn test_htlc_ignore_latest_remote_commitment() {
3553         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3554         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3555         let chanmon_cfgs = create_chanmon_cfgs(2);
3556         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3557         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3558         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3559         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3560                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3561                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3562                 // connect_style.
3563                 return;
3564         }
3565         let funding_tx = create_announced_chan_between_nodes(&nodes, 0, 1).3;
3566
3567         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3568         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3569         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3570         check_closed_broadcast!(nodes[0], true);
3571         check_added_monitors!(nodes[0], 1);
3572         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3573
3574         let node_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
3575         assert_eq!(node_txn.len(), 2);
3576         check_spends!(node_txn[0], funding_tx);
3577         check_spends!(node_txn[1], node_txn[0]);
3578
3579         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone()]);
3580         connect_block(&nodes[1], &block);
3581         check_closed_broadcast!(nodes[1], true);
3582         check_added_monitors!(nodes[1], 1);
3583         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3584
3585         // Duplicate the connect_block call since this may happen due to other listeners
3586         // registering new transactions
3587         connect_block(&nodes[1], &block);
3588 }
3589
3590 #[test]
3591 fn test_force_close_fail_back() {
3592         // Check which HTLCs are failed-backwards on channel force-closure
3593         let chanmon_cfgs = create_chanmon_cfgs(3);
3594         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3595         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3596         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3597         create_announced_chan_between_nodes(&nodes, 0, 1);
3598         create_announced_chan_between_nodes(&nodes, 1, 2);
3599
3600         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3601
3602         let mut payment_event = {
3603                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3604                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3605                 check_added_monitors!(nodes[0], 1);
3606
3607                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3608                 assert_eq!(events.len(), 1);
3609                 SendEvent::from_event(events.remove(0))
3610         };
3611
3612         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3613         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3614
3615         expect_pending_htlcs_forwardable!(nodes[1]);
3616
3617         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3618         assert_eq!(events_2.len(), 1);
3619         payment_event = SendEvent::from_event(events_2.remove(0));
3620         assert_eq!(payment_event.msgs.len(), 1);
3621
3622         check_added_monitors!(nodes[1], 1);
3623         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3624         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3625         check_added_monitors!(nodes[2], 1);
3626         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3627
3628         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3629         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3630         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3631
3632         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3633         check_closed_broadcast!(nodes[2], true);
3634         check_added_monitors!(nodes[2], 1);
3635         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3636         let commitment_tx = {
3637                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3638                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3639                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3640                 // back to nodes[1] upon timeout otherwise.
3641                 assert_eq!(node_txn.len(), 1);
3642                 node_txn.remove(0)
3643         };
3644
3645         mine_transaction(&nodes[1], &commitment_tx);
3646
3647         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3648         check_closed_broadcast!(nodes[1], true);
3649         check_added_monitors!(nodes[1], 1);
3650         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3651
3652         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3653         {
3654                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3655                         .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);
3656         }
3657         mine_transaction(&nodes[2], &commitment_tx);
3658         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcast();
3659         assert_eq!(node_txn.len(), if nodes[2].connect_style.borrow().updates_best_block_first() { 2 } else { 1 });
3660         let htlc_tx = node_txn.pop().unwrap();
3661         assert_eq!(htlc_tx.input.len(), 1);
3662         assert_eq!(htlc_tx.input[0].previous_output.txid, commitment_tx.txid());
3663         assert_eq!(htlc_tx.lock_time, LockTime::ZERO); // Must be an HTLC-Success
3664         assert_eq!(htlc_tx.input[0].witness.len(), 5); // Must be an HTLC-Success
3665
3666         check_spends!(htlc_tx, commitment_tx);
3667 }
3668
3669 #[test]
3670 fn test_dup_events_on_peer_disconnect() {
3671         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3672         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3673         // as we used to generate the event immediately upon receipt of the payment preimage in the
3674         // update_fulfill_htlc message.
3675
3676         let chanmon_cfgs = create_chanmon_cfgs(2);
3677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3679         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3680         create_announced_chan_between_nodes(&nodes, 0, 1);
3681
3682         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3683
3684         nodes[1].node.claim_funds(payment_preimage);
3685         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3686         check_added_monitors!(nodes[1], 1);
3687         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3688         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3689         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3690
3691         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3692         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3693
3694         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3695         reconnect_args.pending_htlc_claims.0 = 1;
3696         reconnect_nodes(reconnect_args);
3697         expect_payment_path_successful!(nodes[0]);
3698 }
3699
3700 #[test]
3701 fn test_peer_disconnected_before_funding_broadcasted() {
3702         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3703         // before the funding transaction has been broadcasted, and doesn't reconnect back within time.
3704         let chanmon_cfgs = create_chanmon_cfgs(2);
3705         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3706         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3707         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3708
3709         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3710         // broadcasted, even though it's created by `nodes[0]`.
3711         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();
3712         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3713         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3714         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3715         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3716
3717         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3718         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3719
3720         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3721
3722         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3723         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3724
3725         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3726         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3727         // broadcasted.
3728         {
3729                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3730         }
3731
3732         // The peers disconnect before the funding is broadcasted.
3733         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3734         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3735
3736         // The time for peers to reconnect expires.
3737         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
3738                 nodes[0].node.timer_tick_occurred();
3739         }
3740
3741         // Ensure that the channel is closed with `ClosureReason::HolderForceClosed`
3742         // when the peers are disconnected and do not reconnect before the funding
3743         // transaction is broadcasted.
3744         check_closed_event!(&nodes[0], 2, ClosureReason::HolderForceClosed, true
3745                 , [nodes[1].node.get_our_node_id()], 1000000);
3746         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3747                 , [nodes[0].node.get_our_node_id()], 1000000);
3748 }
3749
3750 #[test]
3751 fn test_simple_peer_disconnect() {
3752         // Test that we can reconnect when there are no lost messages
3753         let chanmon_cfgs = create_chanmon_cfgs(3);
3754         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3755         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3756         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3757         create_announced_chan_between_nodes(&nodes, 0, 1);
3758         create_announced_chan_between_nodes(&nodes, 1, 2);
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         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3763         reconnect_args.send_channel_ready = (true, true);
3764         reconnect_nodes(reconnect_args);
3765
3766         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3767         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3768         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3769         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3770
3771         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3772         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3773         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3774
3775         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3776         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3777         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3778         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3779
3780         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3781         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3782
3783         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3784         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3785
3786         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3787         reconnect_args.pending_cell_htlc_fails.0 = 1;
3788         reconnect_args.pending_cell_htlc_claims.0 = 1;
3789         reconnect_nodes(reconnect_args);
3790         {
3791                 let events = nodes[0].node.get_and_clear_pending_events();
3792                 assert_eq!(events.len(), 4);
3793                 match events[0] {
3794                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3795                                 assert_eq!(payment_preimage, payment_preimage_3);
3796                                 assert_eq!(payment_hash, payment_hash_3);
3797                         },
3798                         _ => panic!("Unexpected event"),
3799                 }
3800                 match events[1] {
3801                         Event::PaymentPathSuccessful { .. } => {},
3802                         _ => panic!("Unexpected event"),
3803                 }
3804                 match events[2] {
3805                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3806                                 assert_eq!(payment_hash, payment_hash_5);
3807                                 assert!(payment_failed_permanently);
3808                         },
3809                         _ => panic!("Unexpected event"),
3810                 }
3811                 match events[3] {
3812                         Event::PaymentFailed { payment_hash, .. } => {
3813                                 assert_eq!(payment_hash, payment_hash_5);
3814                         },
3815                         _ => panic!("Unexpected event"),
3816                 }
3817         }
3818         check_added_monitors(&nodes[0], 1);
3819
3820         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3821         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3822 }
3823
3824 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3825         // Test that we can reconnect when in-flight HTLC updates get dropped
3826         let chanmon_cfgs = create_chanmon_cfgs(2);
3827         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3828         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3829         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3830
3831         let mut as_channel_ready = None;
3832         let channel_id = if messages_delivered == 0 {
3833                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3834                 as_channel_ready = Some(channel_ready);
3835                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3836                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3837                 // it before the channel_reestablish message.
3838                 chan_id
3839         } else {
3840                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3841         };
3842
3843         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3844
3845         let payment_event = {
3846                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3847                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3848                 check_added_monitors!(nodes[0], 1);
3849
3850                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3851                 assert_eq!(events.len(), 1);
3852                 SendEvent::from_event(events.remove(0))
3853         };
3854         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3855
3856         if messages_delivered < 2 {
3857                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3858         } else {
3859                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3860                 if messages_delivered >= 3 {
3861                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3862                         check_added_monitors!(nodes[1], 1);
3863                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3864
3865                         if messages_delivered >= 4 {
3866                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3867                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3868                                 check_added_monitors!(nodes[0], 1);
3869
3870                                 if messages_delivered >= 5 {
3871                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3872                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3873                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3874                                         check_added_monitors!(nodes[0], 1);
3875
3876                                         if messages_delivered >= 6 {
3877                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3878                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3879                                                 check_added_monitors!(nodes[1], 1);
3880                                         }
3881                                 }
3882                         }
3883                 }
3884         }
3885
3886         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3887         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3888         if messages_delivered < 3 {
3889                 if simulate_broken_lnd {
3890                         // lnd has a long-standing bug where they send a channel_ready prior to a
3891                         // channel_reestablish if you reconnect prior to channel_ready time.
3892                         //
3893                         // Here we simulate that behavior, delivering a channel_ready immediately on
3894                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3895                         // in `reconnect_nodes` but we currently don't fail based on that.
3896                         //
3897                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3898                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3899                 }
3900                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3901                 // received on either side, both sides will need to resend them.
3902                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3903                 reconnect_args.send_channel_ready = (true, true);
3904                 reconnect_args.pending_htlc_adds.1 = 1;
3905                 reconnect_nodes(reconnect_args);
3906         } else if messages_delivered == 3 {
3907                 // nodes[0] still wants its RAA + commitment_signed
3908                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3909                 reconnect_args.pending_responding_commitment_signed.0 = true;
3910                 reconnect_args.pending_raa.0 = true;
3911                 reconnect_nodes(reconnect_args);
3912         } else if messages_delivered == 4 {
3913                 // nodes[0] still wants its commitment_signed
3914                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3915                 reconnect_args.pending_responding_commitment_signed.0 = true;
3916                 reconnect_nodes(reconnect_args);
3917         } else if messages_delivered == 5 {
3918                 // nodes[1] still wants its final RAA
3919                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3920                 reconnect_args.pending_raa.1 = true;
3921                 reconnect_nodes(reconnect_args);
3922         } else if messages_delivered == 6 {
3923                 // Everything was delivered...
3924                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3925         }
3926
3927         let events_1 = nodes[1].node.get_and_clear_pending_events();
3928         if messages_delivered == 0 {
3929                 assert_eq!(events_1.len(), 2);
3930                 match events_1[0] {
3931                         Event::ChannelReady { .. } => { },
3932                         _ => panic!("Unexpected event"),
3933                 };
3934                 match events_1[1] {
3935                         Event::PendingHTLCsForwardable { .. } => { },
3936                         _ => panic!("Unexpected event"),
3937                 };
3938         } else {
3939                 assert_eq!(events_1.len(), 1);
3940                 match events_1[0] {
3941                         Event::PendingHTLCsForwardable { .. } => { },
3942                         _ => panic!("Unexpected event"),
3943                 };
3944         }
3945
3946         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3947         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3948         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3949
3950         nodes[1].node.process_pending_htlc_forwards();
3951
3952         let events_2 = nodes[1].node.get_and_clear_pending_events();
3953         assert_eq!(events_2.len(), 1);
3954         match events_2[0] {
3955                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3956                         assert_eq!(payment_hash_1, *payment_hash);
3957                         assert_eq!(amount_msat, 1_000_000);
3958                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3959                         assert_eq!(via_channel_id, Some(channel_id));
3960                         match &purpose {
3961                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
3962                                         assert!(payment_preimage.is_none());
3963                                         assert_eq!(payment_secret_1, *payment_secret);
3964                                 },
3965                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
3966                         }
3967                 },
3968                 _ => panic!("Unexpected event"),
3969         }
3970
3971         nodes[1].node.claim_funds(payment_preimage_1);
3972         check_added_monitors!(nodes[1], 1);
3973         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3974
3975         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3976         assert_eq!(events_3.len(), 1);
3977         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3978                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3979                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3980                         assert!(updates.update_add_htlcs.is_empty());
3981                         assert!(updates.update_fail_htlcs.is_empty());
3982                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3983                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3984                         assert!(updates.update_fee.is_none());
3985                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3986                 },
3987                 _ => panic!("Unexpected event"),
3988         };
3989
3990         if messages_delivered >= 1 {
3991                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3992
3993                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3994                 assert_eq!(events_4.len(), 1);
3995                 match events_4[0] {
3996                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3997                                 assert_eq!(payment_preimage_1, *payment_preimage);
3998                                 assert_eq!(payment_hash_1, *payment_hash);
3999                         },
4000                         _ => panic!("Unexpected event"),
4001                 }
4002
4003                 if messages_delivered >= 2 {
4004                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
4005                         check_added_monitors!(nodes[0], 1);
4006                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4007
4008                         if messages_delivered >= 3 {
4009                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4010                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4011                                 check_added_monitors!(nodes[1], 1);
4012
4013                                 if messages_delivered >= 4 {
4014                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4015                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4016                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4017                                         check_added_monitors!(nodes[1], 1);
4018
4019                                         if messages_delivered >= 5 {
4020                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4021                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4022                                                 check_added_monitors!(nodes[0], 1);
4023                                         }
4024                                 }
4025                         }
4026                 }
4027         }
4028
4029         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4030         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4031         if messages_delivered < 2 {
4032                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4033                 reconnect_args.pending_htlc_claims.0 = 1;
4034                 reconnect_nodes(reconnect_args);
4035                 if messages_delivered < 1 {
4036                         expect_payment_sent!(nodes[0], payment_preimage_1);
4037                 } else {
4038                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4039                 }
4040         } else if messages_delivered == 2 {
4041                 // nodes[0] still wants its RAA + commitment_signed
4042                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4043                 reconnect_args.pending_responding_commitment_signed.1 = true;
4044                 reconnect_args.pending_raa.1 = true;
4045                 reconnect_nodes(reconnect_args);
4046         } else if messages_delivered == 3 {
4047                 // nodes[0] still wants its commitment_signed
4048                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4049                 reconnect_args.pending_responding_commitment_signed.1 = true;
4050                 reconnect_nodes(reconnect_args);
4051         } else if messages_delivered == 4 {
4052                 // nodes[1] still wants its final RAA
4053                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4054                 reconnect_args.pending_raa.0 = true;
4055                 reconnect_nodes(reconnect_args);
4056         } else if messages_delivered == 5 {
4057                 // Everything was delivered...
4058                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4059         }
4060
4061         if messages_delivered == 1 || messages_delivered == 2 {
4062                 expect_payment_path_successful!(nodes[0]);
4063         }
4064         if messages_delivered <= 5 {
4065                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4066                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4067         }
4068         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4069
4070         if messages_delivered > 2 {
4071                 expect_payment_path_successful!(nodes[0]);
4072         }
4073
4074         // Channel should still work fine...
4075         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4076         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4077         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4078 }
4079
4080 #[test]
4081 fn test_drop_messages_peer_disconnect_a() {
4082         do_test_drop_messages_peer_disconnect(0, true);
4083         do_test_drop_messages_peer_disconnect(0, false);
4084         do_test_drop_messages_peer_disconnect(1, false);
4085         do_test_drop_messages_peer_disconnect(2, false);
4086 }
4087
4088 #[test]
4089 fn test_drop_messages_peer_disconnect_b() {
4090         do_test_drop_messages_peer_disconnect(3, false);
4091         do_test_drop_messages_peer_disconnect(4, false);
4092         do_test_drop_messages_peer_disconnect(5, false);
4093         do_test_drop_messages_peer_disconnect(6, false);
4094 }
4095
4096 #[test]
4097 fn test_channel_ready_without_best_block_updated() {
4098         // Previously, if we were offline when a funding transaction was locked in, and then we came
4099         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4100         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4101         // channel_ready immediately instead.
4102         let chanmon_cfgs = create_chanmon_cfgs(2);
4103         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4104         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4105         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4106         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4107
4108         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4109
4110         let conf_height = nodes[0].best_block_info().1 + 1;
4111         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4112         let block_txn = [funding_tx];
4113         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4114         let conf_block_header = nodes[0].get_block_header(conf_height);
4115         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4116
4117         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4118         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4119         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4120 }
4121
4122 #[test]
4123 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4124         let chanmon_cfgs = create_chanmon_cfgs(2);
4125         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4126         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4127         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4128
4129         // Let channel_manager get ahead of chain_monitor by 1 block.
4130         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4131         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4132         let height_1 = nodes[0].best_block_info().1 + 1;
4133         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4134
4135         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4136         nodes[0].node.block_connected(&block_1, height_1);
4137
4138         // Create channel, and it gets added to chain_monitor in funding_created.
4139         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4140
4141         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4142         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4143         // was running ahead of chain_monitor at the time of funding_created.
4144         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4145         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4146         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4147         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4148
4149         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4150         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4151         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4152 }
4153
4154 #[test]
4155 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4156         let chanmon_cfgs = create_chanmon_cfgs(2);
4157         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4158         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4159         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4160
4161         // Let chain_monitor get ahead of channel_manager by 1 block.
4162         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4163         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4164         let height_1 = nodes[0].best_block_info().1 + 1;
4165         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4166
4167         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4168         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4169
4170         // Create channel, and it gets added to chain_monitor in funding_created.
4171         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4172
4173         // channel_manager can't really skip block_1, it should get it eventually.
4174         nodes[0].node.block_connected(&block_1, height_1);
4175
4176         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4177         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4178         // running behind at the time of funding_created.
4179         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4180         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4181         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4182         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4183
4184         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4185         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4186         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4187 }
4188
4189 #[test]
4190 fn test_drop_messages_peer_disconnect_dual_htlc() {
4191         // Test that we can handle reconnecting when both sides of a channel have pending
4192         // commitment_updates when we disconnect.
4193         let chanmon_cfgs = create_chanmon_cfgs(2);
4194         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4195         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4196         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4197         create_announced_chan_between_nodes(&nodes, 0, 1);
4198
4199         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4200
4201         // Now try to send a second payment which will fail to send
4202         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4203         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4204                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4205         check_added_monitors!(nodes[0], 1);
4206
4207         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4208         assert_eq!(events_1.len(), 1);
4209         match events_1[0] {
4210                 MessageSendEvent::UpdateHTLCs { .. } => {},
4211                 _ => panic!("Unexpected event"),
4212         }
4213
4214         nodes[1].node.claim_funds(payment_preimage_1);
4215         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4216         check_added_monitors!(nodes[1], 1);
4217
4218         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4219         assert_eq!(events_2.len(), 1);
4220         match events_2[0] {
4221                 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 } } => {
4222                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4223                         assert!(update_add_htlcs.is_empty());
4224                         assert_eq!(update_fulfill_htlcs.len(), 1);
4225                         assert!(update_fail_htlcs.is_empty());
4226                         assert!(update_fail_malformed_htlcs.is_empty());
4227                         assert!(update_fee.is_none());
4228
4229                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4230                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4231                         assert_eq!(events_3.len(), 1);
4232                         match events_3[0] {
4233                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4234                                         assert_eq!(*payment_preimage, payment_preimage_1);
4235                                         assert_eq!(*payment_hash, payment_hash_1);
4236                                 },
4237                                 _ => panic!("Unexpected event"),
4238                         }
4239
4240                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4241                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4242                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4243                         check_added_monitors!(nodes[0], 1);
4244                 },
4245                 _ => panic!("Unexpected event"),
4246         }
4247
4248         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4249         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4250
4251         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4252                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4253         }, true).unwrap();
4254         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4255         assert_eq!(reestablish_1.len(), 1);
4256         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4257                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4258         }, false).unwrap();
4259         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4260         assert_eq!(reestablish_2.len(), 1);
4261
4262         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4263         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4264         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4265         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4266
4267         assert!(as_resp.0.is_none());
4268         assert!(bs_resp.0.is_none());
4269
4270         assert!(bs_resp.1.is_none());
4271         assert!(bs_resp.2.is_none());
4272
4273         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4274
4275         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4276         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4277         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4278         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4279         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4280         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4281         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4282         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4283         // No commitment_signed so get_event_msg's assert(len == 1) passes
4284         check_added_monitors!(nodes[1], 1);
4285
4286         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4287         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4288         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4289         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4290         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4291         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4292         assert!(bs_second_commitment_signed.update_fee.is_none());
4293         check_added_monitors!(nodes[1], 1);
4294
4295         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4296         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4297         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4298         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4299         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4300         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4301         assert!(as_commitment_signed.update_fee.is_none());
4302         check_added_monitors!(nodes[0], 1);
4303
4304         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4305         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4306         // No commitment_signed so get_event_msg's assert(len == 1) passes
4307         check_added_monitors!(nodes[0], 1);
4308
4309         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4310         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4311         // No commitment_signed so get_event_msg's assert(len == 1) passes
4312         check_added_monitors!(nodes[1], 1);
4313
4314         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4315         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4316         check_added_monitors!(nodes[1], 1);
4317
4318         expect_pending_htlcs_forwardable!(nodes[1]);
4319
4320         let events_5 = nodes[1].node.get_and_clear_pending_events();
4321         assert_eq!(events_5.len(), 1);
4322         match events_5[0] {
4323                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4324                         assert_eq!(payment_hash_2, *payment_hash);
4325                         match &purpose {
4326                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
4327                                         assert!(payment_preimage.is_none());
4328                                         assert_eq!(payment_secret_2, *payment_secret);
4329                                 },
4330                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
4331                         }
4332                 },
4333                 _ => panic!("Unexpected event"),
4334         }
4335
4336         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4337         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4338         check_added_monitors!(nodes[0], 1);
4339
4340         expect_payment_path_successful!(nodes[0]);
4341         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4342 }
4343
4344 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4345         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4346         // to avoid our counterparty failing the channel.
4347         let chanmon_cfgs = create_chanmon_cfgs(2);
4348         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4349         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4350         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4351
4352         create_announced_chan_between_nodes(&nodes, 0, 1);
4353
4354         let our_payment_hash = if send_partial_mpp {
4355                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4356                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4357                 // indicates there are more HTLCs coming.
4358                 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.
4359                 let payment_id = PaymentId([42; 32]);
4360                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4361                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4362                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4363                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4364                         &None, session_privs[0]).unwrap();
4365                 check_added_monitors!(nodes[0], 1);
4366                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4367                 assert_eq!(events.len(), 1);
4368                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4369                 // hop should *not* yet generate any PaymentClaimable event(s).
4370                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4371                 our_payment_hash
4372         } else {
4373                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4374         };
4375
4376         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4377         connect_block(&nodes[0], &block);
4378         connect_block(&nodes[1], &block);
4379         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4380         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4381                 block.header.prev_blockhash = block.block_hash();
4382                 connect_block(&nodes[0], &block);
4383                 connect_block(&nodes[1], &block);
4384         }
4385
4386         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4387
4388         check_added_monitors!(nodes[1], 1);
4389         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4390         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4391         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4392         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4393         assert!(htlc_timeout_updates.update_fee.is_none());
4394
4395         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4396         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4397         // 100_000 msat as u64, followed by the height at which we failed back above
4398         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4399         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4400         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4401 }
4402
4403 #[test]
4404 fn test_htlc_timeout() {
4405         do_test_htlc_timeout(true);
4406         do_test_htlc_timeout(false);
4407 }
4408
4409 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4410         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4411         let chanmon_cfgs = create_chanmon_cfgs(3);
4412         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4413         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4414         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4415         create_announced_chan_between_nodes(&nodes, 0, 1);
4416         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4417
4418         // Make sure all nodes are at the same starting height
4419         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4420         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4421         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4422
4423         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4424         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4425         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4426                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4427         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4428         check_added_monitors!(nodes[1], 1);
4429
4430         // Now attempt to route a second payment, which should be placed in the holding cell
4431         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4432         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4433         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4434                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4435         if forwarded_htlc {
4436                 check_added_monitors!(nodes[0], 1);
4437                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4438                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4439                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4440                 expect_pending_htlcs_forwardable!(nodes[1]);
4441         }
4442         check_added_monitors!(nodes[1], 0);
4443
4444         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4445         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4446         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4447         connect_blocks(&nodes[1], 1);
4448
4449         if forwarded_htlc {
4450                 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 }]);
4451                 check_added_monitors!(nodes[1], 1);
4452                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4453                 assert_eq!(fail_commit.len(), 1);
4454                 match fail_commit[0] {
4455                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4456                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4457                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4458                         },
4459                         _ => unreachable!(),
4460                 }
4461                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4462         } else {
4463                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4464         }
4465 }
4466
4467 #[test]
4468 fn test_holding_cell_htlc_add_timeouts() {
4469         do_test_holding_cell_htlc_add_timeouts(false);
4470         do_test_holding_cell_htlc_add_timeouts(true);
4471 }
4472
4473 macro_rules! check_spendable_outputs {
4474         ($node: expr, $keysinterface: expr) => {
4475                 {
4476                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4477                         let mut txn = Vec::new();
4478                         let mut all_outputs = Vec::new();
4479                         let secp_ctx = Secp256k1::new();
4480                         for event in events.drain(..) {
4481                                 match event {
4482                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4483                                                 for outp in outputs.drain(..) {
4484                                                         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());
4485                                                         all_outputs.push(outp);
4486                                                 }
4487                                         },
4488                                         _ => panic!("Unexpected event"),
4489                                 };
4490                         }
4491                         if all_outputs.len() > 1 {
4492                                 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) {
4493                                         txn.push(tx);
4494                                 }
4495                         }
4496                         txn
4497                 }
4498         }
4499 }
4500
4501 #[test]
4502 fn test_claim_sizeable_push_msat() {
4503         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4504         let chanmon_cfgs = create_chanmon_cfgs(2);
4505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4507         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4508
4509         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4510         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4511         check_closed_broadcast!(nodes[1], true);
4512         check_added_monitors!(nodes[1], 1);
4513         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4514         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4515         assert_eq!(node_txn.len(), 1);
4516         check_spends!(node_txn[0], chan.3);
4517         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
4518
4519         mine_transaction(&nodes[1], &node_txn[0]);
4520         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4521
4522         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4523         assert_eq!(spend_txn.len(), 1);
4524         assert_eq!(spend_txn[0].input.len(), 1);
4525         check_spends!(spend_txn[0], node_txn[0]);
4526         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4527 }
4528
4529 #[test]
4530 fn test_claim_on_remote_sizeable_push_msat() {
4531         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4532         // to_remote output is encumbered by a P2WPKH
4533         let chanmon_cfgs = create_chanmon_cfgs(2);
4534         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4535         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4536         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4537
4538         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4539         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4540         check_closed_broadcast!(nodes[0], true);
4541         check_added_monitors!(nodes[0], 1);
4542         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4543
4544         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4545         assert_eq!(node_txn.len(), 1);
4546         check_spends!(node_txn[0], chan.3);
4547         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
4548
4549         mine_transaction(&nodes[1], &node_txn[0]);
4550         check_closed_broadcast!(nodes[1], true);
4551         check_added_monitors!(nodes[1], 1);
4552         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4553         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4554
4555         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4556         assert_eq!(spend_txn.len(), 1);
4557         check_spends!(spend_txn[0], node_txn[0]);
4558 }
4559
4560 #[test]
4561 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4562         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4563         // to_remote output is encumbered by a P2WPKH
4564
4565         let chanmon_cfgs = create_chanmon_cfgs(2);
4566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4568         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4569
4570         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4571         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4572         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4573         assert_eq!(revoked_local_txn[0].input.len(), 1);
4574         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4575
4576         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4577         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4578         check_closed_broadcast!(nodes[1], true);
4579         check_added_monitors!(nodes[1], 1);
4580         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4581
4582         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4583         mine_transaction(&nodes[1], &node_txn[0]);
4584         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4585
4586         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4587         assert_eq!(spend_txn.len(), 3);
4588         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4589         check_spends!(spend_txn[1], node_txn[0]);
4590         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4591 }
4592
4593 #[test]
4594 fn test_static_spendable_outputs_preimage_tx() {
4595         let chanmon_cfgs = create_chanmon_cfgs(2);
4596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4598         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4599
4600         // Create some initial channels
4601         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4602
4603         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4604
4605         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4606         assert_eq!(commitment_tx[0].input.len(), 1);
4607         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4608
4609         // Settle A's commitment tx on B's chain
4610         nodes[1].node.claim_funds(payment_preimage);
4611         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4612         check_added_monitors!(nodes[1], 1);
4613         mine_transaction(&nodes[1], &commitment_tx[0]);
4614         check_added_monitors!(nodes[1], 1);
4615         let events = nodes[1].node.get_and_clear_pending_msg_events();
4616         match events[0] {
4617                 MessageSendEvent::UpdateHTLCs { .. } => {},
4618                 _ => panic!("Unexpected event"),
4619         }
4620         match events[2] {
4621                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4622                 _ => panic!("Unexepected event"),
4623         }
4624
4625         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4626         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4627         assert_eq!(node_txn.len(), 1);
4628         check_spends!(node_txn[0], commitment_tx[0]);
4629         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4630
4631         mine_transaction(&nodes[1], &node_txn[0]);
4632         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4633         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4634
4635         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4636         assert_eq!(spend_txn.len(), 1);
4637         check_spends!(spend_txn[0], node_txn[0]);
4638 }
4639
4640 #[test]
4641 fn test_static_spendable_outputs_timeout_tx() {
4642         let chanmon_cfgs = create_chanmon_cfgs(2);
4643         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4644         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4645         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4646
4647         // Create some initial channels
4648         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4649
4650         // Rebalance the network a bit by relaying one payment through all the channels ...
4651         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4652
4653         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4654
4655         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4656         assert_eq!(commitment_tx[0].input.len(), 1);
4657         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4658
4659         // Settle A's commitment tx on B' chain
4660         mine_transaction(&nodes[1], &commitment_tx[0]);
4661         check_added_monitors!(nodes[1], 1);
4662         let events = nodes[1].node.get_and_clear_pending_msg_events();
4663         match events[1] {
4664                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4665                 _ => panic!("Unexpected event"),
4666         }
4667         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4668
4669         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4670         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4671         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4672         check_spends!(node_txn[0],  commitment_tx[0].clone());
4673         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4674
4675         mine_transaction(&nodes[1], &node_txn[0]);
4676         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4677         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4678         expect_payment_failed!(nodes[1], our_payment_hash, false);
4679
4680         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4681         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4682         check_spends!(spend_txn[0], commitment_tx[0]);
4683         check_spends!(spend_txn[1], node_txn[0]);
4684         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4685 }
4686
4687 #[test]
4688 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4689         let chanmon_cfgs = create_chanmon_cfgs(2);
4690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4692         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4693
4694         // Create some initial channels
4695         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4696
4697         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4698         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4699         assert_eq!(revoked_local_txn[0].input.len(), 1);
4700         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4701
4702         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4703
4704         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4705         check_closed_broadcast!(nodes[1], true);
4706         check_added_monitors!(nodes[1], 1);
4707         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4708
4709         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4710         assert_eq!(node_txn.len(), 1);
4711         assert_eq!(node_txn[0].input.len(), 2);
4712         check_spends!(node_txn[0], revoked_local_txn[0]);
4713
4714         mine_transaction(&nodes[1], &node_txn[0]);
4715         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4716
4717         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4718         assert_eq!(spend_txn.len(), 1);
4719         check_spends!(spend_txn[0], node_txn[0]);
4720 }
4721
4722 #[test]
4723 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4724         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4725         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4726         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4727         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4728         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4729
4730         // Create some initial channels
4731         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4732
4733         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4734         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4735         assert_eq!(revoked_local_txn[0].input.len(), 1);
4736         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4737
4738         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4739
4740         // A will generate HTLC-Timeout from revoked commitment tx
4741         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4742         check_closed_broadcast!(nodes[0], true);
4743         check_added_monitors!(nodes[0], 1);
4744         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4745         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4746
4747         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4748         assert_eq!(revoked_htlc_txn.len(), 1);
4749         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4750         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4751         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4752         assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4753
4754         // B will generate justice tx from A's revoked commitment/HTLC tx
4755         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4756         check_closed_broadcast!(nodes[1], true);
4757         check_added_monitors!(nodes[1], 1);
4758         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4759
4760         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4761         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4762         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4763         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4764         // transactions next...
4765         assert_eq!(node_txn[0].input.len(), 3);
4766         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4767
4768         assert_eq!(node_txn[1].input.len(), 2);
4769         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4770         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4771                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4772         } else {
4773                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4774                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4775         }
4776
4777         mine_transaction(&nodes[1], &node_txn[1]);
4778         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4779
4780         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4781         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4782         assert_eq!(spend_txn.len(), 1);
4783         assert_eq!(spend_txn[0].input.len(), 1);
4784         check_spends!(spend_txn[0], node_txn[1]);
4785 }
4786
4787 #[test]
4788 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4789         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4790         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4794
4795         // Create some initial channels
4796         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4797
4798         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4799         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4800         assert_eq!(revoked_local_txn[0].input.len(), 1);
4801         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4802
4803         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4804         assert_eq!(revoked_local_txn[0].output.len(), 2);
4805
4806         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4807
4808         // B will generate HTLC-Success from revoked commitment tx
4809         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4810         check_closed_broadcast!(nodes[1], true);
4811         check_added_monitors!(nodes[1], 1);
4812         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4813         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4814
4815         assert_eq!(revoked_htlc_txn.len(), 1);
4816         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4817         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4818         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4819
4820         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4821         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4822         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4823
4824         // A will generate justice tx from B's revoked commitment/HTLC tx
4825         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4826         check_closed_broadcast!(nodes[0], true);
4827         check_added_monitors!(nodes[0], 1);
4828         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4829
4830         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4831         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4832
4833         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4834         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4835         // transactions next...
4836         assert_eq!(node_txn[0].input.len(), 2);
4837         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4838         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4839                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4840         } else {
4841                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4842                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4843         }
4844
4845         assert_eq!(node_txn[1].input.len(), 1);
4846         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4847
4848         mine_transaction(&nodes[0], &node_txn[1]);
4849         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4850
4851         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4852         // didn't try to generate any new transactions.
4853
4854         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4855         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4856         assert_eq!(spend_txn.len(), 3);
4857         assert_eq!(spend_txn[0].input.len(), 1);
4858         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4859         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4860         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4861         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4862 }
4863
4864 #[test]
4865 fn test_onchain_to_onchain_claim() {
4866         // Test that in case of channel closure, we detect the state of output and claim HTLC
4867         // on downstream peer's remote commitment tx.
4868         // First, have C claim an HTLC against its own latest commitment transaction.
4869         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4870         // channel.
4871         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4872         // gets broadcast.
4873
4874         let chanmon_cfgs = create_chanmon_cfgs(3);
4875         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4876         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4877         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4878
4879         // Create some initial channels
4880         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4881         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4882
4883         // Ensure all nodes are at the same height
4884         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4885         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4886         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4887         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4888
4889         // Rebalance the network a bit by relaying one payment through all the channels ...
4890         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4891         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4892
4893         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4894         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4895         check_spends!(commitment_tx[0], chan_2.3);
4896         nodes[2].node.claim_funds(payment_preimage);
4897         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4898         check_added_monitors!(nodes[2], 1);
4899         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4900         assert!(updates.update_add_htlcs.is_empty());
4901         assert!(updates.update_fail_htlcs.is_empty());
4902         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4903         assert!(updates.update_fail_malformed_htlcs.is_empty());
4904
4905         mine_transaction(&nodes[2], &commitment_tx[0]);
4906         check_closed_broadcast!(nodes[2], true);
4907         check_added_monitors!(nodes[2], 1);
4908         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4909
4910         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4911         assert_eq!(c_txn.len(), 1);
4912         check_spends!(c_txn[0], commitment_tx[0]);
4913         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4914         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4915         assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4916
4917         // 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
4918         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4919         check_added_monitors!(nodes[1], 1);
4920         let events = nodes[1].node.get_and_clear_pending_events();
4921         assert_eq!(events.len(), 2);
4922         match events[0] {
4923                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4924                 _ => panic!("Unexpected event"),
4925         }
4926         match events[1] {
4927                 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
4928                         next_channel_id, outbound_amount_forwarded_msat, ..
4929                 } => {
4930                         assert_eq!(total_fee_earned_msat, Some(1000));
4931                         assert_eq!(prev_channel_id, Some(chan_1.2));
4932                         assert_eq!(claim_from_onchain_tx, true);
4933                         assert_eq!(next_channel_id, Some(chan_2.2));
4934                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4935                 },
4936                 _ => panic!("Unexpected event"),
4937         }
4938         check_added_monitors!(nodes[1], 1);
4939         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4940         assert_eq!(msg_events.len(), 3);
4941         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4942         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4943
4944         match nodes_2_event {
4945                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4946                 _ => panic!("Unexpected event"),
4947         }
4948
4949         match nodes_0_event {
4950                 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, .. } } => {
4951                         assert!(update_add_htlcs.is_empty());
4952                         assert!(update_fail_htlcs.is_empty());
4953                         assert_eq!(update_fulfill_htlcs.len(), 1);
4954                         assert!(update_fail_malformed_htlcs.is_empty());
4955                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4956                 },
4957                 _ => panic!("Unexpected event"),
4958         };
4959
4960         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4961         match msg_events[0] {
4962                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4963                 _ => panic!("Unexpected event"),
4964         }
4965
4966         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4967         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4968         mine_transaction(&nodes[1], &commitment_tx[0]);
4969         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4970         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4971         // ChannelMonitor: HTLC-Success tx
4972         assert_eq!(b_txn.len(), 1);
4973         check_spends!(b_txn[0], commitment_tx[0]);
4974         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4975         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4976         assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
4977
4978         check_closed_broadcast!(nodes[1], true);
4979         check_added_monitors!(nodes[1], 1);
4980 }
4981
4982 #[test]
4983 fn test_duplicate_payment_hash_one_failure_one_success() {
4984         // Topology : A --> B --> C --> D
4985         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4986         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4987         // we forward one of the payments onwards to D.
4988         let chanmon_cfgs = create_chanmon_cfgs(4);
4989         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4990         // When this test was written, the default base fee floated based on the HTLC count.
4991         // It is now fixed, so we simply set the fee to the expected value here.
4992         let mut config = test_default_channel_config();
4993         config.channel_config.forwarding_fee_base_msat = 196;
4994         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4995                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4996         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4997
4998         create_announced_chan_between_nodes(&nodes, 0, 1);
4999         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5000         create_announced_chan_between_nodes(&nodes, 2, 3);
5001
5002         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5003         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5004         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5005         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5006         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5007
5008         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5009
5010         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
5011         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5012         // script push size limit so that the below script length checks match
5013         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5014         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
5015                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
5016         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5017         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5018
5019         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5020         assert_eq!(commitment_txn[0].input.len(), 1);
5021         check_spends!(commitment_txn[0], chan_2.3);
5022
5023         mine_transaction(&nodes[1], &commitment_txn[0]);
5024         check_closed_broadcast!(nodes[1], true);
5025         check_added_monitors!(nodes[1], 1);
5026         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5027         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5028
5029         let htlc_timeout_tx;
5030         { // Extract one of the two HTLC-Timeout transaction
5031                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5032                 // ChannelMonitor: timeout tx * 2-or-3
5033                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5034
5035                 check_spends!(node_txn[0], commitment_txn[0]);
5036                 assert_eq!(node_txn[0].input.len(), 1);
5037                 assert_eq!(node_txn[0].output.len(), 1);
5038
5039                 if node_txn.len() > 2 {
5040                         check_spends!(node_txn[1], commitment_txn[0]);
5041                         assert_eq!(node_txn[1].input.len(), 1);
5042                         assert_eq!(node_txn[1].output.len(), 1);
5043                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5044
5045                         check_spends!(node_txn[2], commitment_txn[0]);
5046                         assert_eq!(node_txn[2].input.len(), 1);
5047                         assert_eq!(node_txn[2].output.len(), 1);
5048                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5049                 } else {
5050                         check_spends!(node_txn[1], commitment_txn[0]);
5051                         assert_eq!(node_txn[1].input.len(), 1);
5052                         assert_eq!(node_txn[1].output.len(), 1);
5053                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5054                 }
5055
5056                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5057                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5058                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5059                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5060                 if node_txn.len() > 2 {
5061                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5062                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5063                 } else {
5064                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5065                 }
5066         }
5067
5068         nodes[2].node.claim_funds(our_payment_preimage);
5069         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5070
5071         mine_transaction(&nodes[2], &commitment_txn[0]);
5072         check_added_monitors!(nodes[2], 2);
5073         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5074         let events = nodes[2].node.get_and_clear_pending_msg_events();
5075         match events[0] {
5076                 MessageSendEvent::UpdateHTLCs { .. } => {},
5077                 _ => panic!("Unexpected event"),
5078         }
5079         match events[2] {
5080                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5081                 _ => panic!("Unexepected event"),
5082         }
5083         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5084         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5085         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5086         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5087         assert_eq!(htlc_success_txn[0].input.len(), 1);
5088         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5089         assert_eq!(htlc_success_txn[1].input.len(), 1);
5090         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5091         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5092         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5093
5094         mine_transaction(&nodes[1], &htlc_timeout_tx);
5095         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5096         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 }]);
5097         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5098         assert!(htlc_updates.update_add_htlcs.is_empty());
5099         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5100         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5101         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5102         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5103         check_added_monitors!(nodes[1], 1);
5104
5105         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5106         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5107         {
5108                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5109         }
5110         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5111
5112         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5113         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5114         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5115         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5116         assert!(updates.update_add_htlcs.is_empty());
5117         assert!(updates.update_fail_htlcs.is_empty());
5118         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5119         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5120         assert!(updates.update_fail_malformed_htlcs.is_empty());
5121         check_added_monitors!(nodes[1], 1);
5122
5123         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5124         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5125         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5126 }
5127
5128 #[test]
5129 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5130         let chanmon_cfgs = create_chanmon_cfgs(2);
5131         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5132         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5133         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5134
5135         // Create some initial channels
5136         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5137
5138         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5139         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5140         assert_eq!(local_txn.len(), 1);
5141         assert_eq!(local_txn[0].input.len(), 1);
5142         check_spends!(local_txn[0], chan_1.3);
5143
5144         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5145         nodes[1].node.claim_funds(payment_preimage);
5146         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5147         check_added_monitors!(nodes[1], 1);
5148
5149         mine_transaction(&nodes[1], &local_txn[0]);
5150         check_added_monitors!(nodes[1], 1);
5151         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5152         let events = nodes[1].node.get_and_clear_pending_msg_events();
5153         match events[0] {
5154                 MessageSendEvent::UpdateHTLCs { .. } => {},
5155                 _ => panic!("Unexpected event"),
5156         }
5157         match events[2] {
5158                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5159                 _ => panic!("Unexepected event"),
5160         }
5161         let node_tx = {
5162                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5163                 assert_eq!(node_txn.len(), 1);
5164                 assert_eq!(node_txn[0].input.len(), 1);
5165                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5166                 check_spends!(node_txn[0], local_txn[0]);
5167                 node_txn[0].clone()
5168         };
5169
5170         mine_transaction(&nodes[1], &node_tx);
5171         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5172
5173         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5174         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5175         assert_eq!(spend_txn.len(), 1);
5176         assert_eq!(spend_txn[0].input.len(), 1);
5177         check_spends!(spend_txn[0], node_tx);
5178         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5179 }
5180
5181 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5182         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5183         // unrevoked commitment transaction.
5184         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5185         // a remote RAA before they could be failed backwards (and combinations thereof).
5186         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5187         // use the same payment hashes.
5188         // Thus, we use a six-node network:
5189         //
5190         // A \         / E
5191         //    - C - D -
5192         // B /         \ F
5193         // And test where C fails back to A/B when D announces its latest commitment transaction
5194         let chanmon_cfgs = create_chanmon_cfgs(6);
5195         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5196         // When this test was written, the default base fee floated based on the HTLC count.
5197         // It is now fixed, so we simply set the fee to the expected value here.
5198         let mut config = test_default_channel_config();
5199         config.channel_config.forwarding_fee_base_msat = 196;
5200         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5201                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5202         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5203
5204         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5205         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5206         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5207         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5208         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5209
5210         // Rebalance and check output sanity...
5211         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5212         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5213         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5214
5215         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5216                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5217         // 0th HTLC:
5218         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
5219         // 1st HTLC:
5220         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
5221         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5222         // 2nd HTLC:
5223         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
5224         // 3rd HTLC:
5225         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
5226         // 4th HTLC:
5227         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5228         // 5th HTLC:
5229         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5230         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5231         // 6th HTLC:
5232         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());
5233         // 7th HTLC:
5234         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());
5235
5236         // 8th HTLC:
5237         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5238         // 9th HTLC:
5239         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5240         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
5241
5242         // 10th HTLC:
5243         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
5244         // 11th HTLC:
5245         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5246         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());
5247
5248         // Double-check that six of the new HTLC were added
5249         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5250         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5251         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5252         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5253
5254         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5255         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5256         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5257         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5258         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5259         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5260         check_added_monitors!(nodes[4], 0);
5261
5262         let failed_destinations = vec![
5263                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5264                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5265                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5266                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5267         ];
5268         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5269         check_added_monitors!(nodes[4], 1);
5270
5271         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5272         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5273         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5274         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5275         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5276         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5277
5278         // Fail 3rd below-dust and 7th above-dust HTLCs
5279         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5280         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5281         check_added_monitors!(nodes[5], 0);
5282
5283         let failed_destinations_2 = vec![
5284                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5285                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5286         ];
5287         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5288         check_added_monitors!(nodes[5], 1);
5289
5290         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5291         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5292         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5293         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5294
5295         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5296
5297         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5298         let failed_destinations_3 = vec![
5299                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5300                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5301                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5302                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5303                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5304                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5305         ];
5306         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5307         check_added_monitors!(nodes[3], 1);
5308         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5309         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5310         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5311         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5312         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5313         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5314         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5315         if deliver_last_raa {
5316                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5317         } else {
5318                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5319         }
5320
5321         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5322         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5323         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5324         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5325         //
5326         // We now broadcast the latest commitment transaction, which *should* result in failures for
5327         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5328         // the non-broadcast above-dust HTLCs.
5329         //
5330         // Alternatively, we may broadcast the previous commitment transaction, which should only
5331         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5332         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5333
5334         if announce_latest {
5335                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5336         } else {
5337                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5338         }
5339         let events = nodes[2].node.get_and_clear_pending_events();
5340         let close_event = if deliver_last_raa {
5341                 assert_eq!(events.len(), 2 + 6);
5342                 events.last().clone().unwrap()
5343         } else {
5344                 assert_eq!(events.len(), 1);
5345                 events.last().clone().unwrap()
5346         };
5347         match close_event {
5348                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5349                 _ => panic!("Unexpected event"),
5350         }
5351
5352         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5353         check_closed_broadcast!(nodes[2], true);
5354         if deliver_last_raa {
5355                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[1..2], true);
5356
5357                 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();
5358                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5359         } else {
5360                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5361                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5362                 } else {
5363                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5364                 };
5365
5366                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5367         }
5368         check_added_monitors!(nodes[2], 3);
5369
5370         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5371         assert_eq!(cs_msgs.len(), 2);
5372         let mut a_done = false;
5373         for msg in cs_msgs {
5374                 match msg {
5375                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5376                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5377                                 // should be failed-backwards here.
5378                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5379                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5380                                         for htlc in &updates.update_fail_htlcs {
5381                                                 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 });
5382                                         }
5383                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5384                                         assert!(!a_done);
5385                                         a_done = true;
5386                                         &nodes[0]
5387                                 } else {
5388                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5389                                         for htlc in &updates.update_fail_htlcs {
5390                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5391                                         }
5392                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5393                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5394                                         &nodes[1]
5395                                 };
5396                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5397                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5398                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5399                                 if announce_latest {
5400                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5401                                         if *node_id == nodes[0].node.get_our_node_id() {
5402                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5403                                         }
5404                                 }
5405                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5406                         },
5407                         _ => panic!("Unexpected event"),
5408                 }
5409         }
5410
5411         let as_events = nodes[0].node.get_and_clear_pending_events();
5412         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5413         let mut as_faileds = new_hash_set();
5414         let mut as_updates = 0;
5415         for event in as_events.iter() {
5416                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5417                         assert!(as_faileds.insert(*payment_hash));
5418                         if *payment_hash != payment_hash_2 {
5419                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5420                         } else {
5421                                 assert!(!payment_failed_permanently);
5422                         }
5423                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5424                                 as_updates += 1;
5425                         }
5426                 } else if let &Event::PaymentFailed { .. } = event {
5427                 } else { panic!("Unexpected event"); }
5428         }
5429         assert!(as_faileds.contains(&payment_hash_1));
5430         assert!(as_faileds.contains(&payment_hash_2));
5431         if announce_latest {
5432                 assert!(as_faileds.contains(&payment_hash_3));
5433                 assert!(as_faileds.contains(&payment_hash_5));
5434         }
5435         assert!(as_faileds.contains(&payment_hash_6));
5436
5437         let bs_events = nodes[1].node.get_and_clear_pending_events();
5438         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5439         let mut bs_faileds = new_hash_set();
5440         let mut bs_updates = 0;
5441         for event in bs_events.iter() {
5442                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5443                         assert!(bs_faileds.insert(*payment_hash));
5444                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5445                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5446                         } else {
5447                                 assert!(!payment_failed_permanently);
5448                         }
5449                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5450                                 bs_updates += 1;
5451                         }
5452                 } else if let &Event::PaymentFailed { .. } = event {
5453                 } else { panic!("Unexpected event"); }
5454         }
5455         assert!(bs_faileds.contains(&payment_hash_1));
5456         assert!(bs_faileds.contains(&payment_hash_2));
5457         if announce_latest {
5458                 assert!(bs_faileds.contains(&payment_hash_4));
5459         }
5460         assert!(bs_faileds.contains(&payment_hash_5));
5461
5462         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5463         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5464         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5465         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5466         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5467         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5468 }
5469
5470 #[test]
5471 fn test_fail_backwards_latest_remote_announce_a() {
5472         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5473 }
5474
5475 #[test]
5476 fn test_fail_backwards_latest_remote_announce_b() {
5477         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5478 }
5479
5480 #[test]
5481 fn test_fail_backwards_previous_remote_announce() {
5482         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5483         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5484         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5485 }
5486
5487 #[test]
5488 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5489         let chanmon_cfgs = create_chanmon_cfgs(2);
5490         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5491         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5492         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5493
5494         // Create some initial channels
5495         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5496
5497         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5498         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5499         assert_eq!(local_txn[0].input.len(), 1);
5500         check_spends!(local_txn[0], chan_1.3);
5501
5502         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5503         mine_transaction(&nodes[0], &local_txn[0]);
5504         check_closed_broadcast!(nodes[0], true);
5505         check_added_monitors!(nodes[0], 1);
5506         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5507         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5508
5509         let htlc_timeout = {
5510                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5511                 assert_eq!(node_txn.len(), 1);
5512                 assert_eq!(node_txn[0].input.len(), 1);
5513                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5514                 check_spends!(node_txn[0], local_txn[0]);
5515                 node_txn[0].clone()
5516         };
5517
5518         mine_transaction(&nodes[0], &htlc_timeout);
5519         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5520         expect_payment_failed!(nodes[0], our_payment_hash, false);
5521
5522         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5523         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5524         assert_eq!(spend_txn.len(), 3);
5525         check_spends!(spend_txn[0], local_txn[0]);
5526         assert_eq!(spend_txn[1].input.len(), 1);
5527         check_spends!(spend_txn[1], htlc_timeout);
5528         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5529         assert_eq!(spend_txn[2].input.len(), 2);
5530         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5531         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5532                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5533 }
5534
5535 #[test]
5536 fn test_key_derivation_params() {
5537         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5538         // manager rotation to test that `channel_keys_id` returned in
5539         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5540         // then derive a `delayed_payment_key`.
5541
5542         let chanmon_cfgs = create_chanmon_cfgs(3);
5543
5544         // We manually create the node configuration to backup the seed.
5545         let seed = [42; 32];
5546         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5547         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);
5548         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5549         let scorer = RwLock::new(test_utils::TestScorer::new());
5550         let router = test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[0].logger, &scorer);
5551         let message_router = test_utils::TestMessageRouter::new(network_graph.clone(), &keys_manager);
5552         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, message_router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5553         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5554         node_cfgs.remove(0);
5555         node_cfgs.insert(0, node);
5556
5557         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5558         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5559
5560         // Create some initial channels
5561         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5562         // for node 0
5563         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5564         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5565         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5566
5567         // Ensure all nodes are at the same height
5568         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5569         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5570         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5571         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5572
5573         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5574         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5575         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5576         assert_eq!(local_txn_1[0].input.len(), 1);
5577         check_spends!(local_txn_1[0], chan_1.3);
5578
5579         // We check funding pubkey are unique
5580         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]));
5581         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]));
5582         if from_0_funding_key_0 == from_1_funding_key_0
5583             || from_0_funding_key_0 == from_1_funding_key_1
5584             || from_0_funding_key_1 == from_1_funding_key_0
5585             || from_0_funding_key_1 == from_1_funding_key_1 {
5586                 panic!("Funding pubkeys aren't unique");
5587         }
5588
5589         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5590         mine_transaction(&nodes[0], &local_txn_1[0]);
5591         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5592         check_closed_broadcast!(nodes[0], true);
5593         check_added_monitors!(nodes[0], 1);
5594         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5595
5596         let htlc_timeout = {
5597                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5598                 assert_eq!(node_txn.len(), 1);
5599                 assert_eq!(node_txn[0].input.len(), 1);
5600                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5601                 check_spends!(node_txn[0], local_txn_1[0]);
5602                 node_txn[0].clone()
5603         };
5604
5605         mine_transaction(&nodes[0], &htlc_timeout);
5606         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5607         expect_payment_failed!(nodes[0], our_payment_hash, false);
5608
5609         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5610         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5611         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5612         assert_eq!(spend_txn.len(), 3);
5613         check_spends!(spend_txn[0], local_txn_1[0]);
5614         assert_eq!(spend_txn[1].input.len(), 1);
5615         check_spends!(spend_txn[1], htlc_timeout);
5616         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5617         assert_eq!(spend_txn[2].input.len(), 2);
5618         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5619         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5620                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5621 }
5622
5623 #[test]
5624 fn test_static_output_closing_tx() {
5625         let chanmon_cfgs = create_chanmon_cfgs(2);
5626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5628         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5629
5630         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5631
5632         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5633         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5634
5635         mine_transaction(&nodes[0], &closing_tx);
5636         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5637         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5638
5639         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5640         assert_eq!(spend_txn.len(), 1);
5641         check_spends!(spend_txn[0], closing_tx);
5642
5643         mine_transaction(&nodes[1], &closing_tx);
5644         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5645         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5646
5647         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5648         assert_eq!(spend_txn.len(), 1);
5649         check_spends!(spend_txn[0], closing_tx);
5650 }
5651
5652 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5653         let chanmon_cfgs = create_chanmon_cfgs(2);
5654         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5655         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5656         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5657         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5658
5659         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5660
5661         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5662         // present in B's local commitment transaction, but none of A's commitment transactions.
5663         nodes[1].node.claim_funds(payment_preimage);
5664         check_added_monitors!(nodes[1], 1);
5665         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5666
5667         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5668         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5669         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5670
5671         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5672         check_added_monitors!(nodes[0], 1);
5673         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5674         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5675         check_added_monitors!(nodes[1], 1);
5676
5677         let starting_block = nodes[1].best_block_info();
5678         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5679         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5680                 connect_block(&nodes[1], &block);
5681                 block.header.prev_blockhash = block.block_hash();
5682         }
5683         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5684         check_closed_broadcast!(nodes[1], true);
5685         check_added_monitors!(nodes[1], 1);
5686         check_closed_event!(nodes[1], 1, ClosureReason::HTLCsTimedOut, [nodes[0].node.get_our_node_id()], 100000);
5687 }
5688
5689 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5690         let chanmon_cfgs = create_chanmon_cfgs(2);
5691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5693         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5694         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5695
5696         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5697         nodes[0].node.send_payment_with_route(&route, payment_hash,
5698                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5699         check_added_monitors!(nodes[0], 1);
5700
5701         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5702
5703         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5704         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5705         // to "time out" the HTLC.
5706
5707         let starting_block = nodes[1].best_block_info();
5708         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5709
5710         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5711                 connect_block(&nodes[0], &block);
5712                 block.header.prev_blockhash = block.block_hash();
5713         }
5714         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5715         check_closed_broadcast!(nodes[0], true);
5716         check_added_monitors!(nodes[0], 1);
5717         check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5718 }
5719
5720 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5721         let chanmon_cfgs = create_chanmon_cfgs(3);
5722         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5723         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5724         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5725         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5726
5727         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5728         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5729         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5730         // actually revoked.
5731         let htlc_value = if use_dust { 50000 } else { 3000000 };
5732         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5733         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5734         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5735         check_added_monitors!(nodes[1], 1);
5736
5737         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5738         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5739         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5740         check_added_monitors!(nodes[0], 1);
5741         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5742         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5743         check_added_monitors!(nodes[1], 1);
5744         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5745         check_added_monitors!(nodes[1], 1);
5746         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5747
5748         if check_revoke_no_close {
5749                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5750                 check_added_monitors!(nodes[0], 1);
5751         }
5752
5753         let starting_block = nodes[1].best_block_info();
5754         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5755         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5756                 connect_block(&nodes[0], &block);
5757                 block.header.prev_blockhash = block.block_hash();
5758         }
5759         if !check_revoke_no_close {
5760                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5761                 check_closed_broadcast!(nodes[0], true);
5762                 check_added_monitors!(nodes[0], 1);
5763                 check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5764         } else {
5765                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5766         }
5767 }
5768
5769 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5770 // There are only a few cases to test here:
5771 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5772 //    broadcastable commitment transactions result in channel closure,
5773 //  * its included in an unrevoked-but-previous remote commitment transaction,
5774 //  * its included in the latest remote or local commitment transactions.
5775 // We test each of the three possible commitment transactions individually and use both dust and
5776 // non-dust HTLCs.
5777 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5778 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5779 // tested for at least one of the cases in other tests.
5780 #[test]
5781 fn htlc_claim_single_commitment_only_a() {
5782         do_htlc_claim_local_commitment_only(true);
5783         do_htlc_claim_local_commitment_only(false);
5784
5785         do_htlc_claim_current_remote_commitment_only(true);
5786         do_htlc_claim_current_remote_commitment_only(false);
5787 }
5788
5789 #[test]
5790 fn htlc_claim_single_commitment_only_b() {
5791         do_htlc_claim_previous_remote_commitment_only(true, false);
5792         do_htlc_claim_previous_remote_commitment_only(false, false);
5793         do_htlc_claim_previous_remote_commitment_only(true, true);
5794         do_htlc_claim_previous_remote_commitment_only(false, true);
5795 }
5796
5797 #[test]
5798 #[should_panic]
5799 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5800         let chanmon_cfgs = create_chanmon_cfgs(2);
5801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5804         // Force duplicate randomness for every get-random call
5805         for node in nodes.iter() {
5806                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5807         }
5808
5809         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5810         let channel_value_satoshis=10000;
5811         let push_msat=10001;
5812         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5813         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5814         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5815         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5816
5817         // Create a second channel with the same random values. This used to panic due to a colliding
5818         // channel_id, but now panics due to a colliding outbound SCID alias.
5819         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5820 }
5821
5822 #[test]
5823 fn bolt2_open_channel_sending_node_checks_part2() {
5824         let chanmon_cfgs = create_chanmon_cfgs(2);
5825         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5827         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5828
5829         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5830         let channel_value_satoshis=2^24;
5831         let push_msat=10001;
5832         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5833
5834         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5835         let channel_value_satoshis=10000;
5836         // Test when push_msat is equal to 1000 * funding_satoshis.
5837         let push_msat=1000*channel_value_satoshis+1;
5838         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5839
5840         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5841         let channel_value_satoshis=10000;
5842         let push_msat=10001;
5843         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
5844         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5845         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.common_fields.dust_limit_satoshis);
5846
5847         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5848         // 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
5849         assert!(node0_to_1_send_open_channel.common_fields.channel_flags<=1);
5850
5851         // 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.
5852         assert!(BREAKDOWN_TIMEOUT>0);
5853         assert!(node0_to_1_send_open_channel.common_fields.to_self_delay==BREAKDOWN_TIMEOUT);
5854
5855         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5856         let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5857         assert_eq!(node0_to_1_send_open_channel.common_fields.chain_hash, chain_hash);
5858
5859         // 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.
5860         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.funding_pubkey.serialize()).is_ok());
5861         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.revocation_basepoint.serialize()).is_ok());
5862         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.htlc_basepoint.serialize()).is_ok());
5863         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.payment_basepoint.serialize()).is_ok());
5864         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.delayed_payment_basepoint.serialize()).is_ok());
5865 }
5866
5867 #[test]
5868 fn bolt2_open_channel_sane_dust_limit() {
5869         let chanmon_cfgs = create_chanmon_cfgs(2);
5870         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5871         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5872         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5873
5874         let channel_value_satoshis=1000000;
5875         let push_msat=10001;
5876         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5877         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5878         node0_to_1_send_open_channel.common_fields.dust_limit_satoshis = 547;
5879         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5880
5881         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5882         let events = nodes[1].node.get_and_clear_pending_msg_events();
5883         let err_msg = match events[0] {
5884                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5885                         msg.clone()
5886                 },
5887                 _ => panic!("Unexpected event"),
5888         };
5889         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5890 }
5891
5892 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5893 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5894 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5895 // is no longer affordable once it's freed.
5896 #[test]
5897 fn test_fail_holding_cell_htlc_upon_free() {
5898         let chanmon_cfgs = create_chanmon_cfgs(2);
5899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5901         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5902         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5903
5904         // First nodes[0] generates an update_fee, setting the channel's
5905         // pending_update_fee.
5906         {
5907                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5908                 *feerate_lock += 20;
5909         }
5910         nodes[0].node.timer_tick_occurred();
5911         check_added_monitors!(nodes[0], 1);
5912
5913         let events = nodes[0].node.get_and_clear_pending_msg_events();
5914         assert_eq!(events.len(), 1);
5915         let (update_msg, commitment_signed) = match events[0] {
5916                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5917                         (update_fee.as_ref(), commitment_signed)
5918                 },
5919                 _ => panic!("Unexpected event"),
5920         };
5921
5922         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5923
5924         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5925         let channel_reserve = chan_stat.channel_reserve_msat;
5926         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5927         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5928
5929         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5930         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5931         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5932
5933         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5934         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5935                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5936         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5937         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5938
5939         // Flush the pending fee update.
5940         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5941         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5942         check_added_monitors!(nodes[1], 1);
5943         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5944         check_added_monitors!(nodes[0], 1);
5945
5946         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5947         // HTLC, but now that the fee has been raised the payment will now fail, causing
5948         // us to surface its failure to the user.
5949         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5950         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5951         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5952
5953         // Check that the payment failed to be sent out.
5954         let events = nodes[0].node.get_and_clear_pending_events();
5955         assert_eq!(events.len(), 2);
5956         match &events[0] {
5957                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5958                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5959                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5960                         assert_eq!(*payment_failed_permanently, false);
5961                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5962                 },
5963                 _ => panic!("Unexpected event"),
5964         }
5965         match &events[1] {
5966                 &Event::PaymentFailed { ref payment_hash, .. } => {
5967                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5968                 },
5969                 _ => panic!("Unexpected event"),
5970         }
5971 }
5972
5973 // Test that if multiple HTLCs are released from the holding cell and one is
5974 // valid but the other is no longer valid upon release, the valid HTLC can be
5975 // successfully completed while the other one fails as expected.
5976 #[test]
5977 fn test_free_and_fail_holding_cell_htlcs() {
5978         let chanmon_cfgs = create_chanmon_cfgs(2);
5979         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5980         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5981         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5982         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5983
5984         // First nodes[0] generates an update_fee, setting the channel's
5985         // pending_update_fee.
5986         {
5987                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5988                 *feerate_lock += 200;
5989         }
5990         nodes[0].node.timer_tick_occurred();
5991         check_added_monitors!(nodes[0], 1);
5992
5993         let events = nodes[0].node.get_and_clear_pending_msg_events();
5994         assert_eq!(events.len(), 1);
5995         let (update_msg, commitment_signed) = match events[0] {
5996                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5997                         (update_fee.as_ref(), commitment_signed)
5998                 },
5999                 _ => panic!("Unexpected event"),
6000         };
6001
6002         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6003
6004         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6005         let channel_reserve = chan_stat.channel_reserve_msat;
6006         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6007         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6008
6009         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6010         let amt_1 = 20000;
6011         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
6012         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6013         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6014
6015         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6016         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
6017                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6018         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6019         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6020         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6021         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6022                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6023         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6024         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6025
6026         // Flush the pending fee update.
6027         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6028         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6029         check_added_monitors!(nodes[1], 1);
6030         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6031         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6032         check_added_monitors!(nodes[0], 2);
6033
6034         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6035         // but now that the fee has been raised the second payment will now fail, causing us
6036         // to surface its failure to the user. The first payment should succeed.
6037         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6038         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6039         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6040
6041         // Check that the second payment failed to be sent out.
6042         let events = nodes[0].node.get_and_clear_pending_events();
6043         assert_eq!(events.len(), 2);
6044         match &events[0] {
6045                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6046                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6047                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6048                         assert_eq!(*payment_failed_permanently, false);
6049                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6050                 },
6051                 _ => panic!("Unexpected event"),
6052         }
6053         match &events[1] {
6054                 &Event::PaymentFailed { ref payment_hash, .. } => {
6055                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6056                 },
6057                 _ => panic!("Unexpected event"),
6058         }
6059
6060         // Complete the first payment and the RAA from the fee update.
6061         let (payment_event, send_raa_event) = {
6062                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6063                 assert_eq!(msgs.len(), 2);
6064                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6065         };
6066         let raa = match send_raa_event {
6067                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6068                 _ => panic!("Unexpected event"),
6069         };
6070         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6071         check_added_monitors!(nodes[1], 1);
6072         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6073         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6074         let events = nodes[1].node.get_and_clear_pending_events();
6075         assert_eq!(events.len(), 1);
6076         match events[0] {
6077                 Event::PendingHTLCsForwardable { .. } => {},
6078                 _ => panic!("Unexpected event"),
6079         }
6080         nodes[1].node.process_pending_htlc_forwards();
6081         let events = nodes[1].node.get_and_clear_pending_events();
6082         assert_eq!(events.len(), 1);
6083         match events[0] {
6084                 Event::PaymentClaimable { .. } => {},
6085                 _ => panic!("Unexpected event"),
6086         }
6087         nodes[1].node.claim_funds(payment_preimage_1);
6088         check_added_monitors!(nodes[1], 1);
6089         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6090
6091         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6092         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6093         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6094         expect_payment_sent!(nodes[0], payment_preimage_1);
6095 }
6096
6097 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6098 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6099 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6100 // once it's freed.
6101 #[test]
6102 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6103         let chanmon_cfgs = create_chanmon_cfgs(3);
6104         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6105         // Avoid having to include routing fees in calculations
6106         let mut config = test_default_channel_config();
6107         config.channel_config.forwarding_fee_base_msat = 0;
6108         config.channel_config.forwarding_fee_proportional_millionths = 0;
6109         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6110         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6111         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6112         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6113
6114         // First nodes[1] generates an update_fee, setting the channel's
6115         // pending_update_fee.
6116         {
6117                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6118                 *feerate_lock += 20;
6119         }
6120         nodes[1].node.timer_tick_occurred();
6121         check_added_monitors!(nodes[1], 1);
6122
6123         let events = nodes[1].node.get_and_clear_pending_msg_events();
6124         assert_eq!(events.len(), 1);
6125         let (update_msg, commitment_signed) = match events[0] {
6126                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6127                         (update_fee.as_ref(), commitment_signed)
6128                 },
6129                 _ => panic!("Unexpected event"),
6130         };
6131
6132         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6133
6134         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6135         let channel_reserve = chan_stat.channel_reserve_msat;
6136         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6137         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6138
6139         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6140         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6141         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6142         let payment_event = {
6143                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6144                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6145                 check_added_monitors!(nodes[0], 1);
6146
6147                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6148                 assert_eq!(events.len(), 1);
6149
6150                 SendEvent::from_event(events.remove(0))
6151         };
6152         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6153         check_added_monitors!(nodes[1], 0);
6154         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6155         expect_pending_htlcs_forwardable!(nodes[1]);
6156
6157         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6158         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6159
6160         // Flush the pending fee update.
6161         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6162         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6163         check_added_monitors!(nodes[2], 1);
6164         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6165         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6166         check_added_monitors!(nodes[1], 2);
6167
6168         // A final RAA message is generated to finalize the fee update.
6169         let events = nodes[1].node.get_and_clear_pending_msg_events();
6170         assert_eq!(events.len(), 1);
6171
6172         let raa_msg = match &events[0] {
6173                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6174                         msg.clone()
6175                 },
6176                 _ => panic!("Unexpected event"),
6177         };
6178
6179         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6180         check_added_monitors!(nodes[2], 1);
6181         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6182
6183         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6184         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6185         assert_eq!(process_htlc_forwards_event.len(), 2);
6186         match &process_htlc_forwards_event[1] {
6187                 &Event::PendingHTLCsForwardable { .. } => {},
6188                 _ => panic!("Unexpected event"),
6189         }
6190
6191         // In response, we call ChannelManager's process_pending_htlc_forwards
6192         nodes[1].node.process_pending_htlc_forwards();
6193         check_added_monitors!(nodes[1], 1);
6194
6195         // This causes the HTLC to be failed backwards.
6196         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6197         assert_eq!(fail_event.len(), 1);
6198         let (fail_msg, commitment_signed) = match &fail_event[0] {
6199                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6200                         assert_eq!(updates.update_add_htlcs.len(), 0);
6201                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6202                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6203                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6204                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6205                 },
6206                 _ => panic!("Unexpected event"),
6207         };
6208
6209         // Pass the failure messages back to nodes[0].
6210         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6211         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6212
6213         // Complete the HTLC failure+removal process.
6214         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6215         check_added_monitors!(nodes[0], 1);
6216         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6217         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6218         check_added_monitors!(nodes[1], 2);
6219         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6220         assert_eq!(final_raa_event.len(), 1);
6221         let raa = match &final_raa_event[0] {
6222                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6223                 _ => panic!("Unexpected event"),
6224         };
6225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6226         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6227         check_added_monitors!(nodes[0], 1);
6228 }
6229
6230 #[test]
6231 fn test_payment_route_reaching_same_channel_twice() {
6232         //A route should not go through the same channel twice
6233         //It is enforced when constructing a route.
6234         let chanmon_cfgs = create_chanmon_cfgs(2);
6235         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6236         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6237         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6238         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6239
6240         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6241                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6242         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6243
6244         // Extend the path by itself, essentially simulating route going through same channel twice
6245         let cloned_hops = route.paths[0].hops.clone();
6246         route.paths[0].hops.extend_from_slice(&cloned_hops);
6247
6248         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6249                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6250         ), false, APIError::InvalidRoute { ref err },
6251         assert_eq!(err, &"Path went through the same channel twice"));
6252 }
6253
6254 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6255 // 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.
6256 //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.
6257
6258 #[test]
6259 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6260         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6261         let chanmon_cfgs = create_chanmon_cfgs(2);
6262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6264         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6265         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6266
6267         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6268         route.paths[0].hops[0].fee_msat = 100;
6269
6270         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6271                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6272                 ), true, APIError::ChannelUnavailable { .. }, {});
6273         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6274 }
6275
6276 #[test]
6277 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6278         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6279         let chanmon_cfgs = create_chanmon_cfgs(2);
6280         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6281         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6282         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6283         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6284
6285         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6286         route.paths[0].hops[0].fee_msat = 0;
6287         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6288                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6289                 true, APIError::ChannelUnavailable { ref err },
6290                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6291
6292         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6293         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6294 }
6295
6296 #[test]
6297 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6298         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6299         let chanmon_cfgs = create_chanmon_cfgs(2);
6300         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6301         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6302         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6303         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6304
6305         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6306         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6307                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6308         check_added_monitors!(nodes[0], 1);
6309         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6310         updates.update_add_htlcs[0].amount_msat = 0;
6311
6312         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6313         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC", 3);
6314         check_closed_broadcast!(nodes[1], true).unwrap();
6315         check_added_monitors!(nodes[1], 1);
6316         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6317                 [nodes[0].node.get_our_node_id()], 100000);
6318 }
6319
6320 #[test]
6321 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6322         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6323         //It is enforced when constructing a route.
6324         let chanmon_cfgs = create_chanmon_cfgs(2);
6325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6327         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6328         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6329
6330         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6331                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6332         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6333         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6334         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6335                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6336                 ), true, APIError::InvalidRoute { ref err },
6337                 assert_eq!(err, &"Channel CLTV overflowed?"));
6338 }
6339
6340 #[test]
6341 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6342         //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.
6343         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6344         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6345         let chanmon_cfgs = create_chanmon_cfgs(2);
6346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6348         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6349         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6350         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6351                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6352
6353         // Fetch a route in advance as we will be unable to once we're unable to send.
6354         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6355         for i in 0..max_accepted_htlcs {
6356                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6357                 let payment_event = {
6358                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6359                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6360                         check_added_monitors!(nodes[0], 1);
6361
6362                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6363                         assert_eq!(events.len(), 1);
6364                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6365                                 assert_eq!(htlcs[0].htlc_id, i);
6366                         } else {
6367                                 assert!(false);
6368                         }
6369                         SendEvent::from_event(events.remove(0))
6370                 };
6371                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6372                 check_added_monitors!(nodes[1], 0);
6373                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6374
6375                 expect_pending_htlcs_forwardable!(nodes[1]);
6376                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6377         }
6378         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6379                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6380                 ), true, APIError::ChannelUnavailable { .. }, {});
6381
6382         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6383 }
6384
6385 #[test]
6386 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6387         //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.
6388         let chanmon_cfgs = create_chanmon_cfgs(2);
6389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6391         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6392         let channel_value = 100000;
6393         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6394         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6395
6396         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6397
6398         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6399         // Manually create a route over our max in flight (which our router normally automatically
6400         // limits us to.
6401         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6402         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6403                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6404                 ), true, APIError::ChannelUnavailable { .. }, {});
6405         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6406
6407         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6408 }
6409
6410 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6411 #[test]
6412 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6413         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6414         let chanmon_cfgs = create_chanmon_cfgs(2);
6415         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6416         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6417         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6418         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6419         let htlc_minimum_msat: u64;
6420         {
6421                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6422                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6423                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6424                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6425         }
6426
6427         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6428         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6429                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6430         check_added_monitors!(nodes[0], 1);
6431         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6432         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6433         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6434         assert!(nodes[1].node.list_channels().is_empty());
6435         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6436         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()));
6437         check_added_monitors!(nodes[1], 1);
6438         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6439 }
6440
6441 #[test]
6442 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6443         //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
6444         let chanmon_cfgs = create_chanmon_cfgs(2);
6445         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6446         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6447         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6448         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6449
6450         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6451         let channel_reserve = chan_stat.channel_reserve_msat;
6452         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6453         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6454         // The 2* and +1 are for the fee spike reserve.
6455         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6456
6457         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6458         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6459         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6460                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6461         check_added_monitors!(nodes[0], 1);
6462         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6463
6464         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6465         // at this time channel-initiatee receivers are not required to enforce that senders
6466         // respect the fee_spike_reserve.
6467         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6468         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6469
6470         assert!(nodes[1].node.list_channels().is_empty());
6471         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6472         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6473         check_added_monitors!(nodes[1], 1);
6474         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6475 }
6476
6477 #[test]
6478 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6479         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6480         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6481         let chanmon_cfgs = create_chanmon_cfgs(2);
6482         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6483         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6484         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6485         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6486
6487         let send_amt = 3999999;
6488         let (mut route, our_payment_hash, _, our_payment_secret) =
6489                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6490         route.paths[0].hops[0].fee_msat = send_amt;
6491         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6492         let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
6493         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6494         let recipient_onion_fields = RecipientOnionFields::secret_only(our_payment_secret);
6495         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6496                 &route.paths[0], send_amt, &recipient_onion_fields, cur_height, &None).unwrap();
6497         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6498
6499         let mut msg = msgs::UpdateAddHTLC {
6500                 channel_id: chan.2,
6501                 htlc_id: 0,
6502                 amount_msat: 1000,
6503                 payment_hash: our_payment_hash,
6504                 cltv_expiry: htlc_cltv,
6505                 onion_routing_packet: onion_packet.clone(),
6506                 skimmed_fee_msat: None,
6507                 blinding_point: None,
6508         };
6509
6510         for i in 0..50 {
6511                 msg.htlc_id = i as u64;
6512                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6513         }
6514         msg.htlc_id = (50) as u64;
6515         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6516
6517         assert!(nodes[1].node.list_channels().is_empty());
6518         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6519         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6520         check_added_monitors!(nodes[1], 1);
6521         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6522 }
6523
6524 #[test]
6525 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6526         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6527         let chanmon_cfgs = create_chanmon_cfgs(2);
6528         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6529         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6530         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6531         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6532
6533         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6534         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6535                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6536         check_added_monitors!(nodes[0], 1);
6537         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6538         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;
6539         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6540
6541         assert!(nodes[1].node.list_channels().is_empty());
6542         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6543         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6544         check_added_monitors!(nodes[1], 1);
6545         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6546 }
6547
6548 #[test]
6549 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6550         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6551         let chanmon_cfgs = create_chanmon_cfgs(2);
6552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6554         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6555
6556         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6557         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6558         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6559                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6560         check_added_monitors!(nodes[0], 1);
6561         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6563         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6564
6565         assert!(nodes[1].node.list_channels().is_empty());
6566         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6567         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6568         check_added_monitors!(nodes[1], 1);
6569         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6570 }
6571
6572 #[test]
6573 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6574         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6575         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6576         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6577         let chanmon_cfgs = create_chanmon_cfgs(2);
6578         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6579         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6580         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6581
6582         create_announced_chan_between_nodes(&nodes, 0, 1);
6583         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6584         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6585                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6586         check_added_monitors!(nodes[0], 1);
6587         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6588         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6589
6590         //Disconnect and Reconnect
6591         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6592         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6593         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6594                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6595         }, true).unwrap();
6596         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6597         assert_eq!(reestablish_1.len(), 1);
6598         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6599                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6600         }, false).unwrap();
6601         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6602         assert_eq!(reestablish_2.len(), 1);
6603         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6604         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6605         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6606         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6607
6608         //Resend HTLC
6609         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6610         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6611         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6612         check_added_monitors!(nodes[1], 1);
6613         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6614
6615         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6616
6617         assert!(nodes[1].node.list_channels().is_empty());
6618         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6619         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6620         check_added_monitors!(nodes[1], 1);
6621         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6622 }
6623
6624 #[test]
6625 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6626         //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.
6627
6628         let chanmon_cfgs = create_chanmon_cfgs(2);
6629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6631         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6632         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6633         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6634         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6635                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6636
6637         check_added_monitors!(nodes[0], 1);
6638         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6639         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6640
6641         let update_msg = msgs::UpdateFulfillHTLC{
6642                 channel_id: chan.2,
6643                 htlc_id: 0,
6644                 payment_preimage: our_payment_preimage,
6645         };
6646
6647         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6648
6649         assert!(nodes[0].node.list_channels().is_empty());
6650         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6651         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()));
6652         check_added_monitors!(nodes[0], 1);
6653         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6654 }
6655
6656 #[test]
6657 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6658         //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.
6659
6660         let chanmon_cfgs = create_chanmon_cfgs(2);
6661         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6662         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6663         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6664         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6665
6666         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6667         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6668                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6669         check_added_monitors!(nodes[0], 1);
6670         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6671         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6672
6673         let update_msg = msgs::UpdateFailHTLC{
6674                 channel_id: chan.2,
6675                 htlc_id: 0,
6676                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6677         };
6678
6679         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6680
6681         assert!(nodes[0].node.list_channels().is_empty());
6682         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6683         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()));
6684         check_added_monitors!(nodes[0], 1);
6685         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6686 }
6687
6688 #[test]
6689 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6690         //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.
6691
6692         let chanmon_cfgs = create_chanmon_cfgs(2);
6693         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6694         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6695         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6696         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6697
6698         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6699         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6700                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6701         check_added_monitors!(nodes[0], 1);
6702         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6703         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6704         let update_msg = msgs::UpdateFailMalformedHTLC{
6705                 channel_id: chan.2,
6706                 htlc_id: 0,
6707                 sha256_of_onion: [1; 32],
6708                 failure_code: 0x8000,
6709         };
6710
6711         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6712
6713         assert!(nodes[0].node.list_channels().is_empty());
6714         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6715         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()));
6716         check_added_monitors!(nodes[0], 1);
6717         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6718 }
6719
6720 #[test]
6721 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6722         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6723
6724         let chanmon_cfgs = create_chanmon_cfgs(2);
6725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6727         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6728         create_announced_chan_between_nodes(&nodes, 0, 1);
6729
6730         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6731
6732         nodes[1].node.claim_funds(our_payment_preimage);
6733         check_added_monitors!(nodes[1], 1);
6734         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6735
6736         let events = nodes[1].node.get_and_clear_pending_msg_events();
6737         assert_eq!(events.len(), 1);
6738         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6739                 match events[0] {
6740                         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, .. } } => {
6741                                 assert!(update_add_htlcs.is_empty());
6742                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6743                                 assert!(update_fail_htlcs.is_empty());
6744                                 assert!(update_fail_malformed_htlcs.is_empty());
6745                                 assert!(update_fee.is_none());
6746                                 update_fulfill_htlcs[0].clone()
6747                         },
6748                         _ => panic!("Unexpected event"),
6749                 }
6750         };
6751
6752         update_fulfill_msg.htlc_id = 1;
6753
6754         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6755
6756         assert!(nodes[0].node.list_channels().is_empty());
6757         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6758         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6759         check_added_monitors!(nodes[0], 1);
6760         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6761 }
6762
6763 #[test]
6764 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6765         //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.
6766
6767         let chanmon_cfgs = create_chanmon_cfgs(2);
6768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6769         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6770         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6771         create_announced_chan_between_nodes(&nodes, 0, 1);
6772
6773         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6774
6775         nodes[1].node.claim_funds(our_payment_preimage);
6776         check_added_monitors!(nodes[1], 1);
6777         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6778
6779         let events = nodes[1].node.get_and_clear_pending_msg_events();
6780         assert_eq!(events.len(), 1);
6781         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6782                 match events[0] {
6783                         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, .. } } => {
6784                                 assert!(update_add_htlcs.is_empty());
6785                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6786                                 assert!(update_fail_htlcs.is_empty());
6787                                 assert!(update_fail_malformed_htlcs.is_empty());
6788                                 assert!(update_fee.is_none());
6789                                 update_fulfill_htlcs[0].clone()
6790                         },
6791                         _ => panic!("Unexpected event"),
6792                 }
6793         };
6794
6795         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6796
6797         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6798
6799         assert!(nodes[0].node.list_channels().is_empty());
6800         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6801         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6802         check_added_monitors!(nodes[0], 1);
6803         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6804 }
6805
6806 #[test]
6807 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6808         //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.
6809
6810         let chanmon_cfgs = create_chanmon_cfgs(2);
6811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6813         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6814         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6815
6816         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6817         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6818                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6819         check_added_monitors!(nodes[0], 1);
6820
6821         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6822         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6823
6824         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6825         check_added_monitors!(nodes[1], 0);
6826         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6827
6828         let events = nodes[1].node.get_and_clear_pending_msg_events();
6829
6830         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6831                 match events[0] {
6832                         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, .. } } => {
6833                                 assert!(update_add_htlcs.is_empty());
6834                                 assert!(update_fulfill_htlcs.is_empty());
6835                                 assert!(update_fail_htlcs.is_empty());
6836                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6837                                 assert!(update_fee.is_none());
6838                                 update_fail_malformed_htlcs[0].clone()
6839                         },
6840                         _ => panic!("Unexpected event"),
6841                 }
6842         };
6843         update_msg.failure_code &= !0x8000;
6844         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6845
6846         assert!(nodes[0].node.list_channels().is_empty());
6847         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6848         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6849         check_added_monitors!(nodes[0], 1);
6850         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6851 }
6852
6853 #[test]
6854 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6855         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6856         //    * 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.
6857
6858         let chanmon_cfgs = create_chanmon_cfgs(3);
6859         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6860         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6861         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6862         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6863         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6864
6865         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6866
6867         //First hop
6868         let mut payment_event = {
6869                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6870                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6871                 check_added_monitors!(nodes[0], 1);
6872                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6873                 assert_eq!(events.len(), 1);
6874                 SendEvent::from_event(events.remove(0))
6875         };
6876         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6877         check_added_monitors!(nodes[1], 0);
6878         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6879         expect_pending_htlcs_forwardable!(nodes[1]);
6880         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6881         assert_eq!(events_2.len(), 1);
6882         check_added_monitors!(nodes[1], 1);
6883         payment_event = SendEvent::from_event(events_2.remove(0));
6884         assert_eq!(payment_event.msgs.len(), 1);
6885
6886         //Second Hop
6887         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6888         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6889         check_added_monitors!(nodes[2], 0);
6890         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6891
6892         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6893         assert_eq!(events_3.len(), 1);
6894         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6895                 match events_3[0] {
6896                         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 } } => {
6897                                 assert!(update_add_htlcs.is_empty());
6898                                 assert!(update_fulfill_htlcs.is_empty());
6899                                 assert!(update_fail_htlcs.is_empty());
6900                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6901                                 assert!(update_fee.is_none());
6902                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6903                         },
6904                         _ => panic!("Unexpected event"),
6905                 }
6906         };
6907
6908         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6909
6910         check_added_monitors!(nodes[1], 0);
6911         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6912         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 }]);
6913         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6914         assert_eq!(events_4.len(), 1);
6915
6916         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6917         match events_4[0] {
6918                 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, .. } } => {
6919                         assert!(update_add_htlcs.is_empty());
6920                         assert!(update_fulfill_htlcs.is_empty());
6921                         assert_eq!(update_fail_htlcs.len(), 1);
6922                         assert!(update_fail_malformed_htlcs.is_empty());
6923                         assert!(update_fee.is_none());
6924                 },
6925                 _ => panic!("Unexpected event"),
6926         };
6927
6928         check_added_monitors!(nodes[1], 1);
6929 }
6930
6931 #[test]
6932 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6933         let chanmon_cfgs = create_chanmon_cfgs(3);
6934         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6935         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6936         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6937         create_announced_chan_between_nodes(&nodes, 0, 1);
6938         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6939
6940         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6941
6942         // First hop
6943         let mut payment_event = {
6944                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6945                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6946                 check_added_monitors!(nodes[0], 1);
6947                 SendEvent::from_node(&nodes[0])
6948         };
6949
6950         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6951         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6952         expect_pending_htlcs_forwardable!(nodes[1]);
6953         check_added_monitors!(nodes[1], 1);
6954         payment_event = SendEvent::from_node(&nodes[1]);
6955         assert_eq!(payment_event.msgs.len(), 1);
6956
6957         // Second Hop
6958         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6959         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6960         check_added_monitors!(nodes[2], 0);
6961         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6962
6963         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6964         assert_eq!(events_3.len(), 1);
6965         match events_3[0] {
6966                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6967                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6968                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6969                         update_msg.failure_code |= 0x2000;
6970
6971                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6972                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6973                 },
6974                 _ => panic!("Unexpected event"),
6975         }
6976
6977         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6978                 vec![HTLCDestination::NextHopChannel {
6979                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6980         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6981         assert_eq!(events_4.len(), 1);
6982         check_added_monitors!(nodes[1], 1);
6983
6984         match events_4[0] {
6985                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6986                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6987                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6988                 },
6989                 _ => panic!("Unexpected event"),
6990         }
6991
6992         let events_5 = nodes[0].node.get_and_clear_pending_events();
6993         assert_eq!(events_5.len(), 2);
6994
6995         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6996         // the node originating the error to its next hop.
6997         match events_5[0] {
6998                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6999                 } => {
7000                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7001                         assert!(is_permanent);
7002                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7003                 },
7004                 _ => panic!("Unexpected event"),
7005         }
7006         match events_5[1] {
7007                 Event::PaymentFailed { payment_hash, .. } => {
7008                         assert_eq!(payment_hash, our_payment_hash);
7009                 },
7010                 _ => panic!("Unexpected event"),
7011         }
7012
7013         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7014 }
7015
7016 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7017         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7018         // 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
7019         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7020
7021         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7022         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7023         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7024         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7025         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7026         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7027
7028         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7029                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7030
7031         // We route 2 dust-HTLCs between A and B
7032         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7033         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7034         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7035
7036         // Cache one local commitment tx as previous
7037         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7038
7039         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7040         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7041         check_added_monitors!(nodes[1], 0);
7042         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7043         check_added_monitors!(nodes[1], 1);
7044
7045         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7046         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7047         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7048         check_added_monitors!(nodes[0], 1);
7049
7050         // Cache one local commitment tx as lastest
7051         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7052
7053         let events = nodes[0].node.get_and_clear_pending_msg_events();
7054         match events[0] {
7055                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7056                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7057                 },
7058                 _ => panic!("Unexpected event"),
7059         }
7060         match events[1] {
7061                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7062                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7063                 },
7064                 _ => panic!("Unexpected event"),
7065         }
7066
7067         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7068         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7069         if announce_latest {
7070                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7071         } else {
7072                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7073         }
7074
7075         check_closed_broadcast!(nodes[0], true);
7076         check_added_monitors!(nodes[0], 1);
7077         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7078
7079         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7080         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7081         let events = nodes[0].node.get_and_clear_pending_events();
7082         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7083         assert_eq!(events.len(), 4);
7084         let mut first_failed = false;
7085         for event in events {
7086                 match event {
7087                         Event::PaymentPathFailed { payment_hash, .. } => {
7088                                 if payment_hash == payment_hash_1 {
7089                                         assert!(!first_failed);
7090                                         first_failed = true;
7091                                 } else {
7092                                         assert_eq!(payment_hash, payment_hash_2);
7093                                 }
7094                         },
7095                         Event::PaymentFailed { .. } => {}
7096                         _ => panic!("Unexpected event"),
7097                 }
7098         }
7099 }
7100
7101 #[test]
7102 fn test_failure_delay_dust_htlc_local_commitment() {
7103         do_test_failure_delay_dust_htlc_local_commitment(true);
7104         do_test_failure_delay_dust_htlc_local_commitment(false);
7105 }
7106
7107 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7108         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7109         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7110         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7111         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7112         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7113         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7114
7115         let chanmon_cfgs = create_chanmon_cfgs(3);
7116         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7117         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7118         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7119         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7120
7121         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7122                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7123
7124         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7125         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7126
7127         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7128         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7129
7130         // We revoked bs_commitment_tx
7131         if revoked {
7132                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7133                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7134         }
7135
7136         let mut timeout_tx = Vec::new();
7137         if local {
7138                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7139                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7140                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7141                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7142                 expect_payment_failed!(nodes[0], dust_hash, false);
7143
7144                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7145                 check_closed_broadcast!(nodes[0], true);
7146                 check_added_monitors!(nodes[0], 1);
7147                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7148                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7149                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7150                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7151                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7152                 mine_transaction(&nodes[0], &timeout_tx[0]);
7153                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7154                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7155         } else {
7156                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7157                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7158                 check_closed_broadcast!(nodes[0], true);
7159                 check_added_monitors!(nodes[0], 1);
7160                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7161                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7162
7163                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7164                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7165                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7166                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7167                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7168                 // dust HTLC should have been failed.
7169                 expect_payment_failed!(nodes[0], dust_hash, false);
7170
7171                 if !revoked {
7172                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7173                 } else {
7174                         assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7175                 }
7176                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7177                 mine_transaction(&nodes[0], &timeout_tx[0]);
7178                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7179                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7180                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7181         }
7182 }
7183
7184 #[test]
7185 fn test_sweep_outbound_htlc_failure_update() {
7186         do_test_sweep_outbound_htlc_failure_update(false, true);
7187         do_test_sweep_outbound_htlc_failure_update(false, false);
7188         do_test_sweep_outbound_htlc_failure_update(true, false);
7189 }
7190
7191 #[test]
7192 fn test_user_configurable_csv_delay() {
7193         // We test our channel constructors yield errors when we pass them absurd csv delay
7194
7195         let mut low_our_to_self_config = UserConfig::default();
7196         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7197         let mut high_their_to_self_config = UserConfig::default();
7198         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7199         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7200         let chanmon_cfgs = create_chanmon_cfgs(2);
7201         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7202         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7203         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7204
7205         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7206         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7207                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7208                 &low_our_to_self_config, 0, 42, None)
7209         {
7210                 match error {
7211                         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())); },
7212                         _ => panic!("Unexpected event"),
7213                 }
7214         } else { assert!(false) }
7215
7216         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7217         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7218         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7219         open_channel.common_fields.to_self_delay = 200;
7220         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7221                 &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,
7222                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7223         {
7224                 match error {
7225                         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()));  },
7226                         _ => panic!("Unexpected event"),
7227                 }
7228         } else { assert!(false); }
7229
7230         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7231         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7232         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()));
7233         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7234         accept_channel.common_fields.to_self_delay = 200;
7235         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7236         let reason_msg;
7237         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7238                 match action {
7239                         &ErrorAction::SendErrorMessage { ref msg } => {
7240                                 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()));
7241                                 reason_msg = msg.data.clone();
7242                         },
7243                         _ => { panic!(); }
7244                 }
7245         } else { panic!(); }
7246         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7247
7248         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7249         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7250         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7251         open_channel.common_fields.to_self_delay = 200;
7252         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7253                 &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,
7254                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7255         {
7256                 match error {
7257                         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())); },
7258                         _ => panic!("Unexpected event"),
7259                 }
7260         } else { assert!(false); }
7261 }
7262
7263 #[test]
7264 fn test_check_htlc_underpaying() {
7265         // Send payment through A -> B but A is maliciously
7266         // sending a probe payment (i.e less than expected value0
7267         // to B, B should refuse payment.
7268
7269         let chanmon_cfgs = create_chanmon_cfgs(2);
7270         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7271         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7272         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7273
7274         // Create some initial channels
7275         create_announced_chan_between_nodes(&nodes, 0, 1);
7276
7277         let scorer = test_utils::TestScorer::new();
7278         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7279         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7280                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7281         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7282         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7283                 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7284         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7285         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7286         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7287                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7288         check_added_monitors!(nodes[0], 1);
7289
7290         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7291         assert_eq!(events.len(), 1);
7292         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7293         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7294         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7295
7296         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7297         // and then will wait a second random delay before failing the HTLC back:
7298         expect_pending_htlcs_forwardable!(nodes[1]);
7299         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7300
7301         // Node 3 is expecting payment of 100_000 but received 10_000,
7302         // it should fail htlc like we didn't know the preimage.
7303         nodes[1].node.process_pending_htlc_forwards();
7304
7305         let events = nodes[1].node.get_and_clear_pending_msg_events();
7306         assert_eq!(events.len(), 1);
7307         let (update_fail_htlc, commitment_signed) = match events[0] {
7308                 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 } } => {
7309                         assert!(update_add_htlcs.is_empty());
7310                         assert!(update_fulfill_htlcs.is_empty());
7311                         assert_eq!(update_fail_htlcs.len(), 1);
7312                         assert!(update_fail_malformed_htlcs.is_empty());
7313                         assert!(update_fee.is_none());
7314                         (update_fail_htlcs[0].clone(), commitment_signed)
7315                 },
7316                 _ => panic!("Unexpected event"),
7317         };
7318         check_added_monitors!(nodes[1], 1);
7319
7320         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7321         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7322
7323         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7324         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7325         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7326         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7327 }
7328
7329 #[test]
7330 fn test_announce_disable_channels() {
7331         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7332         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7333
7334         let chanmon_cfgs = create_chanmon_cfgs(2);
7335         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7336         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7337         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7338
7339         // Connect a dummy node for proper future events broadcasting
7340         connect_dummy_node(&nodes[0]);
7341
7342         create_announced_chan_between_nodes(&nodes, 0, 1);
7343         create_announced_chan_between_nodes(&nodes, 1, 0);
7344         create_announced_chan_between_nodes(&nodes, 0, 1);
7345
7346         // Disconnect peers
7347         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7348         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7349
7350         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7351                 nodes[0].node.timer_tick_occurred();
7352         }
7353         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7354         assert_eq!(msg_events.len(), 3);
7355         let mut chans_disabled = new_hash_map();
7356         for e in msg_events {
7357                 match e {
7358                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7359                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7360                                 // Check that each channel gets updated exactly once
7361                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7362                                         panic!("Generated ChannelUpdate for wrong chan!");
7363                                 }
7364                         },
7365                         _ => panic!("Unexpected event"),
7366                 }
7367         }
7368         // Reconnect peers
7369         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7370                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7371         }, true).unwrap();
7372         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7373         assert_eq!(reestablish_1.len(), 3);
7374         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7375                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7376         }, false).unwrap();
7377         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7378         assert_eq!(reestablish_2.len(), 3);
7379
7380         // Reestablish chan_1
7381         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7382         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7383         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7384         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7385         // Reestablish chan_2
7386         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7387         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7388         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7389         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7390         // Reestablish chan_3
7391         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7392         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7393         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7394         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7395
7396         for _ in 0..ENABLE_GOSSIP_TICKS {
7397                 nodes[0].node.timer_tick_occurred();
7398         }
7399         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7400         nodes[0].node.timer_tick_occurred();
7401         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7402         assert_eq!(msg_events.len(), 3);
7403         for e in msg_events {
7404                 match e {
7405                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7406                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7407                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7408                                         // Each update should have a higher timestamp than the previous one, replacing
7409                                         // the old one.
7410                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7411                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7412                                 }
7413                         },
7414                         _ => panic!("Unexpected event"),
7415                 }
7416         }
7417         // Check that each channel gets updated exactly once
7418         assert!(chans_disabled.is_empty());
7419 }
7420
7421 #[test]
7422 fn test_bump_penalty_txn_on_revoked_commitment() {
7423         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7424         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7425
7426         let chanmon_cfgs = create_chanmon_cfgs(2);
7427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7429         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7430
7431         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7432
7433         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7434         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7435                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7436         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7437         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7438
7439         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7440         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7441         assert_eq!(revoked_txn[0].output.len(), 4);
7442         assert_eq!(revoked_txn[0].input.len(), 1);
7443         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7444         let revoked_txid = revoked_txn[0].txid();
7445
7446         let mut penalty_sum = 0;
7447         for outp in revoked_txn[0].output.iter() {
7448                 if outp.script_pubkey.is_v0_p2wsh() {
7449                         penalty_sum += outp.value;
7450                 }
7451         }
7452
7453         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7454         let header_114 = connect_blocks(&nodes[1], 14);
7455
7456         // Actually revoke tx by claiming a HTLC
7457         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7458         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7459         check_added_monitors!(nodes[1], 1);
7460
7461         // One or more justice tx should have been broadcast, check it
7462         let penalty_1;
7463         let feerate_1;
7464         {
7465                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7466                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7467                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7468                 assert_eq!(node_txn[0].output.len(), 1);
7469                 check_spends!(node_txn[0], revoked_txn[0]);
7470                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7471                 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7472                 penalty_1 = node_txn[0].txid();
7473                 node_txn.clear();
7474         };
7475
7476         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7477         connect_blocks(&nodes[1], 15);
7478         let mut penalty_2 = penalty_1;
7479         let mut feerate_2 = 0;
7480         {
7481                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7482                 assert_eq!(node_txn.len(), 1);
7483                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7484                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7485                         assert_eq!(node_txn[0].output.len(), 1);
7486                         check_spends!(node_txn[0], revoked_txn[0]);
7487                         penalty_2 = node_txn[0].txid();
7488                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7489                         assert_ne!(penalty_2, penalty_1);
7490                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7491                         feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7492                         // Verify 25% bump heuristic
7493                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7494                         node_txn.clear();
7495                 }
7496         }
7497         assert_ne!(feerate_2, 0);
7498
7499         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7500         connect_blocks(&nodes[1], 1);
7501         let penalty_3;
7502         let mut feerate_3 = 0;
7503         {
7504                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7505                 assert_eq!(node_txn.len(), 1);
7506                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7507                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7508                         assert_eq!(node_txn[0].output.len(), 1);
7509                         check_spends!(node_txn[0], revoked_txn[0]);
7510                         penalty_3 = node_txn[0].txid();
7511                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7512                         assert_ne!(penalty_3, penalty_2);
7513                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7514                         feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7515                         // Verify 25% bump heuristic
7516                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7517                         node_txn.clear();
7518                 }
7519         }
7520         assert_ne!(feerate_3, 0);
7521
7522         nodes[1].node.get_and_clear_pending_events();
7523         nodes[1].node.get_and_clear_pending_msg_events();
7524 }
7525
7526 #[test]
7527 fn test_bump_penalty_txn_on_revoked_htlcs() {
7528         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7529         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7530
7531         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7532         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7535         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7536
7537         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7538         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7539         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();
7540         let scorer = test_utils::TestScorer::new();
7541         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7542         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7543         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7544                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7545         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7546         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7547                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7548         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7549         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7550                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7551         let failed_payment_hash = send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000).1;
7552
7553         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7554         assert_eq!(revoked_local_txn[0].input.len(), 1);
7555         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7556
7557         // Revoke local commitment tx
7558         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7559
7560         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7561         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7562         check_closed_broadcast!(nodes[1], true);
7563         check_added_monitors!(nodes[1], 1);
7564         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7565         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7566
7567         let revoked_htlc_txn = {
7568                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7569                 assert_eq!(txn.len(), 2);
7570
7571                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7572                 assert_eq!(txn[0].input.len(), 1);
7573                 check_spends!(txn[0], revoked_local_txn[0]);
7574
7575                 assert_eq!(txn[1].input.len(), 1);
7576                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7577                 assert_eq!(txn[1].output.len(), 1);
7578                 check_spends!(txn[1], revoked_local_txn[0]);
7579
7580                 txn
7581         };
7582
7583         // Broadcast set of revoked txn on A
7584         let hash_128 = connect_blocks(&nodes[0], 40);
7585         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7586         connect_block(&nodes[0], &block_11);
7587         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7588         connect_block(&nodes[0], &block_129);
7589         let events = nodes[0].node.get_and_clear_pending_events();
7590         expect_pending_htlcs_forwardable_conditions(events[0..2].to_vec(), &[HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
7591         match events.last().unwrap() {
7592                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7593                 _ => panic!("Unexpected event"),
7594         }
7595         let first;
7596         let feerate_1;
7597         let penalty_txn;
7598         {
7599                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7600                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7601                 // Verify claim tx are spending revoked HTLC txn
7602
7603                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7604                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7605                 // which are included in the same block (they are broadcasted because we scan the
7606                 // transactions linearly and generate claims as we go, they likely should be removed in the
7607                 // future).
7608                 assert_eq!(node_txn[0].input.len(), 1);
7609                 check_spends!(node_txn[0], revoked_local_txn[0]);
7610                 assert_eq!(node_txn[1].input.len(), 1);
7611                 check_spends!(node_txn[1], revoked_local_txn[0]);
7612                 assert_eq!(node_txn[2].input.len(), 1);
7613                 check_spends!(node_txn[2], revoked_local_txn[0]);
7614
7615                 // Each of the three justice transactions claim a separate (single) output of the three
7616                 // available, which we check here:
7617                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7618                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7619                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7620
7621                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7622                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7623
7624                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7625                 // output, checked above).
7626                 assert_eq!(node_txn[3].input.len(), 2);
7627                 assert_eq!(node_txn[3].output.len(), 1);
7628                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7629
7630                 first = node_txn[3].txid();
7631                 // Store both feerates for later comparison
7632                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7633                 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7634                 penalty_txn = vec![node_txn[2].clone()];
7635                 node_txn.clear();
7636         }
7637
7638         // Connect one more block to see if bumped penalty are issued for HTLC txn
7639         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7640         connect_block(&nodes[0], &block_130);
7641         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7642         connect_block(&nodes[0], &block_131);
7643
7644         // Few more blocks to confirm penalty txn
7645         connect_blocks(&nodes[0], 4);
7646         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7647         let header_144 = connect_blocks(&nodes[0], 9);
7648         let node_txn = {
7649                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7650                 assert_eq!(node_txn.len(), 1);
7651
7652                 assert_eq!(node_txn[0].input.len(), 2);
7653                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7654                 // Verify bumped tx is different and 25% bump heuristic
7655                 assert_ne!(first, node_txn[0].txid());
7656                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7657                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7658                 assert!(feerate_2 * 100 > feerate_1 * 125);
7659                 let txn = vec![node_txn[0].clone()];
7660                 node_txn.clear();
7661                 txn
7662         };
7663         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7664         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7665         connect_blocks(&nodes[0], 20);
7666         {
7667                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7668                 // We verify than no new transaction has been broadcast because previously
7669                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7670                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7671                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7672                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7673                 // up bumped justice generation.
7674                 assert_eq!(node_txn.len(), 0);
7675                 node_txn.clear();
7676         }
7677         check_closed_broadcast!(nodes[0], true);
7678         check_added_monitors!(nodes[0], 1);
7679 }
7680
7681 #[test]
7682 fn test_bump_penalty_txn_on_remote_commitment() {
7683         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7684         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7685
7686         // Create 2 HTLCs
7687         // Provide preimage for one
7688         // Check aggregation
7689
7690         let chanmon_cfgs = create_chanmon_cfgs(2);
7691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7694
7695         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7696         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7697         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7698
7699         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7700         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7701         assert_eq!(remote_txn[0].output.len(), 4);
7702         assert_eq!(remote_txn[0].input.len(), 1);
7703         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7704
7705         // Claim a HTLC without revocation (provide B monitor with preimage)
7706         nodes[1].node.claim_funds(payment_preimage);
7707         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7708         mine_transaction(&nodes[1], &remote_txn[0]);
7709         check_added_monitors!(nodes[1], 2);
7710         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7711
7712         // One or more claim tx should have been broadcast, check it
7713         let timeout;
7714         let preimage;
7715         let preimage_bump;
7716         let feerate_timeout;
7717         let feerate_preimage;
7718         {
7719                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7720                 // 3 transactions including:
7721                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7722                 assert_eq!(node_txn.len(), 3);
7723                 assert_eq!(node_txn[0].input.len(), 1);
7724                 assert_eq!(node_txn[1].input.len(), 1);
7725                 assert_eq!(node_txn[2].input.len(), 1);
7726                 check_spends!(node_txn[0], remote_txn[0]);
7727                 check_spends!(node_txn[1], remote_txn[0]);
7728                 check_spends!(node_txn[2], remote_txn[0]);
7729
7730                 preimage = node_txn[0].txid();
7731                 let index = node_txn[0].input[0].previous_output.vout;
7732                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7733                 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7734
7735                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7736                         (node_txn[2].clone(), node_txn[1].clone())
7737                 } else {
7738                         (node_txn[1].clone(), node_txn[2].clone())
7739                 };
7740
7741                 preimage_bump = preimage_bump_tx;
7742                 check_spends!(preimage_bump, remote_txn[0]);
7743                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7744
7745                 timeout = timeout_tx.txid();
7746                 let index = timeout_tx.input[0].previous_output.vout;
7747                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7748                 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7749
7750                 node_txn.clear();
7751         };
7752         assert_ne!(feerate_timeout, 0);
7753         assert_ne!(feerate_preimage, 0);
7754
7755         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7756         connect_blocks(&nodes[1], 1);
7757         {
7758                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7759                 assert_eq!(node_txn.len(), 1);
7760                 assert_eq!(node_txn[0].input.len(), 1);
7761                 assert_eq!(preimage_bump.input.len(), 1);
7762                 check_spends!(node_txn[0], remote_txn[0]);
7763                 check_spends!(preimage_bump, remote_txn[0]);
7764
7765                 let index = preimage_bump.input[0].previous_output.vout;
7766                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7767                 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7768                 assert!(new_feerate * 100 > feerate_timeout * 125);
7769                 assert_ne!(timeout, preimage_bump.txid());
7770
7771                 let index = node_txn[0].input[0].previous_output.vout;
7772                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7773                 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7774                 assert!(new_feerate * 100 > feerate_preimage * 125);
7775                 assert_ne!(preimage, node_txn[0].txid());
7776
7777                 node_txn.clear();
7778         }
7779
7780         nodes[1].node.get_and_clear_pending_events();
7781         nodes[1].node.get_and_clear_pending_msg_events();
7782 }
7783
7784 #[test]
7785 fn test_counterparty_raa_skip_no_crash() {
7786         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7787         // commitment transaction, we would have happily carried on and provided them the next
7788         // commitment transaction based on one RAA forward. This would probably eventually have led to
7789         // channel closure, but it would not have resulted in funds loss. Still, our
7790         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7791         // check simply that the channel is closed in response to such an RAA, but don't check whether
7792         // we decide to punish our counterparty for revoking their funds (as we don't currently
7793         // implement that).
7794         let chanmon_cfgs = create_chanmon_cfgs(2);
7795         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7796         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7797         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7798         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7799
7800         let per_commitment_secret;
7801         let next_per_commitment_point;
7802         {
7803                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7804                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7805                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7806                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7807                 ).flatten().unwrap().get_signer();
7808
7809                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7810
7811                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7812                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7813                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7814
7815                 // Must revoke without gaps
7816                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7817                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7818
7819                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7820                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7821                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7822         }
7823
7824         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7825                 &msgs::RevokeAndACK {
7826                         channel_id,
7827                         per_commitment_secret,
7828                         next_per_commitment_point,
7829                         #[cfg(taproot)]
7830                         next_local_nonce: None,
7831                 });
7832         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7833         check_added_monitors!(nodes[1], 1);
7834         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7835                 , [nodes[0].node.get_our_node_id()], 100000);
7836 }
7837
7838 #[test]
7839 fn test_bump_txn_sanitize_tracking_maps() {
7840         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7841         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7842
7843         let chanmon_cfgs = create_chanmon_cfgs(2);
7844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7847
7848         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7849         // Lock HTLC in both directions
7850         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7851         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7852
7853         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7854         assert_eq!(revoked_local_txn[0].input.len(), 1);
7855         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7856
7857         // Revoke local commitment tx
7858         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7859
7860         // Broadcast set of revoked txn on A
7861         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7862         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7863         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7864
7865         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7866         check_closed_broadcast!(nodes[0], true);
7867         check_added_monitors!(nodes[0], 1);
7868         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7869         let penalty_txn = {
7870                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7871                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7872                 check_spends!(node_txn[0], revoked_local_txn[0]);
7873                 check_spends!(node_txn[1], revoked_local_txn[0]);
7874                 check_spends!(node_txn[2], revoked_local_txn[0]);
7875                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7876                 node_txn.clear();
7877                 penalty_txn
7878         };
7879         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7880         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7881         {
7882                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7883                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7884                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7885         }
7886 }
7887
7888 #[test]
7889 fn test_channel_conf_timeout() {
7890         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7891         // confirm within 2016 blocks, as recommended by BOLT 2.
7892         let chanmon_cfgs = create_chanmon_cfgs(2);
7893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7895         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7896
7897         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7898
7899         // The outbound node should wait forever for confirmation:
7900         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7901         // copied here instead of directly referencing the constant.
7902         connect_blocks(&nodes[0], 2016);
7903         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7904
7905         // The inbound node should fail the channel after exactly 2016 blocks
7906         connect_blocks(&nodes[1], 2015);
7907         check_added_monitors!(nodes[1], 0);
7908         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7909
7910         connect_blocks(&nodes[1], 1);
7911         check_added_monitors!(nodes[1], 1);
7912         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7913         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7914         assert_eq!(close_ev.len(), 1);
7915         match close_ev[0] {
7916                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7917                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7918                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7919                 },
7920                 _ => panic!("Unexpected event"),
7921         }
7922 }
7923
7924 #[test]
7925 fn test_override_channel_config() {
7926         let chanmon_cfgs = create_chanmon_cfgs(2);
7927         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7928         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7929         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7930
7931         // Node0 initiates a channel to node1 using the override config.
7932         let mut override_config = UserConfig::default();
7933         override_config.channel_handshake_config.our_to_self_delay = 200;
7934
7935         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7936
7937         // Assert the channel created by node0 is using the override config.
7938         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7939         assert_eq!(res.common_fields.channel_flags, 0);
7940         assert_eq!(res.common_fields.to_self_delay, 200);
7941 }
7942
7943 #[test]
7944 fn test_override_0msat_htlc_minimum() {
7945         let mut zero_config = UserConfig::default();
7946         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7947         let chanmon_cfgs = create_chanmon_cfgs(2);
7948         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7949         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7950         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7951
7952         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7953         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7954         assert_eq!(res.common_fields.htlc_minimum_msat, 1);
7955
7956         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7957         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7958         assert_eq!(res.common_fields.htlc_minimum_msat, 1);
7959 }
7960
7961 #[test]
7962 fn test_channel_update_has_correct_htlc_maximum_msat() {
7963         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7964         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7965         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7966         // 90% of the `channel_value`.
7967         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7968
7969         let mut config_30_percent = UserConfig::default();
7970         config_30_percent.channel_handshake_config.announced_channel = true;
7971         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7972         let mut config_50_percent = UserConfig::default();
7973         config_50_percent.channel_handshake_config.announced_channel = true;
7974         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7975         let mut config_95_percent = UserConfig::default();
7976         config_95_percent.channel_handshake_config.announced_channel = true;
7977         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7978         let mut config_100_percent = UserConfig::default();
7979         config_100_percent.channel_handshake_config.announced_channel = true;
7980         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7981
7982         let chanmon_cfgs = create_chanmon_cfgs(4);
7983         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7984         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)]);
7985         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7986
7987         let channel_value_satoshis = 100000;
7988         let channel_value_msat = channel_value_satoshis * 1000;
7989         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7990         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7991         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7992
7993         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7994         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7995
7996         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7997         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7998         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7999         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8000         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8001         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8002
8003         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8004         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8005         // `channel_value`.
8006         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8007         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8008         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8009         // `channel_value`.
8010         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8011 }
8012
8013 #[test]
8014 fn test_manually_accept_inbound_channel_request() {
8015         let mut manually_accept_conf = UserConfig::default();
8016         manually_accept_conf.manually_accept_inbound_channels = true;
8017         let chanmon_cfgs = create_chanmon_cfgs(2);
8018         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8019         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8020         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8021
8022         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();
8023         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8024
8025         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8026
8027         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8028         // accepting the inbound channel request.
8029         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8030
8031         let events = nodes[1].node.get_and_clear_pending_events();
8032         match events[0] {
8033                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8034                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8035                 }
8036                 _ => panic!("Unexpected event"),
8037         }
8038
8039         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8040         assert_eq!(accept_msg_ev.len(), 1);
8041
8042         match accept_msg_ev[0] {
8043                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8044                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8045                 }
8046                 _ => panic!("Unexpected event"),
8047         }
8048
8049         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8050
8051         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8052         assert_eq!(close_msg_ev.len(), 1);
8053
8054         let events = nodes[1].node.get_and_clear_pending_events();
8055         match events[0] {
8056                 Event::ChannelClosed { user_channel_id, .. } => {
8057                         assert_eq!(user_channel_id, 23);
8058                 }
8059                 _ => panic!("Unexpected event"),
8060         }
8061 }
8062
8063 #[test]
8064 fn test_manually_reject_inbound_channel_request() {
8065         let mut manually_accept_conf = UserConfig::default();
8066         manually_accept_conf.manually_accept_inbound_channels = true;
8067         let chanmon_cfgs = create_chanmon_cfgs(2);
8068         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8069         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8070         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8071
8072         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8073         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8074
8075         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8076
8077         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8078         // rejecting the inbound channel request.
8079         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8080
8081         let events = nodes[1].node.get_and_clear_pending_events();
8082         match events[0] {
8083                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8084                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8085                 }
8086                 _ => panic!("Unexpected event"),
8087         }
8088
8089         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8090         assert_eq!(close_msg_ev.len(), 1);
8091
8092         match close_msg_ev[0] {
8093                 MessageSendEvent::HandleError { ref node_id, .. } => {
8094                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8095                 }
8096                 _ => panic!("Unexpected event"),
8097         }
8098
8099         // There should be no more events to process, as the channel was never opened.
8100         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8101 }
8102
8103 #[test]
8104 fn test_can_not_accept_inbound_channel_twice() {
8105         let mut manually_accept_conf = UserConfig::default();
8106         manually_accept_conf.manually_accept_inbound_channels = true;
8107         let chanmon_cfgs = create_chanmon_cfgs(2);
8108         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8109         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8110         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8111
8112         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8113         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8114
8115         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8116
8117         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8118         // accepting the inbound channel request.
8119         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8120
8121         let events = nodes[1].node.get_and_clear_pending_events();
8122         match events[0] {
8123                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8124                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8125                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8126                         match api_res {
8127                                 Err(APIError::APIMisuseError { err }) => {
8128                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8129                                 },
8130                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8131                                 Err(e) => panic!("Unexpected Error {:?}", e),
8132                         }
8133                 }
8134                 _ => panic!("Unexpected event"),
8135         }
8136
8137         // Ensure that the channel wasn't closed after attempting to accept it twice.
8138         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8139         assert_eq!(accept_msg_ev.len(), 1);
8140
8141         match accept_msg_ev[0] {
8142                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8143                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8144                 }
8145                 _ => panic!("Unexpected event"),
8146         }
8147 }
8148
8149 #[test]
8150 fn test_can_not_accept_unknown_inbound_channel() {
8151         let chanmon_cfg = create_chanmon_cfgs(2);
8152         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8153         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8154         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8155
8156         let unknown_channel_id = ChannelId::new_zero();
8157         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8158         match api_res {
8159                 Err(APIError::APIMisuseError { err }) => {
8160                         assert_eq!(err, "No such channel awaiting to be accepted.");
8161                 },
8162                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8163                 Err(e) => panic!("Unexpected Error: {:?}", e),
8164         }
8165 }
8166
8167 #[test]
8168 fn test_onion_value_mpp_set_calculation() {
8169         // Test that we use the onion value `amt_to_forward` when
8170         // calculating whether we've reached the `total_msat` of an MPP
8171         // by having a routing node forward more than `amt_to_forward`
8172         // and checking that the receiving node doesn't generate
8173         // a PaymentClaimable event too early
8174         let node_count = 4;
8175         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8176         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8177         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8178         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8179
8180         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8181         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8182         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8183         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8184
8185         let total_msat = 100_000;
8186         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8187         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8188         let sample_path = route.paths.pop().unwrap();
8189
8190         let mut path_1 = sample_path.clone();
8191         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8192         path_1.hops[0].short_channel_id = chan_1_id;
8193         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8194         path_1.hops[1].short_channel_id = chan_3_id;
8195         path_1.hops[1].fee_msat = 100_000;
8196         route.paths.push(path_1);
8197
8198         let mut path_2 = sample_path.clone();
8199         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8200         path_2.hops[0].short_channel_id = chan_2_id;
8201         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8202         path_2.hops[1].short_channel_id = chan_4_id;
8203         path_2.hops[1].fee_msat = 1_000;
8204         route.paths.push(path_2);
8205
8206         // Send payment
8207         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8208         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8209                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8210         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8211                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8212         check_added_monitors!(nodes[0], expected_paths.len());
8213
8214         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8215         assert_eq!(events.len(), expected_paths.len());
8216
8217         // First path
8218         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8219         let mut payment_event = SendEvent::from_event(ev);
8220         let mut prev_node = &nodes[0];
8221
8222         for (idx, &node) in expected_paths[0].iter().enumerate() {
8223                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8224
8225                 if idx == 0 { // routing node
8226                         let session_priv = [3; 32];
8227                         let height = nodes[0].best_block_info().1;
8228                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8229                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8230                         let recipient_onion_fields = RecipientOnionFields::secret_only(our_payment_secret);
8231                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8232                                 &recipient_onion_fields, height + 1, &None).unwrap();
8233                         // Edit amt_to_forward to simulate the sender having set
8234                         // the final amount and the routing node taking less fee
8235                         if let msgs::OutboundOnionPayload::Receive {
8236                                 ref mut sender_intended_htlc_amt_msat, ..
8237                         } = onion_payloads[1] {
8238                                 *sender_intended_htlc_amt_msat = 99_000;
8239                         } else { panic!() }
8240                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8241                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8242                 }
8243
8244                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8245                 check_added_monitors!(node, 0);
8246                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8247                 expect_pending_htlcs_forwardable!(node);
8248
8249                 if idx == 0 {
8250                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8251                         assert_eq!(events_2.len(), 1);
8252                         check_added_monitors!(node, 1);
8253                         payment_event = SendEvent::from_event(events_2.remove(0));
8254                         assert_eq!(payment_event.msgs.len(), 1);
8255                 } else {
8256                         let events_2 = node.node.get_and_clear_pending_events();
8257                         assert!(events_2.is_empty());
8258                 }
8259
8260                 prev_node = node;
8261         }
8262
8263         // Second path
8264         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8265         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8266
8267         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8268 }
8269
8270 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8271
8272         let routing_node_count = msat_amounts.len();
8273         let node_count = routing_node_count + 2;
8274
8275         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8276         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8277         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8278         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8279
8280         let src_idx = 0;
8281         let dst_idx = 1;
8282
8283         // Create channels for each amount
8284         let mut expected_paths = Vec::with_capacity(routing_node_count);
8285         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8286         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8287         for i in 0..routing_node_count {
8288                 let routing_node = 2 + i;
8289                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8290                 src_chan_ids.push(src_chan_id);
8291                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8292                 dst_chan_ids.push(dst_chan_id);
8293                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8294                 expected_paths.push(path);
8295         }
8296         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8297
8298         // Create a route for each amount
8299         let example_amount = 100000;
8300         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);
8301         let sample_path = route.paths.pop().unwrap();
8302         for i in 0..routing_node_count {
8303                 let routing_node = 2 + i;
8304                 let mut path = sample_path.clone();
8305                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8306                 path.hops[0].short_channel_id = src_chan_ids[i];
8307                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8308                 path.hops[1].short_channel_id = dst_chan_ids[i];
8309                 path.hops[1].fee_msat = msat_amounts[i];
8310                 route.paths.push(path);
8311         }
8312
8313         // Send payment with manually set total_msat
8314         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8315         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8316                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8317         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8318                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8319         check_added_monitors!(nodes[src_idx], expected_paths.len());
8320
8321         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8322         assert_eq!(events.len(), expected_paths.len());
8323         let mut amount_received = 0;
8324         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8325                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8326
8327                 let current_path_amount = msat_amounts[path_idx];
8328                 amount_received += current_path_amount;
8329                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8330                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8331         }
8332
8333         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8334 }
8335
8336 #[test]
8337 fn test_overshoot_mpp() {
8338         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8339         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8340 }
8341
8342 #[test]
8343 fn test_simple_mpp() {
8344         // Simple test of sending a multi-path payment.
8345         let chanmon_cfgs = create_chanmon_cfgs(4);
8346         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8347         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8348         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8349
8350         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8351         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8352         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8353         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8354
8355         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8356         let path = route.paths[0].clone();
8357         route.paths.push(path);
8358         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8359         route.paths[0].hops[0].short_channel_id = chan_1_id;
8360         route.paths[0].hops[1].short_channel_id = chan_3_id;
8361         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8362         route.paths[1].hops[0].short_channel_id = chan_2_id;
8363         route.paths[1].hops[1].short_channel_id = chan_4_id;
8364         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8365         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8366 }
8367
8368 #[test]
8369 fn test_preimage_storage() {
8370         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8371         let chanmon_cfgs = create_chanmon_cfgs(2);
8372         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8373         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8374         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8375
8376         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8377
8378         {
8379                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8380                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8381                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8382                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8383                 check_added_monitors!(nodes[0], 1);
8384                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8385                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8386                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8387                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8388         }
8389         // Note that after leaving the above scope we have no knowledge of any arguments or return
8390         // values from previous calls.
8391         expect_pending_htlcs_forwardable!(nodes[1]);
8392         let events = nodes[1].node.get_and_clear_pending_events();
8393         assert_eq!(events.len(), 1);
8394         match events[0] {
8395                 Event::PaymentClaimable { ref purpose, .. } => {
8396                         match &purpose {
8397                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => {
8398                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8399                                 },
8400                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
8401                         }
8402                 },
8403                 _ => panic!("Unexpected event"),
8404         }
8405 }
8406
8407 #[test]
8408 fn test_bad_secret_hash() {
8409         // Simple test of unregistered payment hash/invalid payment secret handling
8410         let chanmon_cfgs = create_chanmon_cfgs(2);
8411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8413         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8414
8415         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8416
8417         let random_payment_hash = PaymentHash([42; 32]);
8418         let random_payment_secret = PaymentSecret([43; 32]);
8419         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8420         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8421
8422         // All the below cases should end up being handled exactly identically, so we macro the
8423         // resulting events.
8424         macro_rules! handle_unknown_invalid_payment_data {
8425                 ($payment_hash: expr) => {
8426                         check_added_monitors!(nodes[0], 1);
8427                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8428                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8429                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8430                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8431
8432                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8433                         // again to process the pending backwards-failure of the HTLC
8434                         expect_pending_htlcs_forwardable!(nodes[1]);
8435                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8436                         check_added_monitors!(nodes[1], 1);
8437
8438                         // We should fail the payment back
8439                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8440                         match events.pop().unwrap() {
8441                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8442                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8443                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8444                                 },
8445                                 _ => panic!("Unexpected event"),
8446                         }
8447                 }
8448         }
8449
8450         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8451         // Error data is the HTLC value (100,000) and current block height
8452         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8453
8454         // Send a payment with the right payment hash but the wrong payment secret
8455         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8456                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8457         handle_unknown_invalid_payment_data!(our_payment_hash);
8458         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8459
8460         // Send a payment with a random payment hash, but the right payment secret
8461         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8462                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8463         handle_unknown_invalid_payment_data!(random_payment_hash);
8464         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8465
8466         // Send a payment with a random payment hash and random payment secret
8467         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8468                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8469         handle_unknown_invalid_payment_data!(random_payment_hash);
8470         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8471 }
8472
8473 #[test]
8474 fn test_update_err_monitor_lockdown() {
8475         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8476         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8477         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8478         // error.
8479         //
8480         // This scenario may happen in a watchtower setup, where watchtower process a block height
8481         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8482         // commitment at same time.
8483
8484         let chanmon_cfgs = create_chanmon_cfgs(2);
8485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8487         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8488
8489         // Create some initial channel
8490         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8491         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8492
8493         // Rebalance the network to generate htlc in the two directions
8494         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8495
8496         // Route a HTLC from node 0 to node 1 (but don't settle)
8497         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8498
8499         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8500         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8501         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8502         let persister = test_utils::TestPersister::new();
8503         let watchtower = {
8504                 let new_monitor = {
8505                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8506                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8507                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8508                         assert!(new_monitor == *monitor);
8509                         new_monitor
8510                 };
8511                 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);
8512                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8513                 watchtower
8514         };
8515         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8516         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8517         // transaction lock time requirements here.
8518         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8519         watchtower.chain_monitor.block_connected(&block, 200);
8520
8521         // Try to update ChannelMonitor
8522         nodes[1].node.claim_funds(preimage);
8523         check_added_monitors!(nodes[1], 1);
8524         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8525
8526         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8527         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8528         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8529         {
8530                 let mut node_0_per_peer_lock;
8531                 let mut node_0_peer_state_lock;
8532                 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) {
8533                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8534                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8535                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8536                         } else { assert!(false); }
8537                 } else {
8538                         assert!(false);
8539                 }
8540         }
8541         // Our local monitor is in-sync and hasn't processed yet timeout
8542         check_added_monitors!(nodes[0], 1);
8543         let events = nodes[0].node.get_and_clear_pending_events();
8544         assert_eq!(events.len(), 1);
8545 }
8546
8547 #[test]
8548 fn test_concurrent_monitor_claim() {
8549         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8550         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8551         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8552         // state N+1 confirms. Alice claims output from state N+1.
8553
8554         let chanmon_cfgs = create_chanmon_cfgs(2);
8555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8557         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8558
8559         // Create some initial channel
8560         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8561         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8562
8563         // Rebalance the network to generate htlc in the two directions
8564         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8565
8566         // Route a HTLC from node 0 to node 1 (but don't settle)
8567         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8568
8569         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8570         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8571         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8572         let persister = test_utils::TestPersister::new();
8573         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8574                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8575         );
8576         let watchtower_alice = {
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), &alice_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         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8589         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8590         // requirements here.
8591         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8592         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8593         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8594
8595         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8596         {
8597                 let mut txn = alice_broadcaster.txn_broadcast();
8598                 assert_eq!(txn.len(), 2);
8599                 check_spends!(txn[0], chan_1.3);
8600                 check_spends!(txn[1], txn[0]);
8601         };
8602
8603         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8604         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8605         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8606         let persister = test_utils::TestPersister::new();
8607         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8608         let watchtower_bob = {
8609                 let new_monitor = {
8610                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8611                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8612                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8613                         assert!(new_monitor == *monitor);
8614                         new_monitor
8615                 };
8616                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8617                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8618                 watchtower
8619         };
8620         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8621
8622         // Route another payment to generate another update with still previous HTLC pending
8623         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8624         nodes[1].node.send_payment_with_route(&route, payment_hash,
8625                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8626         check_added_monitors!(nodes[1], 1);
8627
8628         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8629         assert_eq!(updates.update_add_htlcs.len(), 1);
8630         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8631         {
8632                 let mut node_0_per_peer_lock;
8633                 let mut node_0_peer_state_lock;
8634                 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) {
8635                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8636                                 // Watchtower Alice should already have seen the block and reject the update
8637                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8638                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8639                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8640                         } else { assert!(false); }
8641                 } else {
8642                         assert!(false);
8643                 }
8644         }
8645         // Our local monitor is in-sync and hasn't processed yet timeout
8646         check_added_monitors!(nodes[0], 1);
8647
8648         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8649         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8650
8651         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8652         let bob_state_y;
8653         {
8654                 let mut txn = bob_broadcaster.txn_broadcast();
8655                 assert_eq!(txn.len(), 2);
8656                 bob_state_y = txn.remove(0);
8657         };
8658
8659         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8660         let height = HTLC_TIMEOUT_BROADCAST + 1;
8661         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8662         check_closed_broadcast(&nodes[0], 1, true);
8663         check_closed_event!(&nodes[0], 1, ClosureReason::HTLCsTimedOut, false,
8664                 [nodes[1].node.get_our_node_id()], 100000);
8665         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8666         check_added_monitors(&nodes[0], 1);
8667         {
8668                 let htlc_txn = alice_broadcaster.txn_broadcast();
8669                 assert_eq!(htlc_txn.len(), 1);
8670                 check_spends!(htlc_txn[0], bob_state_y);
8671         }
8672 }
8673
8674 #[test]
8675 fn test_pre_lockin_no_chan_closed_update() {
8676         // Test that if a peer closes a channel in response to a funding_created message we don't
8677         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8678         // message).
8679         //
8680         // Doing so would imply a channel monitor update before the initial channel monitor
8681         // registration, violating our API guarantees.
8682         //
8683         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8684         // then opening a second channel with the same funding output as the first (which is not
8685         // rejected because the first channel does not exist in the ChannelManager) and closing it
8686         // before receiving funding_signed.
8687         let chanmon_cfgs = create_chanmon_cfgs(2);
8688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8690         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8691
8692         // Create an initial channel
8693         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8694         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8695         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8696         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8697         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8698
8699         // Move the first channel through the funding flow...
8700         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8701
8702         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8703         check_added_monitors!(nodes[0], 0);
8704
8705         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8706         let channel_id = ChannelId::v1_from_funding_outpoint(crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index });
8707         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8708         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8709         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8710                 [nodes[1].node.get_our_node_id()], 100000);
8711 }
8712
8713 #[test]
8714 fn test_htlc_no_detection() {
8715         // This test is a mutation to underscore the detection logic bug we had
8716         // before #653. HTLC value routed is above the remaining balance, thus
8717         // inverting HTLC and `to_remote` output. HTLC will come second and
8718         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8719         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8720         // outputs order detection for correct spending children filtring.
8721
8722         let chanmon_cfgs = create_chanmon_cfgs(2);
8723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8725         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8726
8727         // Create some initial channels
8728         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8729
8730         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8731         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8732         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8733         assert_eq!(local_txn[0].input.len(), 1);
8734         assert_eq!(local_txn[0].output.len(), 3);
8735         check_spends!(local_txn[0], chan_1.3);
8736
8737         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8738         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8739         connect_block(&nodes[0], &block);
8740         // We deliberately connect the local tx twice as this should provoke a failure calling
8741         // this test before #653 fix.
8742         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8743         check_closed_broadcast!(nodes[0], true);
8744         check_added_monitors!(nodes[0], 1);
8745         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8746         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8747
8748         let htlc_timeout = {
8749                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8750                 assert_eq!(node_txn.len(), 1);
8751                 assert_eq!(node_txn[0].input.len(), 1);
8752                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8753                 check_spends!(node_txn[0], local_txn[0]);
8754                 node_txn[0].clone()
8755         };
8756
8757         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8758         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8759         expect_payment_failed!(nodes[0], our_payment_hash, false);
8760 }
8761
8762 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8763         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8764         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8765         // Carol, Alice would be the upstream node, and Carol the downstream.)
8766         //
8767         // Steps of the test:
8768         // 1) Alice sends a HTLC to Carol through Bob.
8769         // 2) Carol doesn't settle the HTLC.
8770         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8771         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8772         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8773         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8774         // 5) Carol release the preimage to Bob off-chain.
8775         // 6) Bob claims the offered output on the broadcasted commitment.
8776         let chanmon_cfgs = create_chanmon_cfgs(3);
8777         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8778         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8779         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8780
8781         // Create some initial channels
8782         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8783         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8784
8785         // Steps (1) and (2):
8786         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8787         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8788
8789         // Check that Alice's commitment transaction now contains an output for this HTLC.
8790         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8791         check_spends!(alice_txn[0], chan_ab.3);
8792         assert_eq!(alice_txn[0].output.len(), 2);
8793         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8794         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8795         assert_eq!(alice_txn.len(), 2);
8796
8797         // Steps (3) and (4):
8798         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8799         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8800         let mut force_closing_node = 0; // Alice force-closes
8801         let mut counterparty_node = 1; // Bob if Alice force-closes
8802
8803         // Bob force-closes
8804         if !broadcast_alice {
8805                 force_closing_node = 1;
8806                 counterparty_node = 0;
8807         }
8808         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8809         check_closed_broadcast!(nodes[force_closing_node], true);
8810         check_added_monitors!(nodes[force_closing_node], 1);
8811         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8812         if go_onchain_before_fulfill {
8813                 let txn_to_broadcast = match broadcast_alice {
8814                         true => alice_txn.clone(),
8815                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8816                 };
8817                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8818                 if broadcast_alice {
8819                         check_closed_broadcast!(nodes[1], true);
8820                         check_added_monitors!(nodes[1], 1);
8821                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8822                 }
8823         }
8824
8825         // Step (5):
8826         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8827         // process of removing the HTLC from their commitment transactions.
8828         nodes[2].node.claim_funds(payment_preimage);
8829         check_added_monitors!(nodes[2], 1);
8830         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8831
8832         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8833         assert!(carol_updates.update_add_htlcs.is_empty());
8834         assert!(carol_updates.update_fail_htlcs.is_empty());
8835         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8836         assert!(carol_updates.update_fee.is_none());
8837         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8838
8839         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8840         let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8841         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8842         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8843         if !go_onchain_before_fulfill && broadcast_alice {
8844                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8845                 assert_eq!(events.len(), 1);
8846                 match events[0] {
8847                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8848                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8849                         },
8850                         _ => panic!("Unexpected event"),
8851                 };
8852         }
8853         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8854         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8855         // Carol<->Bob's updated commitment transaction info.
8856         check_added_monitors!(nodes[1], 2);
8857
8858         let events = nodes[1].node.get_and_clear_pending_msg_events();
8859         assert_eq!(events.len(), 2);
8860         let bob_revocation = match events[0] {
8861                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8862                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8863                         (*msg).clone()
8864                 },
8865                 _ => panic!("Unexpected event"),
8866         };
8867         let bob_updates = match events[1] {
8868                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8869                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8870                         (*updates).clone()
8871                 },
8872                 _ => panic!("Unexpected event"),
8873         };
8874
8875         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8876         check_added_monitors!(nodes[2], 1);
8877         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8878         check_added_monitors!(nodes[2], 1);
8879
8880         let events = nodes[2].node.get_and_clear_pending_msg_events();
8881         assert_eq!(events.len(), 1);
8882         let carol_revocation = match events[0] {
8883                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8884                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8885                         (*msg).clone()
8886                 },
8887                 _ => panic!("Unexpected event"),
8888         };
8889         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8890         check_added_monitors!(nodes[1], 1);
8891
8892         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8893         // here's where we put said channel's commitment tx on-chain.
8894         let mut txn_to_broadcast = alice_txn.clone();
8895         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8896         if !go_onchain_before_fulfill {
8897                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8898                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8899                 if broadcast_alice {
8900                         check_closed_broadcast!(nodes[1], true);
8901                         check_added_monitors!(nodes[1], 1);
8902                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8903                 }
8904                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8905                 if broadcast_alice {
8906                         assert_eq!(bob_txn.len(), 1);
8907                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8908                 } else {
8909                         if nodes[1].connect_style.borrow().updates_best_block_first() {
8910                                 assert_eq!(bob_txn.len(), 3);
8911                                 assert_eq!(bob_txn[0].txid(), bob_txn[1].txid());
8912                         } else {
8913                                 assert_eq!(bob_txn.len(), 2);
8914                         }
8915                         check_spends!(bob_txn[0], chan_ab.3);
8916                 }
8917         }
8918
8919         // Step (6):
8920         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8921         // broadcasted commitment transaction.
8922         {
8923                 let script_weight = match broadcast_alice {
8924                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8925                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8926                 };
8927                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8928                 // Bob force-closed and broadcasts the commitment transaction along with a
8929                 // HTLC-output-claiming transaction.
8930                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8931                 if broadcast_alice {
8932                         assert_eq!(bob_txn.len(), 1);
8933                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8934                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8935                 } else {
8936                         assert_eq!(bob_txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
8937                         let htlc_tx = bob_txn.pop().unwrap();
8938                         check_spends!(htlc_tx, txn_to_broadcast[0]);
8939                         assert_eq!(htlc_tx.input[0].witness.last().unwrap().len(), script_weight);
8940                 }
8941         }
8942 }
8943
8944 #[test]
8945 fn test_onchain_htlc_settlement_after_close() {
8946         do_test_onchain_htlc_settlement_after_close(true, true);
8947         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8948         do_test_onchain_htlc_settlement_after_close(true, false);
8949         do_test_onchain_htlc_settlement_after_close(false, false);
8950 }
8951
8952 #[test]
8953 fn test_duplicate_temporary_channel_id_from_different_peers() {
8954         // Tests that we can accept two different `OpenChannel` requests with the same
8955         // `temporary_channel_id`, as long as they are from different peers.
8956         let chanmon_cfgs = create_chanmon_cfgs(3);
8957         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8958         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8959         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8960
8961         // Create an first channel channel
8962         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8963         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8964
8965         // Create an second channel
8966         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8967         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8968
8969         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8970         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8971         open_chan_msg_chan_2_0.common_fields.temporary_channel_id = open_chan_msg_chan_1_0.common_fields.temporary_channel_id;
8972
8973         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8974         // `temporary_channel_id` as they are from different peers.
8975         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8976         {
8977                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8978                 assert_eq!(events.len(), 1);
8979                 match &events[0] {
8980                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8981                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8982                                 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
8983                         },
8984                         _ => panic!("Unexpected event"),
8985                 }
8986         }
8987
8988         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8989         {
8990                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8991                 assert_eq!(events.len(), 1);
8992                 match &events[0] {
8993                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8994                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8995                                 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
8996                         },
8997                         _ => panic!("Unexpected event"),
8998                 }
8999         }
9000 }
9001
9002 #[test]
9003 fn test_peer_funding_sidechannel() {
9004         // Test that if a peer somehow learns which txid we'll use for our channel funding before we
9005         // receive `funding_transaction_generated` the peer cannot cause us to crash. We'd previously
9006         // assumed that LDK would receive `funding_transaction_generated` prior to our peer learning
9007         // the txid and panicked if the peer tried to open a redundant channel to us with the same
9008         // funding outpoint.
9009         //
9010         // While this assumption is generally safe, some users may have out-of-band protocols where
9011         // they notify their LSP about a funding outpoint first, or this may be violated in the future
9012         // with collaborative transaction construction protocols, i.e. dual-funding.
9013         let chanmon_cfgs = create_chanmon_cfgs(3);
9014         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9015         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9016         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9017
9018         let temp_chan_id_ab = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9019         let temp_chan_id_ca = exchange_open_accept_chan(&nodes[2], &nodes[0], 1_000_000, 0);
9020
9021         let (_, tx, funding_output) =
9022                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9023
9024         let cs_funding_events = nodes[2].node.get_and_clear_pending_events();
9025         assert_eq!(cs_funding_events.len(), 1);
9026         match cs_funding_events[0] {
9027                 Event::FundingGenerationReady { .. } => {}
9028                 _ => panic!("Unexpected event {:?}", cs_funding_events),
9029         }
9030
9031         nodes[2].node.funding_transaction_generated_unchecked(&temp_chan_id_ca, &nodes[0].node.get_our_node_id(), tx.clone(), funding_output.index).unwrap();
9032         let funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[0].node.get_our_node_id());
9033         nodes[0].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9034         get_event_msg!(nodes[0], MessageSendEvent::SendFundingSigned, nodes[2].node.get_our_node_id());
9035         expect_channel_pending_event(&nodes[0], &nodes[2].node.get_our_node_id());
9036         check_added_monitors!(nodes[0], 1);
9037
9038         let res = nodes[0].node.funding_transaction_generated(&temp_chan_id_ab, &nodes[1].node.get_our_node_id(), tx.clone());
9039         let err_msg = format!("{:?}", res.unwrap_err());
9040         assert!(err_msg.contains("An existing channel using outpoint "));
9041         assert!(err_msg.contains(" is open with peer"));
9042         // Even though the last funding_transaction_generated errored, it still generated a
9043         // SendFundingCreated. However, when the peer responds with a funding_signed it will send the
9044         // appropriate error message.
9045         let as_funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9046         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &as_funding_created);
9047         check_added_monitors!(nodes[1], 1);
9048         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9049         let reason = ClosureReason::ProcessingError { err: format!("An existing channel using outpoint {} is open with peer {}", funding_output, nodes[2].node.get_our_node_id()), };
9050         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(ChannelId::v1_from_funding_outpoint(funding_output), true, reason)]);
9051
9052         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9053         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9054         get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9055 }
9056
9057 #[test]
9058 fn test_duplicate_conflicting_funding_from_second_peer() {
9059         // Test that if a user tries to fund a channel with a funding outpoint they'd previously used
9060         // we don't try to remove the previous ChannelMonitor. This is largely a test to ensure we
9061         // don't regress in the fuzzer, as such funding getting passed our outpoint-matches checks
9062         // implies the user (and our counterparty) has reused cryptographic keys across channels, which
9063         // we require the user not do.
9064         let chanmon_cfgs = create_chanmon_cfgs(4);
9065         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9066         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9067         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9068
9069         let temp_chan_id = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9070
9071         let (_, tx, funding_output) =
9072                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9073
9074         // Now that we have a funding outpoint, create a dummy `ChannelMonitor` and insert it into
9075         // nodes[0]'s ChainMonitor so that the initial `ChannelMonitor` write fails.
9076         let dummy_chan_id = create_chan_between_nodes(&nodes[2], &nodes[3]).3;
9077         let dummy_monitor = get_monitor!(nodes[2], dummy_chan_id).clone();
9078         nodes[0].chain_monitor.chain_monitor.watch_channel(funding_output, dummy_monitor).unwrap();
9079
9080         nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9081
9082         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9083         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9084         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9085         check_added_monitors!(nodes[1], 1);
9086         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9087
9088         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9089         // At this point, the channel should be closed, after having generated one monitor write (the
9090         // watch_channel call which failed), but zero monitor updates.
9091         check_added_monitors!(nodes[0], 1);
9092         get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9093         let err_reason = ClosureReason::ProcessingError { err: "Channel funding outpoint was a duplicate".to_owned() };
9094         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(funding_signed_msg.channel_id, true, err_reason)]);
9095 }
9096
9097 #[test]
9098 fn test_duplicate_funding_err_in_funding() {
9099         // Test that if we have a live channel with one peer, then another peer comes along and tries
9100         // to create a second channel with the same txid we'll fail and not overwrite the
9101         // outpoint_to_peer map in `ChannelManager`.
9102         //
9103         // This was previously broken.
9104         let chanmon_cfgs = create_chanmon_cfgs(3);
9105         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9106         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9107         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9108
9109         let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
9110         let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
9111         assert_eq!(ChannelId::v1_from_funding_outpoint(real_chan_funding_txo), real_channel_id);
9112
9113         nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9114         let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9115         let node_c_temp_chan_id = open_chan_msg.common_fields.temporary_channel_id;
9116         open_chan_msg.common_fields.temporary_channel_id = real_channel_id;
9117         nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
9118         let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
9119         accept_chan_msg.common_fields.temporary_channel_id = node_c_temp_chan_id;
9120         nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
9121
9122         // Now that we have a second channel with the same funding txo, send a bogus funding message
9123         // and let nodes[1] remove the inbound channel.
9124         let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9125
9126         nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9127
9128         let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9129         funding_created_msg.temporary_channel_id = real_channel_id;
9130         // Make the signature invalid by changing the funding output
9131         funding_created_msg.funding_output_index += 10;
9132         nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9133         get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9134         let err = "Invalid funding_created signature from peer".to_owned();
9135         let reason = ClosureReason::ProcessingError { err };
9136         let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9137         check_closed_events(&nodes[1], &[expected_closing]);
9138
9139         assert_eq!(
9140                 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9141                 nodes[0].node.get_our_node_id()
9142         );
9143 }
9144
9145 #[test]
9146 fn test_duplicate_chan_id() {
9147         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9148         // already open we reject it and keep the old channel.
9149         //
9150         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9151         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9152         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9153         // updating logic for the existing channel.
9154         let chanmon_cfgs = create_chanmon_cfgs(2);
9155         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9156         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9157         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9158
9159         // Create an initial channel
9160         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9161         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9162         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9163         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()));
9164
9165         // Try to create a second channel with the same temporary_channel_id as the first and check
9166         // that it is rejected.
9167         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9168         {
9169                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9170                 assert_eq!(events.len(), 1);
9171                 match events[0] {
9172                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9173                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9174                                 // first (valid) and second (invalid) channels are closed, given they both have
9175                                 // the same non-temporary channel_id. However, currently we do not, so we just
9176                                 // move forward with it.
9177                                 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9178                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9179                         },
9180                         _ => panic!("Unexpected event"),
9181                 }
9182         }
9183
9184         // Move the first channel through the funding flow...
9185         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9186
9187         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9188         check_added_monitors!(nodes[0], 0);
9189
9190         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9191         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9192         {
9193                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9194                 assert_eq!(added_monitors.len(), 1);
9195                 assert_eq!(added_monitors[0].0, funding_output);
9196                 added_monitors.clear();
9197         }
9198         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9199
9200         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9201
9202         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9203         let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
9204
9205         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9206         // temporary one).
9207
9208         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9209         // Technically this is allowed by the spec, but we don't support it and there's little reason
9210         // to. Still, it shouldn't cause any other issues.
9211         open_chan_msg.common_fields.temporary_channel_id = channel_id;
9212         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9213         {
9214                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9215                 assert_eq!(events.len(), 1);
9216                 match events[0] {
9217                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9218                                 // Technically, at this point, nodes[1] would be justified in thinking both
9219                                 // channels are closed, but currently we do not, so we just move forward with it.
9220                                 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9221                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9222                         },
9223                         _ => panic!("Unexpected event"),
9224                 }
9225         }
9226
9227         // Now try to create a second channel which has a duplicate funding output.
9228         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9229         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9230         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9231         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()));
9232         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9233
9234         let funding_created = {
9235                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9236                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9237                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9238                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9239                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9240                 // channelmanager in a possibly nonsense state instead).
9241                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.common_fields.temporary_channel_id).unwrap() {
9242                         ChannelPhase::UnfundedOutboundV1(mut chan) => {
9243                                 let logger = test_utils::TestLogger::new();
9244                                 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9245                         },
9246                         _ => panic!("Unexpected ChannelPhase variant"),
9247                 }.unwrap()
9248         };
9249         check_added_monitors!(nodes[0], 0);
9250         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9251         // At this point we'll look up if the channel_id is present and immediately fail the channel
9252         // without trying to persist the `ChannelMonitor`.
9253         check_added_monitors!(nodes[1], 0);
9254
9255         check_closed_events(&nodes[1], &[
9256                 ExpectedCloseEvent::from_id_reason(funding_created.temporary_channel_id, false, ClosureReason::ProcessingError {
9257                         err: "Already had channel with the new channel_id".to_owned()
9258                 })
9259         ]);
9260
9261         // ...still, nodes[1] will reject the duplicate channel.
9262         {
9263                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9264                 assert_eq!(events.len(), 1);
9265                 match events[0] {
9266                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9267                                 // Technically, at this point, nodes[1] would be justified in thinking both
9268                                 // channels are closed, but currently we do not, so we just move forward with it.
9269                                 assert_eq!(msg.channel_id, channel_id);
9270                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9271                         },
9272                         _ => panic!("Unexpected event"),
9273                 }
9274         }
9275
9276         // finally, finish creating the original channel and send a payment over it to make sure
9277         // everything is functional.
9278         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9279         {
9280                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9281                 assert_eq!(added_monitors.len(), 1);
9282                 assert_eq!(added_monitors[0].0, funding_output);
9283                 added_monitors.clear();
9284         }
9285         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9286
9287         let events_4 = nodes[0].node.get_and_clear_pending_events();
9288         assert_eq!(events_4.len(), 0);
9289         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9290         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9291
9292         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9293         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9294         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9295
9296         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9297 }
9298
9299 #[test]
9300 fn test_error_chans_closed() {
9301         // Test that we properly handle error messages, closing appropriate channels.
9302         //
9303         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9304         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9305         // we can test various edge cases around it to ensure we don't regress.
9306         let chanmon_cfgs = create_chanmon_cfgs(3);
9307         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9308         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9309         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9310
9311         // Create some initial channels
9312         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9313         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9314         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9315
9316         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9317         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9318         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9319
9320         // Closing a channel from a different peer has no effect
9321         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9322         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9323
9324         // Closing one channel doesn't impact others
9325         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9326         check_added_monitors!(nodes[0], 1);
9327         check_closed_broadcast!(nodes[0], false);
9328         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9329                 [nodes[1].node.get_our_node_id()], 100000);
9330         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9331         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9332         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);
9333         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);
9334
9335         // A null channel ID should close all channels
9336         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9337         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9338         check_added_monitors!(nodes[0], 2);
9339         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9340                 [nodes[1].node.get_our_node_id(); 2], 100000);
9341         let events = nodes[0].node.get_and_clear_pending_msg_events();
9342         assert_eq!(events.len(), 2);
9343         match events[0] {
9344                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9345                         assert_eq!(msg.contents.flags & 2, 2);
9346                 },
9347                 _ => panic!("Unexpected event"),
9348         }
9349         match events[1] {
9350                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9351                         assert_eq!(msg.contents.flags & 2, 2);
9352                 },
9353                 _ => panic!("Unexpected event"),
9354         }
9355         // Note that at this point users of a standard PeerHandler will end up calling
9356         // peer_disconnected.
9357         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9358         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9359
9360         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9361         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9362         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9363 }
9364
9365 #[test]
9366 fn test_invalid_funding_tx() {
9367         // Test that we properly handle invalid funding transactions sent to us from a peer.
9368         //
9369         // Previously, all other major lightning implementations had failed to properly sanitize
9370         // funding transactions from their counterparties, leading to a multi-implementation critical
9371         // security vulnerability (though we always sanitized properly, we've previously had
9372         // un-released crashes in the sanitization process).
9373         //
9374         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9375         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9376         // gave up on it. We test this here by generating such a transaction.
9377         let chanmon_cfgs = create_chanmon_cfgs(2);
9378         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9379         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9380         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9381
9382         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9383         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()));
9384         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()));
9385
9386         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9387
9388         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9389         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9390         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9391         // its length.
9392         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9393         let wit_program_script: ScriptBuf = wit_program.into();
9394         for output in tx.output.iter_mut() {
9395                 // Make the confirmed funding transaction have a bogus script_pubkey
9396                 output.script_pubkey = ScriptBuf::new_v0_p2wsh(&wit_program_script.wscript_hash());
9397         }
9398
9399         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9400         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()));
9401         check_added_monitors!(nodes[1], 1);
9402         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9403
9404         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()));
9405         check_added_monitors!(nodes[0], 1);
9406         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9407
9408         let events_1 = nodes[0].node.get_and_clear_pending_events();
9409         assert_eq!(events_1.len(), 0);
9410
9411         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9412         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9413         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9414
9415         let expected_err = "funding tx had wrong script/value or output index";
9416         confirm_transaction_at(&nodes[1], &tx, 1);
9417         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9418                 [nodes[0].node.get_our_node_id()], 100000);
9419         check_added_monitors!(nodes[1], 1);
9420         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9421         assert_eq!(events_2.len(), 1);
9422         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9423                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9424                 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9425                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9426                 } else { panic!(); }
9427         } else { panic!(); }
9428         assert_eq!(nodes[1].node.list_channels().len(), 0);
9429
9430         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9431         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9432         // as its not 32 bytes long.
9433         let mut spend_tx = Transaction {
9434                 version: 2i32, lock_time: LockTime::ZERO,
9435                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9436                         previous_output: BitcoinOutPoint {
9437                                 txid: tx.txid(),
9438                                 vout: idx as u32,
9439                         },
9440                         script_sig: ScriptBuf::new(),
9441                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9442                         witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9443                 }).collect(),
9444                 output: vec![TxOut {
9445                         value: 1000,
9446                         script_pubkey: ScriptBuf::new(),
9447                 }]
9448         };
9449         check_spends!(spend_tx, tx);
9450         mine_transaction(&nodes[1], &spend_tx);
9451 }
9452
9453 #[test]
9454 fn test_coinbase_funding_tx() {
9455         // Miners are able to fund channels directly from coinbase transactions, however
9456         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9457         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9458         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9459         //
9460         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9461         // immediately operational after opening.
9462         let chanmon_cfgs = create_chanmon_cfgs(2);
9463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9465         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9466
9467         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9468         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9469
9470         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9471         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9472
9473         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9474
9475         // Create the coinbase funding transaction.
9476         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9477
9478         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9479         check_added_monitors!(nodes[0], 0);
9480         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9481
9482         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9483         check_added_monitors!(nodes[1], 1);
9484         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9485
9486         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9487
9488         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9489         check_added_monitors!(nodes[0], 1);
9490
9491         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9492         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9493
9494         // Starting at height 0, we "confirm" the coinbase at height 1.
9495         confirm_transaction_at(&nodes[0], &tx, 1);
9496         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9497         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9498         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9499         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9500         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9501         connect_blocks(&nodes[0], 1);
9502         // There should now be a `channel_ready` which can be handled.
9503         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()));
9504
9505         confirm_transaction_at(&nodes[1], &tx, 1);
9506         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9507         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9508         connect_blocks(&nodes[1], 1);
9509         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9510         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9511 }
9512
9513 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9514         // In the first version of the chain::Confirm interface, after a refactor was made to not
9515         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9516         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9517         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9518         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9519         // spending transaction until height N+1 (or greater). This was due to the way
9520         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9521         // spending transaction at the height the input transaction was confirmed at, not whether we
9522         // should broadcast a spending transaction at the current height.
9523         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9524         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9525         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9526         // until we learned about an additional block.
9527         //
9528         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9529         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9530         let chanmon_cfgs = create_chanmon_cfgs(3);
9531         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9532         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9533         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9534         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9535
9536         create_announced_chan_between_nodes(&nodes, 0, 1);
9537         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9538         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9539         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9540         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9541
9542         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9543         check_closed_broadcast!(nodes[1], true);
9544         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9545         check_added_monitors!(nodes[1], 1);
9546         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9547         assert_eq!(node_txn.len(), 1);
9548
9549         let conf_height = nodes[1].best_block_info().1;
9550         if !test_height_before_timelock {
9551                 connect_blocks(&nodes[1], 24 * 6);
9552         }
9553         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9554                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9555         if test_height_before_timelock {
9556                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9557                 // generate any events or broadcast any transactions
9558                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9559                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9560         } else {
9561                 // We should broadcast an HTLC transaction spending our funding transaction first
9562                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9563                 assert_eq!(spending_txn.len(), 2);
9564                 let htlc_tx = if spending_txn[0].txid() == node_txn[0].txid() {
9565                         &spending_txn[1]
9566                 } else {
9567                         &spending_txn[0]
9568                 };
9569                 check_spends!(htlc_tx, node_txn[0]);
9570                 // We should also generate a SpendableOutputs event with the to_self output (as its
9571                 // timelock is up).
9572                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9573                 assert_eq!(descriptor_spend_txn.len(), 1);
9574
9575                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9576                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9577                 // additional block built on top of the current chain.
9578                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9579                         &nodes[1].get_block_header(conf_height + 1), &[(0, htlc_tx)], conf_height + 1);
9580                 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 }]);
9581                 check_added_monitors!(nodes[1], 1);
9582
9583                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9584                 assert!(updates.update_add_htlcs.is_empty());
9585                 assert!(updates.update_fulfill_htlcs.is_empty());
9586                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9587                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9588                 assert!(updates.update_fee.is_none());
9589                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9590                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9591                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9592         }
9593 }
9594
9595 #[test]
9596 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9597         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9598         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9599 }
9600
9601 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9602         let chanmon_cfgs = create_chanmon_cfgs(2);
9603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9606
9607         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9608
9609         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9610                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9611         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9612
9613         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9614
9615         {
9616                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9617                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9618                 check_added_monitors!(nodes[0], 1);
9619                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9620                 assert_eq!(events.len(), 1);
9621                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9622                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9623                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9624         }
9625         expect_pending_htlcs_forwardable!(nodes[1]);
9626         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9627
9628         {
9629                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9630                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9631                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9632                 check_added_monitors!(nodes[0], 1);
9633                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9634                 assert_eq!(events.len(), 1);
9635                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9636                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9637                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9638                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9639                 // assume the second is a privacy attack (no longer particularly relevant
9640                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9641                 // the first HTLC delivered above.
9642         }
9643
9644         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9645         nodes[1].node.process_pending_htlc_forwards();
9646
9647         if test_for_second_fail_panic {
9648                 // Now we go fail back the first HTLC from the user end.
9649                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9650
9651                 let expected_destinations = vec![
9652                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9653                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9654                 ];
9655                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9656                 nodes[1].node.process_pending_htlc_forwards();
9657
9658                 check_added_monitors!(nodes[1], 1);
9659                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9660                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9661
9662                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9663                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9664                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9665
9666                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9667                 assert_eq!(failure_events.len(), 4);
9668                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9669                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9670                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9671                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9672         } else {
9673                 // Let the second HTLC fail and claim the first
9674                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9675                 nodes[1].node.process_pending_htlc_forwards();
9676
9677                 check_added_monitors!(nodes[1], 1);
9678                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9679                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9680                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9681
9682                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9683
9684                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9685         }
9686 }
9687
9688 #[test]
9689 fn test_dup_htlc_second_fail_panic() {
9690         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9691         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9692         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9693         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9694         do_test_dup_htlc_second_rejected(true);
9695 }
9696
9697 #[test]
9698 fn test_dup_htlc_second_rejected() {
9699         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9700         // simply reject the second HTLC but are still able to claim the first HTLC.
9701         do_test_dup_htlc_second_rejected(false);
9702 }
9703
9704 #[test]
9705 fn test_inconsistent_mpp_params() {
9706         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9707         // such HTLC and allow the second to stay.
9708         let chanmon_cfgs = create_chanmon_cfgs(4);
9709         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9710         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9711         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9712
9713         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9714         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9715         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9716         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9717
9718         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9719                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9720         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9721         assert_eq!(route.paths.len(), 2);
9722         route.paths.sort_by(|path_a, _| {
9723                 // Sort the path so that the path through nodes[1] comes first
9724                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9725                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9726         });
9727
9728         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9729
9730         let cur_height = nodes[0].best_block_info().1;
9731         let payment_id = PaymentId([42; 32]);
9732
9733         let session_privs = {
9734                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9735                 // ultimately have, just not right away.
9736                 let mut dup_route = route.clone();
9737                 dup_route.paths.push(route.paths[1].clone());
9738                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9739                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9740         };
9741         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9742                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9743                 &None, session_privs[0]).unwrap();
9744         check_added_monitors!(nodes[0], 1);
9745
9746         {
9747                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9748                 assert_eq!(events.len(), 1);
9749                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9750         }
9751         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9752
9753         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9754                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9755         check_added_monitors!(nodes[0], 1);
9756
9757         {
9758                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9759                 assert_eq!(events.len(), 1);
9760                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9761
9762                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9763                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9764
9765                 expect_pending_htlcs_forwardable!(nodes[2]);
9766                 check_added_monitors!(nodes[2], 1);
9767
9768                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9769                 assert_eq!(events.len(), 1);
9770                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9771
9772                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9773                 check_added_monitors!(nodes[3], 0);
9774                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9775
9776                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9777                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9778                 // post-payment_secrets) and fail back the new HTLC.
9779         }
9780         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9781         nodes[3].node.process_pending_htlc_forwards();
9782         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9783         nodes[3].node.process_pending_htlc_forwards();
9784
9785         check_added_monitors!(nodes[3], 1);
9786
9787         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9788         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9789         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9790
9791         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 }]);
9792         check_added_monitors!(nodes[2], 1);
9793
9794         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9795         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9796         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9797
9798         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9799
9800         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9801                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9802                 &None, session_privs[2]).unwrap();
9803         check_added_monitors!(nodes[0], 1);
9804
9805         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9806         assert_eq!(events.len(), 1);
9807         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9808
9809         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9810         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9811 }
9812
9813 #[test]
9814 fn test_double_partial_claim() {
9815         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9816         // time out, the sender resends only some of the MPP parts, then the user processes the
9817         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9818         // amount.
9819         let chanmon_cfgs = create_chanmon_cfgs(4);
9820         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9821         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9822         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9823
9824         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9825         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9826         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9827         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9828
9829         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9830         assert_eq!(route.paths.len(), 2);
9831         route.paths.sort_by(|path_a, _| {
9832                 // Sort the path so that the path through nodes[1] comes first
9833                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9834                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9835         });
9836
9837         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9838         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9839         // amount of time to respond to.
9840
9841         // Connect some blocks to time out the payment
9842         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9843         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9844
9845         let failed_destinations = vec![
9846                 HTLCDestination::FailedPayment { payment_hash },
9847                 HTLCDestination::FailedPayment { payment_hash },
9848         ];
9849         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9850
9851         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9852
9853         // nodes[1] now retries one of the two paths...
9854         nodes[0].node.send_payment_with_route(&route, payment_hash,
9855                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9856         check_added_monitors!(nodes[0], 2);
9857
9858         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9859         assert_eq!(events.len(), 2);
9860         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9861         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9862
9863         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9864         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9865         nodes[3].node.claim_funds(payment_preimage);
9866         check_added_monitors!(nodes[3], 0);
9867         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9868 }
9869
9870 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9871 #[derive(Clone, Copy, PartialEq)]
9872 enum ExposureEvent {
9873         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9874         AtHTLCForward,
9875         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9876         AtHTLCReception,
9877         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9878         AtUpdateFeeOutbound,
9879 }
9880
9881 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool, apply_excess_fee: bool) {
9882         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9883         // policy.
9884         //
9885         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9886         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9887         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9888         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9889         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9890         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9891         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9892         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9893
9894         let chanmon_cfgs = create_chanmon_cfgs(2);
9895         let mut config = test_default_channel_config();
9896
9897         // We hard-code the feerate values here but they're re-calculated furter down and asserted.
9898         // If the values ever change below these constants should simply be updated.
9899         const AT_FEE_OUTBOUND_HTLCS: u64 = 20;
9900         let nondust_htlc_count_in_limit =
9901         if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound  {
9902                 AT_FEE_OUTBOUND_HTLCS
9903         } else { 0 };
9904         let initial_feerate = if apply_excess_fee { 253 * 2 } else { 253 };
9905         let expected_dust_buffer_feerate = initial_feerate + 2530;
9906         let mut commitment_tx_cost = commit_tx_fee_msat(initial_feerate - 253, nondust_htlc_count_in_limit, &ChannelTypeFeatures::empty());
9907         commitment_tx_cost +=
9908                 if on_holder_tx {
9909                         htlc_success_tx_weight(&ChannelTypeFeatures::empty())
9910                 } else {
9911                         htlc_timeout_tx_weight(&ChannelTypeFeatures::empty())
9912                 } * (initial_feerate as u64 - 253) / 1000 * nondust_htlc_count_in_limit;
9913         {
9914                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9915                 *feerate_lock = initial_feerate;
9916         }
9917         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9918                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9919                 // to get roughly the same initial value as the default setting when this test was
9920                 // originally written.
9921                 MaxDustHTLCExposure::FeeRateMultiplier((5_000_000 + commitment_tx_cost) / 253)
9922         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000 + commitment_tx_cost) };
9923         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9924         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9925         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9926
9927         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9928         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9929         open_channel.common_fields.max_htlc_value_in_flight_msat = 50_000_000;
9930         open_channel.common_fields.max_accepted_htlcs = 60;
9931         if on_holder_tx {
9932                 open_channel.common_fields.dust_limit_satoshis = 546;
9933         }
9934         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9935         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9936         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9937
9938         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9939
9940         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9941
9942         if on_holder_tx {
9943                 let mut node_0_per_peer_lock;
9944                 let mut node_0_peer_state_lock;
9945                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9946                         ChannelPhase::UnfundedOutboundV1(chan) => {
9947                                 chan.context.holder_dust_limit_satoshis = 546;
9948                         },
9949                         _ => panic!("Unexpected ChannelPhase variant"),
9950                 }
9951         }
9952
9953         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9954         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()));
9955         check_added_monitors!(nodes[1], 1);
9956         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9957
9958         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()));
9959         check_added_monitors!(nodes[0], 1);
9960         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9961
9962         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9963         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9964         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9965
9966         {
9967                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9968                 *feerate_lock = 253;
9969         }
9970
9971         // Fetch a route in advance as we will be unable to once we're unable to send.
9972         let (mut route, payment_hash, _, payment_secret) =
9973                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9974
9975         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9976                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9977                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9978                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9979                 (chan.context().get_dust_buffer_feerate(None) as u64,
9980                 chan.context().get_max_dust_htlc_exposure_msat(253))
9981         };
9982         assert_eq!(dust_buffer_feerate, expected_dust_buffer_feerate as u64);
9983         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - 1) * 1000;
9984         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9985
9986         // Substract 3 sats for multiplier and 2 sats for fixed limit to make sure we are 50% below the dust limit.
9987         // This is to make sure we fully use the dust limit. If we don't, we could end up with `dust_ibd_htlc_on_holder_tx` being 1
9988         // while `max_dust_htlc_exposure_msat` is not equal to `dust_outbound_htlc_on_holder_tx_msat`.
9989         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - if multiplier_dust_limit { 3 } else { 2 }) * 1000;
9990         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9991
9992         // This test was written with a fixed dust value here, which we retain, but assert that it is,
9993         // indeed, dust on both transactions.
9994         let dust_htlc_on_counterparty_tx: u64 = 4;
9995         let dust_htlc_on_counterparty_tx_msat: u64 = 1_250_000;
9996         let calcd_dust_htlc_on_counterparty_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - if multiplier_dust_limit { 3 } else { 2 }) * 1000;
9997         assert!(dust_htlc_on_counterparty_tx_msat < dust_inbound_htlc_on_holder_tx_msat);
9998         assert!(dust_htlc_on_counterparty_tx_msat < calcd_dust_htlc_on_counterparty_tx_msat);
9999
10000         if on_holder_tx {
10001                 if dust_outbound_balance {
10002                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10003                         // Outbound dust balance: 4372 sats
10004                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10005                         for _ in 0..dust_outbound_htlc_on_holder_tx {
10006                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10007                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10008                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10009                         }
10010                 } else {
10011                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10012                         // Inbound dust balance: 4372 sats
10013                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10014                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10015                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10016                         }
10017                 }
10018         } else {
10019                 if dust_outbound_balance {
10020                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10021                         // Outbound dust balance: 5000 sats
10022                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
10023                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10024                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10025                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10026                         }
10027                 } else {
10028                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10029                         // Inbound dust balance: 5000 sats
10030                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
10031                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10032                         }
10033                 }
10034         }
10035
10036         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10037                 route.paths[0].hops.last_mut().unwrap().fee_msat =
10038                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
10039                 // With default dust exposure: 5000 sats
10040                 if on_holder_tx {
10041                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10042                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10043                                 ), true, APIError::ChannelUnavailable { .. }, {});
10044                 } else {
10045                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10046                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10047                                 ), true, APIError::ChannelUnavailable { .. }, {});
10048                 }
10049         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10050                 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 });
10051                 nodes[1].node.send_payment_with_route(&route, payment_hash,
10052                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10053                 check_added_monitors!(nodes[1], 1);
10054                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10055                 assert_eq!(events.len(), 1);
10056                 let payment_event = SendEvent::from_event(events.remove(0));
10057                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10058                 // With default dust exposure: 5000 sats
10059                 if on_holder_tx {
10060                         // Outbound dust balance: 6399 sats
10061                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10062                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10063                         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
10064                 } else {
10065                         // Outbound dust balance: 5200 sats
10066                         nodes[0].logger.assert_log("lightning::ln::channel",
10067                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
10068                                         dust_htlc_on_counterparty_tx_msat * dust_htlc_on_counterparty_tx + commitment_tx_cost + 4,
10069                                         max_dust_htlc_exposure_msat), 1);
10070                 }
10071         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10072                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
10073                 // For the multiplier dust exposure limit, since it scales with feerate,
10074                 // we need to add a lot of HTLCs that will become dust at the new feerate
10075                 // to cross the threshold.
10076                 for _ in 0..AT_FEE_OUTBOUND_HTLCS {
10077                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
10078                         nodes[0].node.send_payment_with_route(&route, payment_hash,
10079                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10080                 }
10081                 {
10082                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10083                         *feerate_lock = *feerate_lock * 10;
10084                 }
10085                 nodes[0].node.timer_tick_occurred();
10086                 check_added_monitors!(nodes[0], 1);
10087                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
10088         }
10089
10090         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10091         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10092         added_monitors.clear();
10093 }
10094
10095 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool, apply_excess_fee: bool) {
10096         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit, apply_excess_fee);
10097         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit, apply_excess_fee);
10098         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit, apply_excess_fee);
10099         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit, apply_excess_fee);
10100         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit, apply_excess_fee);
10101         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit, apply_excess_fee);
10102         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit, apply_excess_fee);
10103         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit, apply_excess_fee);
10104         if !multiplier_dust_limit && !apply_excess_fee {
10105                 // Because non-dust HTLC transaction fees are included in the dust exposure, trying to
10106                 // increase the fee to hit a higher dust exposure with a
10107                 // `MaxDustHTLCExposure::FeeRateMultiplier` is no longer super practical, so we skip these
10108                 // in the `multiplier_dust_limit` case.
10109                 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit, apply_excess_fee);
10110                 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit, apply_excess_fee);
10111                 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit, apply_excess_fee);
10112                 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit, apply_excess_fee);
10113         }
10114 }
10115
10116 #[test]
10117 fn test_max_dust_htlc_exposure() {
10118         do_test_max_dust_htlc_exposure_by_threshold_type(false, false);
10119         do_test_max_dust_htlc_exposure_by_threshold_type(false, true);
10120         do_test_max_dust_htlc_exposure_by_threshold_type(true, false);
10121         do_test_max_dust_htlc_exposure_by_threshold_type(true, true);
10122 }
10123
10124 #[test]
10125 fn test_nondust_htlc_fees_are_dust() {
10126         // Test that the transaction fees paid in nondust HTLCs count towards our dust limit
10127         let chanmon_cfgs = create_chanmon_cfgs(3);
10128         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10129
10130         let mut config = test_default_channel_config();
10131         // Set the dust limit to the default value
10132         config.channel_config.max_dust_htlc_exposure =
10133                 MaxDustHTLCExposure::FeeRateMultiplier(10_000);
10134         // Make sure the HTLC limits don't get in the way
10135         config.channel_handshake_limits.min_max_accepted_htlcs = 400;
10136         config.channel_handshake_config.our_max_accepted_htlcs = 400;
10137         config.channel_handshake_config.our_htlc_minimum_msat = 1;
10138
10139         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
10140         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10141
10142         // Create a channel from 1 -> 0 but immediately push all of the funds towards 0
10143         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 1, 0).2;
10144         while nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat > 0 {
10145                 send_payment(&nodes[1], &[&nodes[0]], nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat);
10146         }
10147
10148         // First get the channel one HTLC_VALUE HTLC away from the dust limit by sending dust HTLCs
10149         // repeatedly until we run out of space.
10150         const HTLC_VALUE: u64 = 1_000_000; // Doesn't matter, tune until the test passes
10151         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], HTLC_VALUE).0;
10152
10153         while nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat == 0 {
10154                 route_payment(&nodes[0], &[&nodes[1]], HTLC_VALUE);
10155         }
10156         assert_ne!(nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat, 0,
10157                 "We don't want to run out of ability to send because of some non-dust limit");
10158         assert!(nodes[0].node.list_channels()[0].pending_outbound_htlcs.len() < 10,
10159                 "We should be able to fill our dust limit without too many HTLCs");
10160
10161         let dust_limit = nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat;
10162         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
10163         assert_ne!(nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat, 0,
10164                 "Make sure we are able to send once we clear one HTLC");
10165
10166         // At this point we have somewhere between dust_limit and dust_limit * 2 left in our dust
10167         // exposure limit, and we want to max that out using non-dust HTLCs.
10168         let commitment_tx_per_htlc_cost =
10169                 htlc_success_tx_weight(&ChannelTypeFeatures::empty()) * 253;
10170         let max_htlcs_remaining = dust_limit * 2 / commitment_tx_per_htlc_cost;
10171         assert!(max_htlcs_remaining < 30,
10172                 "We should be able to fill our dust limit without too many HTLCs");
10173         for i in 0..max_htlcs_remaining + 1 {
10174                 assert_ne!(i, max_htlcs_remaining);
10175                 if nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat < dust_limit {
10176                         // We found our limit, and it was less than max_htlcs_remaining!
10177                         // At this point we can only send dust HTLCs as any non-dust HTLCs will overuse our
10178                         // remaining dust exposure.
10179                         break;
10180                 }
10181                 route_payment(&nodes[0], &[&nodes[1]], dust_limit * 2);
10182         }
10183
10184         // At this point non-dust HTLCs are no longer accepted from node 0 -> 1, we also check that
10185         // such HTLCs can't be routed over the same channel either.
10186         create_announced_chan_between_nodes(&nodes, 2, 0);
10187         let (route, payment_hash, _, payment_secret) =
10188                 get_route_and_payment_hash!(nodes[2], nodes[1], dust_limit * 2);
10189         let onion = RecipientOnionFields::secret_only(payment_secret);
10190         nodes[2].node.send_payment_with_route(&route, payment_hash, onion, PaymentId([0; 32])).unwrap();
10191         check_added_monitors(&nodes[2], 1);
10192         let send = SendEvent::from_node(&nodes[2]);
10193
10194         nodes[0].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send.msgs[0]);
10195         commitment_signed_dance!(nodes[0], nodes[2], send.commitment_msg, false, true);
10196
10197         expect_pending_htlcs_forwardable!(nodes[0]);
10198         check_added_monitors(&nodes[0], 1);
10199         let node_id_1 = nodes[1].node.get_our_node_id();
10200         expect_htlc_handling_failed_destinations!(
10201                 nodes[0].node.get_and_clear_pending_events(),
10202                 &[HTLCDestination::NextHopChannel { node_id: Some(node_id_1), channel_id: chan_id_1 }]
10203         );
10204
10205         let fail = get_htlc_update_msgs(&nodes[0], &nodes[2].node.get_our_node_id());
10206         nodes[2].node.handle_update_fail_htlc(&nodes[0].node.get_our_node_id(), &fail.update_fail_htlcs[0]);
10207         commitment_signed_dance!(nodes[2], nodes[0], fail.commitment_signed, false);
10208         expect_payment_failed_conditions(&nodes[2], payment_hash, false, PaymentFailedConditions::new());
10209 }
10210
10211
10212 #[test]
10213 fn test_non_final_funding_tx() {
10214         let chanmon_cfgs = create_chanmon_cfgs(2);
10215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10217         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10218
10219         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10220         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10221         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10222         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10223         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10224
10225         let best_height = nodes[0].node.best_block.read().unwrap().height;
10226
10227         let chan_id = *nodes[0].network_chan_count.borrow();
10228         let events = nodes[0].node.get_and_clear_pending_events();
10229         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
10230         assert_eq!(events.len(), 1);
10231         let mut tx = match events[0] {
10232                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10233                         // Timelock the transaction _beyond_ the best client height + 1.
10234                         Transaction { version: chan_id as i32, lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
10235                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10236                         }]}
10237                 },
10238                 _ => panic!("Unexpected event"),
10239         };
10240         // Transaction should fail as it's evaluated as non-final for propagation.
10241         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10242                 Err(APIError::APIMisuseError { err }) => {
10243                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10244                 },
10245                 _ => panic!()
10246         }
10247         let err = "Error in transaction funding: Misuse error: Funding transaction absolute timelock is non-final".to_owned();
10248         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(temp_channel_id, false, ClosureReason::ProcessingError { err })]);
10249         assert_eq!(get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id()).data, "Failed to fund channel");
10250 }
10251
10252 #[test]
10253 fn test_non_final_funding_tx_within_headroom() {
10254         let chanmon_cfgs = create_chanmon_cfgs(2);
10255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10257         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10258
10259         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10260         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10261         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10262         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10263         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10264
10265         let best_height = nodes[0].node.best_block.read().unwrap().height;
10266
10267         let chan_id = *nodes[0].network_chan_count.borrow();
10268         let events = nodes[0].node.get_and_clear_pending_events();
10269         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10270         assert_eq!(events.len(), 1);
10271         let mut tx = match events[0] {
10272                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10273                         // Timelock the transaction within a +1 headroom from the best block.
10274                         Transaction { version: chan_id as i32, lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10275                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10276                         }]}
10277                 },
10278                 _ => panic!("Unexpected event"),
10279         };
10280
10281         // Transaction should be accepted if it's in a +1 headroom from best block.
10282         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10283         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10284 }
10285
10286 #[test]
10287 fn accept_busted_but_better_fee() {
10288         // If a peer sends us a fee update that is too low, but higher than our previous channel
10289         // feerate, we should accept it. In the future we may want to consider closing the channel
10290         // later, but for now we only accept the update.
10291         let mut 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         create_chan_between_nodes(&nodes[0], &nodes[1]);
10297
10298         // Set nodes[1] to expect 5,000 sat/kW.
10299         {
10300                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10301                 *feerate_lock = 5000;
10302         }
10303
10304         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10305         {
10306                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10307                 *feerate_lock = 1000;
10308         }
10309         nodes[0].node.timer_tick_occurred();
10310         check_added_monitors!(nodes[0], 1);
10311
10312         let events = nodes[0].node.get_and_clear_pending_msg_events();
10313         assert_eq!(events.len(), 1);
10314         match events[0] {
10315                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10316                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10317                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10318                 },
10319                 _ => panic!("Unexpected event"),
10320         };
10321
10322         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10323         // it.
10324         {
10325                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10326                 *feerate_lock = 2000;
10327         }
10328         nodes[0].node.timer_tick_occurred();
10329         check_added_monitors!(nodes[0], 1);
10330
10331         let events = nodes[0].node.get_and_clear_pending_msg_events();
10332         assert_eq!(events.len(), 1);
10333         match events[0] {
10334                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10335                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10336                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10337                 },
10338                 _ => panic!("Unexpected event"),
10339         };
10340
10341         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10342         // channel.
10343         {
10344                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10345                 *feerate_lock = 1000;
10346         }
10347         nodes[0].node.timer_tick_occurred();
10348         check_added_monitors!(nodes[0], 1);
10349
10350         let events = nodes[0].node.get_and_clear_pending_msg_events();
10351         assert_eq!(events.len(), 1);
10352         match events[0] {
10353                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10354                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10355                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10356                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10357                                 [nodes[0].node.get_our_node_id()], 100000);
10358                         check_closed_broadcast!(nodes[1], true);
10359                         check_added_monitors!(nodes[1], 1);
10360                 },
10361                 _ => panic!("Unexpected event"),
10362         };
10363 }
10364
10365 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10366         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10369         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10370         let min_final_cltv_expiry_delta = 120;
10371         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10372                 min_final_cltv_expiry_delta - 2 };
10373         let recv_value = 100_000;
10374
10375         create_chan_between_nodes(&nodes[0], &nodes[1]);
10376
10377         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10378         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10379                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10380                         Some(recv_value), Some(min_final_cltv_expiry_delta));
10381                 (payment_hash, payment_preimage, payment_secret)
10382         } else {
10383                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10384                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10385         };
10386         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10387         nodes[0].node.send_payment_with_route(&route, payment_hash,
10388                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10389         check_added_monitors!(nodes[0], 1);
10390         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10391         assert_eq!(events.len(), 1);
10392         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10393         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10394         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10395         expect_pending_htlcs_forwardable!(nodes[1]);
10396
10397         if valid_delta {
10398                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10399                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10400
10401                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10402         } else {
10403                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10404
10405                 check_added_monitors!(nodes[1], 1);
10406
10407                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10408                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10409                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10410
10411                 expect_payment_failed!(nodes[0], payment_hash, true);
10412         }
10413 }
10414
10415 #[test]
10416 fn test_payment_with_custom_min_cltv_expiry_delta() {
10417         do_payment_with_custom_min_final_cltv_expiry(false, false);
10418         do_payment_with_custom_min_final_cltv_expiry(false, true);
10419         do_payment_with_custom_min_final_cltv_expiry(true, false);
10420         do_payment_with_custom_min_final_cltv_expiry(true, true);
10421 }
10422
10423 #[test]
10424 fn test_disconnects_peer_awaiting_response_ticks() {
10425         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10426         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10427         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10428         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10429         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10430         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10431
10432         // Asserts a disconnect event is queued to the user.
10433         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10434                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10435                         if let MessageSendEvent::HandleError { action, .. } = event {
10436                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10437                                         Some(())
10438                                 } else {
10439                                         None
10440                                 }
10441                         } else {
10442                                 None
10443                         }
10444                 );
10445                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10446         };
10447
10448         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10449         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10450         let check_disconnect = |node: &Node| {
10451                 // No disconnect without any timer ticks.
10452                 check_disconnect_event(node, false);
10453
10454                 // No disconnect with 1 timer tick less than required.
10455                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10456                         node.node.timer_tick_occurred();
10457                         check_disconnect_event(node, false);
10458                 }
10459
10460                 // Disconnect after reaching the required ticks.
10461                 node.node.timer_tick_occurred();
10462                 check_disconnect_event(node, true);
10463
10464                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10465                 node.node.timer_tick_occurred();
10466                 check_disconnect_event(node, true);
10467         };
10468
10469         create_chan_between_nodes(&nodes[0], &nodes[1]);
10470
10471         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10472         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10473         nodes[0].node.timer_tick_occurred();
10474         check_added_monitors!(&nodes[0], 1);
10475         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10476         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10477         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10478         check_added_monitors!(&nodes[1], 1);
10479
10480         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10481         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10482         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10483         check_added_monitors!(&nodes[0], 1);
10484         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10485         check_added_monitors(&nodes[0], 1);
10486
10487         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10488         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10489         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10490         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10491         check_disconnect(&nodes[1]);
10492
10493         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10494         //
10495         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10496         // final `RevokeAndACK` to Bob to complete it.
10497         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10498         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10499         let bob_init = msgs::Init {
10500                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10501         };
10502         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10503         let alice_init = msgs::Init {
10504                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10505         };
10506         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10507
10508         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10509         // received Bob's yet, so she should disconnect him after reaching
10510         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10511         let alice_channel_reestablish = get_event_msg!(
10512                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10513         );
10514         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10515         check_disconnect(&nodes[0]);
10516
10517         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10518         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10519                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10520                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10521                         Some(msg.clone())
10522                 } else {
10523                         None
10524                 }
10525         ).unwrap();
10526         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10527
10528         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10529         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10530                 nodes[0].node.timer_tick_occurred();
10531                 check_disconnect_event(&nodes[0], false);
10532         }
10533
10534         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10535         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10536         check_disconnect(&nodes[1]);
10537
10538         // Finally, have Bob process the last message.
10539         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10540         check_added_monitors(&nodes[1], 1);
10541
10542         // At this point, neither node should attempt to disconnect each other, since they aren't
10543         // waiting on any messages.
10544         for node in &nodes {
10545                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10546                         node.node.timer_tick_occurred();
10547                         check_disconnect_event(node, false);
10548                 }
10549         }
10550 }
10551
10552 #[test]
10553 fn test_remove_expired_outbound_unfunded_channels() {
10554         let chanmon_cfgs = create_chanmon_cfgs(2);
10555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10557         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10558
10559         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10560         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10561         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10562         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10563         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10564
10565         let events = nodes[0].node.get_and_clear_pending_events();
10566         assert_eq!(events.len(), 1);
10567         match events[0] {
10568                 Event::FundingGenerationReady { .. } => (),
10569                 _ => panic!("Unexpected event"),
10570         };
10571
10572         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10573         let check_outbound_channel_existence = |should_exist: bool| {
10574                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10575                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10576                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10577         };
10578
10579         // Channel should exist without any timer ticks.
10580         check_outbound_channel_existence(true);
10581
10582         // Channel should exist with 1 timer tick less than required.
10583         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10584                 nodes[0].node.timer_tick_occurred();
10585                 check_outbound_channel_existence(true)
10586         }
10587
10588         // Remove channel after reaching the required ticks.
10589         nodes[0].node.timer_tick_occurred();
10590         check_outbound_channel_existence(false);
10591
10592         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10593         assert_eq!(msg_events.len(), 1);
10594         match msg_events[0] {
10595                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10596                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10597                 },
10598                 _ => panic!("Unexpected event"),
10599         }
10600         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10601 }
10602
10603 #[test]
10604 fn test_remove_expired_inbound_unfunded_channels() {
10605         let chanmon_cfgs = create_chanmon_cfgs(2);
10606         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10607         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10608         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10609
10610         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10611         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10612         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10613         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10614         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10615
10616         let events = nodes[0].node.get_and_clear_pending_events();
10617         assert_eq!(events.len(), 1);
10618         match events[0] {
10619                 Event::FundingGenerationReady { .. } => (),
10620                 _ => panic!("Unexpected event"),
10621         };
10622
10623         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10624         let check_inbound_channel_existence = |should_exist: bool| {
10625                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10626                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10627                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10628         };
10629
10630         // Channel should exist without any timer ticks.
10631         check_inbound_channel_existence(true);
10632
10633         // Channel should exist with 1 timer tick less than required.
10634         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10635                 nodes[1].node.timer_tick_occurred();
10636                 check_inbound_channel_existence(true)
10637         }
10638
10639         // Remove channel after reaching the required ticks.
10640         nodes[1].node.timer_tick_occurred();
10641         check_inbound_channel_existence(false);
10642
10643         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10644         assert_eq!(msg_events.len(), 1);
10645         match msg_events[0] {
10646                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10647                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10648                 },
10649                 _ => panic!("Unexpected event"),
10650         }
10651         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10652 }
10653
10654 #[test]
10655 fn test_channel_close_when_not_timely_accepted() {
10656         // Create network of two nodes
10657         let chanmon_cfgs = create_chanmon_cfgs(2);
10658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10661
10662         // Simulate peer-disconnects mid-handshake
10663         // The channel is initiated from the node 0 side,
10664         // but the nodes disconnect before node 1 could send accept channel
10665         let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10666         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10667         assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10668
10669         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10670         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10671
10672         // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10673         assert_eq!(nodes[0].node.list_channels().len(), 1);
10674
10675         // Since channel was inbound from node[1] perspective, it should have been dropped immediately.
10676         assert_eq!(nodes[1].node.list_channels().len(), 0);
10677
10678         // In the meantime, some time passes.
10679         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
10680                 nodes[0].node.timer_tick_occurred();
10681         }
10682
10683         // Since we disconnected from peer and did not connect back within time,
10684         // we should have forced-closed the channel by now.
10685         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
10686         assert_eq!(nodes[0].node.list_channels().len(), 0);
10687
10688         {
10689                 // Since accept channel message was never received
10690                 // The channel should be forced close by now from node 0 side
10691                 // and the peer removed from per_peer_state
10692                 let node_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10693                 assert_eq!(node_0_per_peer_state.len(), 0);
10694         }
10695 }
10696
10697 #[test]
10698 fn test_rebroadcast_open_channel_when_reconnect_mid_handshake() {
10699         // Create network of two nodes
10700         let chanmon_cfgs = create_chanmon_cfgs(2);
10701         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10702         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10703         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10704
10705         // Simulate peer-disconnects mid-handshake
10706         // The channel is initiated from the node 0 side,
10707         // but the nodes disconnect before node 1 could send accept channel
10708         let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10709         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10710         assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10711
10712         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10713         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10714
10715         // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10716         assert_eq!(nodes[0].node.list_channels().len(), 1);
10717
10718         // Since channel was inbound from node[1] perspective, it should have been immediately dropped.
10719         assert_eq!(nodes[1].node.list_channels().len(), 0);
10720
10721         // The peers now reconnect
10722         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
10723                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10724         }, true).unwrap();
10725         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10726                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10727         }, false).unwrap();
10728
10729         // Make sure the SendOpenChannel message is added to node_0 pending message events
10730         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10731         assert_eq!(msg_events.len(), 1);
10732         match &msg_events[0] {
10733                 MessageSendEvent::SendOpenChannel { msg, .. } => assert_eq!(msg, &open_channel_msg),
10734                 _ => panic!("Unexpected message."),
10735         }
10736 }
10737
10738 fn do_test_multi_post_event_actions(do_reload: bool) {
10739         // Tests handling multiple post-Event actions at once.
10740         // There is specific code in ChannelManager to handle channels where multiple post-Event
10741         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10742         //
10743         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10744         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10745         // - one from an RAA and one from an inbound commitment_signed.
10746         let chanmon_cfgs = create_chanmon_cfgs(3);
10747         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10748         let (persister, chain_monitor);
10749         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10750         let nodes_0_deserialized;
10751         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10752
10753         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10754         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10755
10756         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10757         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10758
10759         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10760         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10761
10762         nodes[1].node.claim_funds(our_payment_preimage);
10763         check_added_monitors!(nodes[1], 1);
10764         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10765
10766         nodes[2].node.claim_funds(payment_preimage_2);
10767         check_added_monitors!(nodes[2], 1);
10768         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10769
10770         for dest in &[1, 2] {
10771                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10772                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10773                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10774                 check_added_monitors(&nodes[0], 0);
10775         }
10776
10777         let (route, payment_hash_3, _, payment_secret_3) =
10778                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10779         let payment_id = PaymentId(payment_hash_3.0);
10780         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10781                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10782         check_added_monitors(&nodes[1], 1);
10783
10784         let send_event = SendEvent::from_node(&nodes[1]);
10785         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10786         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10787         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10788
10789         if do_reload {
10790                 let nodes_0_serialized = nodes[0].node.encode();
10791                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10792                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10793                 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);
10794
10795                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10796                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10797
10798                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10799                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10800         }
10801
10802         let events = nodes[0].node.get_and_clear_pending_events();
10803         assert_eq!(events.len(), 4);
10804         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10805                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10806         } else { panic!(); }
10807         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10808                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10809         } else { panic!(); }
10810         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10811         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10812
10813         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10814         // completion, we'll respond to nodes[1] with an RAA + CS.
10815         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10816         check_added_monitors(&nodes[0], 3);
10817 }
10818
10819 #[test]
10820 fn test_multi_post_event_actions() {
10821         do_test_multi_post_event_actions(true);
10822         do_test_multi_post_event_actions(false);
10823 }
10824
10825 #[test]
10826 fn test_batch_channel_open() {
10827         let chanmon_cfgs = create_chanmon_cfgs(3);
10828         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10829         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10830         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10831
10832         // Initiate channel opening and create the batch channel funding transaction.
10833         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10834                 (&nodes[1], 100_000, 0, 42, None),
10835                 (&nodes[2], 200_000, 0, 43, None),
10836         ]);
10837
10838         // Go through the funding_created and funding_signed flow with node 1.
10839         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10840         check_added_monitors(&nodes[1], 1);
10841         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10842
10843         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10844         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10845         check_added_monitors(&nodes[0], 1);
10846
10847         // The transaction should not have been broadcast before all channels are ready.
10848         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10849
10850         // Go through the funding_created and funding_signed flow with node 2.
10851         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10852         check_added_monitors(&nodes[2], 1);
10853         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10854
10855         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10856         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10857         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10858         check_added_monitors(&nodes[0], 1);
10859
10860         // The transaction should not have been broadcast before persisting all monitors has been
10861         // completed.
10862         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10863         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10864
10865         // Complete the persistence of the monitor.
10866         nodes[0].chain_monitor.complete_sole_pending_chan_update(
10867                 &ChannelId::v1_from_funding_outpoint(OutPoint { txid: tx.txid(), index: 1 })
10868         );
10869         let events = nodes[0].node.get_and_clear_pending_events();
10870
10871         // The transaction should only have been broadcast now.
10872         let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10873         assert_eq!(broadcasted_txs.len(), 1);
10874         assert_eq!(broadcasted_txs[0], tx);
10875
10876         assert_eq!(events.len(), 2);
10877         assert!(events.iter().any(|e| matches!(
10878                 *e,
10879                 crate::events::Event::ChannelPending {
10880                         ref counterparty_node_id,
10881                         ..
10882                 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10883         )));
10884         assert!(events.iter().any(|e| matches!(
10885                 *e,
10886                 crate::events::Event::ChannelPending {
10887                         ref counterparty_node_id,
10888                         ..
10889                 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10890         )));
10891 }
10892
10893 #[test]
10894 fn test_close_in_funding_batch() {
10895         // This test ensures that if one of the channels
10896         // in the batch closes, the complete batch will close.
10897         let chanmon_cfgs = create_chanmon_cfgs(3);
10898         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10899         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10900         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10901
10902         // Initiate channel opening and create the batch channel funding transaction.
10903         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10904                 (&nodes[1], 100_000, 0, 42, None),
10905                 (&nodes[2], 200_000, 0, 43, None),
10906         ]);
10907
10908         // Go through the funding_created and funding_signed flow with node 1.
10909         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10910         check_added_monitors(&nodes[1], 1);
10911         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10912
10913         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10914         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10915         check_added_monitors(&nodes[0], 1);
10916
10917         // The transaction should not have been broadcast before all channels are ready.
10918         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10919
10920         // Force-close the channel for which we've completed the initial monitor.
10921         let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10922         let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10923         let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10924         let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10925
10926         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10927
10928         // The monitor should become closed.
10929         check_added_monitors(&nodes[0], 1);
10930         {
10931                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10932                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10933                 assert_eq!(monitor_updates_1.len(), 1);
10934                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10935         }
10936
10937         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10938         match msg_events[0] {
10939                 MessageSendEvent::HandleError { .. } => (),
10940                 _ => panic!("Unexpected message."),
10941         }
10942
10943         // We broadcast the commitment transaction as part of the force-close.
10944         {
10945                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10946                 assert_eq!(broadcasted_txs.len(), 1);
10947                 assert!(broadcasted_txs[0].txid() != tx.txid());
10948                 assert_eq!(broadcasted_txs[0].input.len(), 1);
10949                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10950         }
10951
10952         // All channels in the batch should close immediately.
10953         check_closed_events(&nodes[0], &[
10954                 ExpectedCloseEvent {
10955                         channel_id: Some(channel_id_1),
10956                         discard_funding: true,
10957                         channel_funding_txo: Some(funding_txo_1),
10958                         user_channel_id: Some(42),
10959                         ..Default::default()
10960                 },
10961                 ExpectedCloseEvent {
10962                         channel_id: Some(channel_id_2),
10963                         discard_funding: true,
10964                         channel_funding_txo: Some(funding_txo_2),
10965                         user_channel_id: Some(43),
10966                         ..Default::default()
10967                 },
10968         ]);
10969
10970         // Ensure the channels don't exist anymore.
10971         assert!(nodes[0].node.list_channels().is_empty());
10972 }
10973
10974 #[test]
10975 fn test_batch_funding_close_after_funding_signed() {
10976         let chanmon_cfgs = create_chanmon_cfgs(3);
10977         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10978         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10979         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10980
10981         // Initiate channel opening and create the batch channel funding transaction.
10982         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10983                 (&nodes[1], 100_000, 0, 42, None),
10984                 (&nodes[2], 200_000, 0, 43, None),
10985         ]);
10986
10987         // Go through the funding_created and funding_signed flow with node 1.
10988         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10989         check_added_monitors(&nodes[1], 1);
10990         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10991
10992         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10993         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10994         check_added_monitors(&nodes[0], 1);
10995
10996         // Go through the funding_created and funding_signed flow with node 2.
10997         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10998         check_added_monitors(&nodes[2], 1);
10999         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
11000
11001         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11002         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
11003         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
11004         check_added_monitors(&nodes[0], 1);
11005
11006         // The transaction should not have been broadcast before all channels are ready.
11007         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
11008
11009         // Force-close the channel for which we've completed the initial monitor.
11010         let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
11011         let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
11012         let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
11013         let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
11014         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
11015         check_added_monitors(&nodes[0], 2);
11016         {
11017                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
11018                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
11019                 assert_eq!(monitor_updates_1.len(), 1);
11020                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
11021                 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
11022                 assert_eq!(monitor_updates_2.len(), 1);
11023                 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
11024         }
11025         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
11026         match msg_events[0] {
11027                 MessageSendEvent::HandleError { .. } => (),
11028                 _ => panic!("Unexpected message."),
11029         }
11030
11031         // We broadcast the commitment transaction as part of the force-close.
11032         {
11033                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
11034                 assert_eq!(broadcasted_txs.len(), 1);
11035                 assert!(broadcasted_txs[0].txid() != tx.txid());
11036                 assert_eq!(broadcasted_txs[0].input.len(), 1);
11037                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
11038         }
11039
11040         // All channels in the batch should close immediately.
11041         check_closed_events(&nodes[0], &[
11042                 ExpectedCloseEvent {
11043                         channel_id: Some(channel_id_1),
11044                         discard_funding: true,
11045                         channel_funding_txo: Some(funding_txo_1),
11046                         user_channel_id: Some(42),
11047                         ..Default::default()
11048                 },
11049                 ExpectedCloseEvent {
11050                         channel_id: Some(channel_id_2),
11051                         discard_funding: true,
11052                         channel_funding_txo: Some(funding_txo_2),
11053                         user_channel_id: Some(43),
11054                         ..Default::default()
11055                 },
11056         ]);
11057
11058         // Ensure the channels don't exist anymore.
11059         assert!(nodes[0].node.list_channels().is_empty());
11060 }
11061
11062 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
11063         // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
11064         // funding and commitment transaction confirm in the same block.
11065         let chanmon_cfgs = create_chanmon_cfgs(2);
11066         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11067         let mut min_depth_1_block_cfg = test_default_channel_config();
11068         min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
11069         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
11070         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11071
11072         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
11073         let chan_id = ChannelId::v1_from_funding_outpoint(chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 });
11074
11075         assert_eq!(nodes[0].node.list_channels().len(), 1);
11076         assert_eq!(nodes[1].node.list_channels().len(), 1);
11077
11078         let (closing_node, other_node) = if confirm_remote_commitment {
11079                 (&nodes[1], &nodes[0])
11080         } else {
11081                 (&nodes[0], &nodes[1])
11082         };
11083
11084         closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
11085         let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
11086         assert_eq!(msg_events.len(), 1);
11087         match msg_events.pop().unwrap() {
11088                 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
11089                 _ => panic!("Unexpected event"),
11090         }
11091         check_added_monitors(closing_node, 1);
11092         check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
11093
11094         let commitment_tx = {
11095                 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
11096                 assert_eq!(txn.len(), 1);
11097                 let commitment_tx = txn.pop().unwrap();
11098                 check_spends!(commitment_tx, funding_tx);
11099                 commitment_tx
11100         };
11101
11102         mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
11103         mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
11104
11105         check_closed_broadcast(other_node, 1, true);
11106         check_added_monitors(other_node, 1);
11107         check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
11108
11109         assert!(nodes[0].node.list_channels().is_empty());
11110         assert!(nodes[1].node.list_channels().is_empty());
11111 }
11112
11113 #[test]
11114 fn test_funding_and_commitment_tx_confirm_same_block() {
11115         do_test_funding_and_commitment_tx_confirm_same_block(false);
11116         do_test_funding_and_commitment_tx_confirm_same_block(true);
11117 }
11118
11119 #[test]
11120 fn test_accept_inbound_channel_errors_queued() {
11121         // For manually accepted inbound channels, tests that a close error is correctly handled
11122         // and the channel fails for the initiator.
11123         let mut config0 = test_default_channel_config();
11124         let mut config1 = config0.clone();
11125         config1.channel_handshake_limits.their_to_self_delay = 1000;
11126         config1.manually_accept_inbound_channels = true;
11127         config0.channel_handshake_config.our_to_self_delay = 2000;
11128
11129         let chanmon_cfgs = create_chanmon_cfgs(2);
11130         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config0), Some(config1)]);
11132         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11133
11134         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11135         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11136
11137         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11138         let events = nodes[1].node.get_and_clear_pending_events();
11139         match events[0] {
11140                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11141                         match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23) {
11142                                 Err(APIError::ChannelUnavailable { err: _ }) => (),
11143                                 _ => panic!(),
11144                         }
11145                 }
11146                 _ => panic!("Unexpected event"),
11147         }
11148         assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11149                 open_channel_msg.common_fields.temporary_channel_id);
11150 }