eee9ef49b60bcd14e5ebd962b7486a8af1b3880f
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::locktime::absolute::LockTime;
42 use bitcoin::blockdata::script::{Builder, ScriptBuf};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{Sequence, Transaction, TxIn, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
51
52 use regex;
53
54 use crate::io;
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex, RwLock};
61
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
64
65 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
66
67 #[test]
68 fn test_insane_channel_opens() {
69         // Stand up a network of 2 nodes
70         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
71         let mut cfg = UserConfig::default();
72         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
73         let chanmon_cfgs = create_chanmon_cfgs(2);
74         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
75         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
76         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
77
78         // Instantiate channel parameters where we push the maximum msats given our
79         // funding satoshis
80         let channel_value_sat = 31337; // same as funding satoshis
81         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
82         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
83
84         // Have node0 initiate a channel to node1 with aforementioned parameters
85         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
86
87         // Extract the channel open message from node0 to node1
88         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
89
90         // Test helper that asserts we get the correct error string given a mutator
91         // that supposedly makes the channel open message insane
92         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
93                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
94                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
95                 assert_eq!(msg_events.len(), 1);
96                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
97                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
98                         match action {
99                                 &ErrorAction::SendErrorMessage { .. } => {
100                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
101                                 },
102                                 _ => panic!("unexpected event!"),
103                         }
104                 } else { assert!(false); }
105         };
106
107         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
108
109         // Test all mutations that would make the channel open message insane
110         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.common_fields.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
111         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.common_fields.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
112
113         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.common_fields.funding_satoshis + 1; msg });
114
115         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.common_fields.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
116
117         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.common_fields.dust_limit_satoshis = msg.common_fields.funding_satoshis + 1 ; msg });
118
119         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 });
120
121         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 });
122
123         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.common_fields.max_accepted_htlcs = 0; msg });
124
125         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.common_fields.max_accepted_htlcs = 484; msg });
126 }
127
128 #[test]
129 fn test_funding_exceeds_no_wumbo_limit() {
130         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
131         // them.
132         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
133         let chanmon_cfgs = create_chanmon_cfgs(2);
134         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
135         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
136         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
137         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
138
139         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
140                 Err(APIError::APIMisuseError { err }) => {
141                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
142                 },
143                 _ => panic!()
144         }
145 }
146
147 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
148         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
149         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
150         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
151         // in normal testing, we test it explicitly here.
152         let chanmon_cfgs = create_chanmon_cfgs(2);
153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
155         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
156         let default_config = UserConfig::default();
157
158         // Have node0 initiate a channel to node1 with aforementioned parameters
159         let mut push_amt = 100_000_000;
160         let feerate_per_kw = 253;
161         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
162         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
163         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
164
165         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None, None).unwrap();
166         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
167         if !send_from_initiator {
168                 open_channel_message.channel_reserve_satoshis = 0;
169                 open_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
170         }
171         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
172
173         // Extract the channel accept message from node1 to node0
174         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
175         if send_from_initiator {
176                 accept_channel_message.channel_reserve_satoshis = 0;
177                 accept_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
178         }
179         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
180         {
181                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
182                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
183                 let mut sender_node_per_peer_lock;
184                 let mut sender_node_peer_state_lock;
185
186                 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
187                 match channel_phase {
188                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
189                                 let chan_context = channel_phase.context_mut();
190                                 chan_context.holder_selected_channel_reserve_satoshis = 0;
191                                 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
192                         },
193                         _ => assert!(false),
194                 }
195         }
196
197         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
198         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
199         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
200
201         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
202         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
203         if send_from_initiator {
204                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
205                         // Note that for outbound channels we have to consider the commitment tx fee and the
206                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
207                         // well as an additional HTLC.
208                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
209         } else {
210                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
211         }
212 }
213
214 #[test]
215 fn test_counterparty_no_reserve() {
216         do_test_counterparty_no_reserve(true);
217         do_test_counterparty_no_reserve(false);
218 }
219
220 #[test]
221 fn test_async_inbound_update_fee() {
222         let chanmon_cfgs = create_chanmon_cfgs(2);
223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
225         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
226         create_announced_chan_between_nodes(&nodes, 0, 1);
227
228         // balancing
229         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
230
231         // A                                        B
232         // update_fee                            ->
233         // send (1) commitment_signed            -.
234         //                                       <- update_add_htlc/commitment_signed
235         // send (2) RAA (awaiting remote revoke) -.
236         // (1) commitment_signed is delivered    ->
237         //                                       .- send (3) RAA (awaiting remote revoke)
238         // (2) RAA is delivered                  ->
239         //                                       .- send (4) commitment_signed
240         //                                       <- (3) RAA is delivered
241         // send (5) commitment_signed            -.
242         //                                       <- (4) commitment_signed is delivered
243         // send (6) RAA                          -.
244         // (5) commitment_signed is delivered    ->
245         //                                       <- RAA
246         // (6) RAA is delivered                  ->
247
248         // First nodes[0] generates an update_fee
249         {
250                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
251                 *feerate_lock += 20;
252         }
253         nodes[0].node.timer_tick_occurred();
254         check_added_monitors!(nodes[0], 1);
255
256         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
257         assert_eq!(events_0.len(), 1);
258         let (update_msg, commitment_signed) = match events_0[0] { // (1)
259                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
260                         (update_fee.as_ref(), commitment_signed)
261                 },
262                 _ => panic!("Unexpected event"),
263         };
264
265         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
266
267         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
268         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
269         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
270                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
271         check_added_monitors!(nodes[1], 1);
272
273         let payment_event = {
274                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275                 assert_eq!(events_1.len(), 1);
276                 SendEvent::from_event(events_1.remove(0))
277         };
278         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279         assert_eq!(payment_event.msgs.len(), 1);
280
281         // ...now when the messages get delivered everyone should be happy
282         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286         check_added_monitors!(nodes[0], 1);
287
288         // deliver(1), generate (3):
289         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
290         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
291         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
292         check_added_monitors!(nodes[1], 1);
293
294         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
295         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
296         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
298         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
299         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
300         assert!(bs_update.update_fee.is_none()); // (4)
301         check_added_monitors!(nodes[1], 1);
302
303         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
304         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
305         assert!(as_update.update_add_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
307         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
308         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
309         assert!(as_update.update_fee.is_none()); // (5)
310         check_added_monitors!(nodes[0], 1);
311
312         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
313         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
314         // only (6) so get_event_msg's assert(len == 1) passes
315         check_added_monitors!(nodes[0], 1);
316
317         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
318         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
319         check_added_monitors!(nodes[1], 1);
320
321         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
322         check_added_monitors!(nodes[0], 1);
323
324         let events_2 = nodes[0].node.get_and_clear_pending_events();
325         assert_eq!(events_2.len(), 1);
326         match events_2[0] {
327                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
328                 _ => panic!("Unexpected event"),
329         }
330
331         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
332         check_added_monitors!(nodes[1], 1);
333 }
334
335 #[test]
336 fn test_update_fee_unordered_raa() {
337         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
338         // crash in an earlier version of the update_fee patch)
339         let chanmon_cfgs = create_chanmon_cfgs(2);
340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
342         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
343         create_announced_chan_between_nodes(&nodes, 0, 1);
344
345         // balancing
346         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
347
348         // First nodes[0] generates an update_fee
349         {
350                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
351                 *feerate_lock += 20;
352         }
353         nodes[0].node.timer_tick_occurred();
354         check_added_monitors!(nodes[0], 1);
355
356         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
357         assert_eq!(events_0.len(), 1);
358         let update_msg = match events_0[0] { // (1)
359                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
360                         update_fee.as_ref()
361                 },
362                 _ => panic!("Unexpected event"),
363         };
364
365         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
366
367         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
368         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
369         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
370                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
371         check_added_monitors!(nodes[1], 1);
372
373         let payment_event = {
374                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
375                 assert_eq!(events_1.len(), 1);
376                 SendEvent::from_event(events_1.remove(0))
377         };
378         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
379         assert_eq!(payment_event.msgs.len(), 1);
380
381         // ...now when the messages get delivered everyone should be happy
382         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
383         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
384         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
385         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
386         check_added_monitors!(nodes[0], 1);
387
388         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
389         check_added_monitors!(nodes[1], 1);
390
391         // We can't continue, sadly, because our (1) now has a bogus signature
392 }
393
394 #[test]
395 fn test_multi_flight_update_fee() {
396         let chanmon_cfgs = create_chanmon_cfgs(2);
397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
399         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
400         create_announced_chan_between_nodes(&nodes, 0, 1);
401
402         // A                                        B
403         // update_fee/commitment_signed          ->
404         //                                       .- send (1) RAA and (2) commitment_signed
405         // update_fee (never committed)          ->
406         // (3) update_fee                        ->
407         // We have to manually generate the above update_fee, it is allowed by the protocol but we
408         // don't track which updates correspond to which revoke_and_ack responses so we're in
409         // AwaitingRAA mode and will not generate the update_fee yet.
410         //                                       <- (1) RAA delivered
411         // (3) is generated and send (4) CS      -.
412         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
413         // know the per_commitment_point to use for it.
414         //                                       <- (2) commitment_signed delivered
415         // revoke_and_ack                        ->
416         //                                          B should send no response here
417         // (4) commitment_signed delivered       ->
418         //                                       <- RAA/commitment_signed delivered
419         // revoke_and_ack                        ->
420
421         // First nodes[0] generates an update_fee
422         let initial_feerate;
423         {
424                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
425                 initial_feerate = *feerate_lock;
426                 *feerate_lock = initial_feerate + 20;
427         }
428         nodes[0].node.timer_tick_occurred();
429         check_added_monitors!(nodes[0], 1);
430
431         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
432         assert_eq!(events_0.len(), 1);
433         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
434                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
435                         (update_fee.as_ref().unwrap(), commitment_signed)
436                 },
437                 _ => panic!("Unexpected event"),
438         };
439
440         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
441         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
442         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
443         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
444         check_added_monitors!(nodes[1], 1);
445
446         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
447         // transaction:
448         {
449                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
450                 *feerate_lock = initial_feerate + 40;
451         }
452         nodes[0].node.timer_tick_occurred();
453         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
454         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
455
456         // Create the (3) update_fee message that nodes[0] will generate before it does...
457         let mut update_msg_2 = msgs::UpdateFee {
458                 channel_id: update_msg_1.channel_id.clone(),
459                 feerate_per_kw: (initial_feerate + 30) as u32,
460         };
461
462         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
463
464         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
465         // Deliver (3)
466         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
467
468         // Deliver (1), generating (3) and (4)
469         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
470         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
471         check_added_monitors!(nodes[0], 1);
472         assert!(as_second_update.update_add_htlcs.is_empty());
473         assert!(as_second_update.update_fulfill_htlcs.is_empty());
474         assert!(as_second_update.update_fail_htlcs.is_empty());
475         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
476         // Check that the update_fee newly generated matches what we delivered:
477         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
478         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
479
480         // Deliver (2) commitment_signed
481         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
482         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
483         check_added_monitors!(nodes[0], 1);
484         // No commitment_signed so get_event_msg's assert(len == 1) passes
485
486         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
487         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
488         check_added_monitors!(nodes[1], 1);
489
490         // Delever (4)
491         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
492         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
493         check_added_monitors!(nodes[1], 1);
494
495         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
496         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
497         check_added_monitors!(nodes[0], 1);
498
499         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
500         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
501         // No commitment_signed so get_event_msg's assert(len == 1) passes
502         check_added_monitors!(nodes[0], 1);
503
504         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
505         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
506         check_added_monitors!(nodes[1], 1);
507 }
508
509 fn do_test_sanity_on_in_flight_opens(steps: u8) {
510         // Previously, we had issues deserializing channels when we hadn't connected the first block
511         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
512         // serialization round-trips and simply do steps towards opening a channel and then drop the
513         // Node objects.
514
515         let chanmon_cfgs = create_chanmon_cfgs(2);
516         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
517         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
518         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
519
520         if steps & 0b1000_0000 != 0{
521                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
522                 connect_block(&nodes[0], &block);
523                 connect_block(&nodes[1], &block);
524         }
525
526         if steps & 0x0f == 0 { return; }
527         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
528         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
529
530         if steps & 0x0f == 1 { return; }
531         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
532         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
533
534         if steps & 0x0f == 2 { return; }
535         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
536
537         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
538
539         if steps & 0x0f == 3 { return; }
540         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
541         check_added_monitors!(nodes[0], 0);
542         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
543
544         if steps & 0x0f == 4 { return; }
545         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
546         {
547                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
548                 assert_eq!(added_monitors.len(), 1);
549                 assert_eq!(added_monitors[0].0, funding_output);
550                 added_monitors.clear();
551         }
552         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
553
554         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
555
556         if steps & 0x0f == 5 { return; }
557         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
558         {
559                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
560                 assert_eq!(added_monitors.len(), 1);
561                 assert_eq!(added_monitors[0].0, funding_output);
562                 added_monitors.clear();
563         }
564
565         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
566         let events_4 = nodes[0].node.get_and_clear_pending_events();
567         assert_eq!(events_4.len(), 0);
568
569         if steps & 0x0f == 6 { return; }
570         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
571
572         if steps & 0x0f == 7 { return; }
573         confirm_transaction_at(&nodes[0], &tx, 2);
574         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
575         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
576         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
577 }
578
579 #[test]
580 fn test_sanity_on_in_flight_opens() {
581         do_test_sanity_on_in_flight_opens(0);
582         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(1);
584         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(2);
586         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(3);
588         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(4);
590         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
591         do_test_sanity_on_in_flight_opens(5);
592         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
593         do_test_sanity_on_in_flight_opens(6);
594         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
595         do_test_sanity_on_in_flight_opens(7);
596         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
597         do_test_sanity_on_in_flight_opens(8);
598         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
599 }
600
601 #[test]
602 fn test_update_fee_vanilla() {
603         let chanmon_cfgs = create_chanmon_cfgs(2);
604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
607         create_announced_chan_between_nodes(&nodes, 0, 1);
608
609         {
610                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
611                 *feerate_lock += 25;
612         }
613         nodes[0].node.timer_tick_occurred();
614         check_added_monitors!(nodes[0], 1);
615
616         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
617         assert_eq!(events_0.len(), 1);
618         let (update_msg, commitment_signed) = match events_0[0] {
619                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
620                         (update_fee.as_ref(), commitment_signed)
621                 },
622                 _ => panic!("Unexpected event"),
623         };
624         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
625
626         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
627         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
628         check_added_monitors!(nodes[1], 1);
629
630         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
631         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
632         check_added_monitors!(nodes[0], 1);
633
634         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
635         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
636         // No commitment_signed so get_event_msg's assert(len == 1) passes
637         check_added_monitors!(nodes[0], 1);
638
639         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
640         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
641         check_added_monitors!(nodes[1], 1);
642 }
643
644 #[test]
645 fn test_update_fee_that_funder_cannot_afford() {
646         let chanmon_cfgs = create_chanmon_cfgs(2);
647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
649         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
650         let channel_value = 5000;
651         let push_sats = 700;
652         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
653         let channel_id = chan.2;
654         let secp_ctx = Secp256k1::new();
655         let default_config = UserConfig::default();
656         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
657
658         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
659
660         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
661         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
662         // calculate two different feerates here - the expected local limit as well as the expected
663         // remote limit.
664         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(&channel_type_features) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
665         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
666         {
667                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
668                 *feerate_lock = feerate;
669         }
670         nodes[0].node.timer_tick_occurred();
671         check_added_monitors!(nodes[0], 1);
672         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
673
674         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
675
676         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
677
678         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
679         {
680                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
681
682                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
683                 assert_eq!(commitment_tx.output.len(), 2);
684                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
685                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
686                 actual_fee = channel_value - actual_fee;
687                 assert_eq!(total_fee, actual_fee);
688         }
689
690         {
691                 // Increment the feerate by a small constant, accounting for rounding errors
692                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
693                 *feerate_lock += 4;
694         }
695         nodes[0].node.timer_tick_occurred();
696         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
697         check_added_monitors!(nodes[0], 0);
698
699         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
700
701         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
702         // needed to sign the new commitment tx and (2) sign the new commitment tx.
703         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
704                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
705                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
706                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
707                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
708                 ).flatten().unwrap();
709                 let chan_signer = local_chan.get_signer();
710                 let pubkeys = chan_signer.as_ref().pubkeys();
711                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
712                  pubkeys.funding_pubkey)
713         };
714         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
715                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
716                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
717                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
718                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
719                 ).flatten().unwrap();
720                 let chan_signer = remote_chan.get_signer();
721                 let pubkeys = chan_signer.as_ref().pubkeys();
722                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
723                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
724                  pubkeys.funding_pubkey)
725         };
726
727         // Assemble the set of keys we can use for signatures for our commitment_signed message.
728         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
729                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
730
731         let res = {
732                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
733                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
734                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
735                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
736                 ).flatten().unwrap();
737                 let local_chan_signer = local_chan.get_signer();
738                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
739                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
740                         INITIAL_COMMITMENT_NUMBER - 1,
741                         push_sats,
742                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
743                         local_funding, remote_funding,
744                         commit_tx_keys.clone(),
745                         non_buffer_feerate + 4,
746                         &mut htlcs,
747                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
748                 );
749                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
750         };
751
752         let commit_signed_msg = msgs::CommitmentSigned {
753                 channel_id: chan.2,
754                 signature: res.0,
755                 htlc_signatures: res.1,
756                 #[cfg(taproot)]
757                 partial_signature_with_nonce: None,
758         };
759
760         let update_fee = msgs::UpdateFee {
761                 channel_id: chan.2,
762                 feerate_per_kw: non_buffer_feerate + 4,
763         };
764
765         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
766
767         //While producing the commitment_signed response after handling a received update_fee request the
768         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
769         //Should produce and error.
770         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
771         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee", 3);
772         check_added_monitors!(nodes[1], 1);
773         check_closed_broadcast!(nodes[1], true);
774         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
775                 [nodes[0].node.get_our_node_id()], channel_value);
776 }
777
778 #[test]
779 fn test_update_fee_with_fundee_update_add_htlc() {
780         let chanmon_cfgs = create_chanmon_cfgs(2);
781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
783         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
784         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
785
786         // balancing
787         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
788
789         {
790                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
791                 *feerate_lock += 20;
792         }
793         nodes[0].node.timer_tick_occurred();
794         check_added_monitors!(nodes[0], 1);
795
796         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
797         assert_eq!(events_0.len(), 1);
798         let (update_msg, commitment_signed) = match events_0[0] {
799                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
800                         (update_fee.as_ref(), commitment_signed)
801                 },
802                 _ => panic!("Unexpected event"),
803         };
804         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
805         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
806         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807         check_added_monitors!(nodes[1], 1);
808
809         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
810
811         // nothing happens since node[1] is in AwaitingRemoteRevoke
812         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
813                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
814         {
815                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
816                 assert_eq!(added_monitors.len(), 0);
817                 added_monitors.clear();
818         }
819         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
820         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
821         // node[1] has nothing to do
822
823         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
824         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
825         check_added_monitors!(nodes[0], 1);
826
827         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
828         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
829         // No commitment_signed so get_event_msg's assert(len == 1) passes
830         check_added_monitors!(nodes[0], 1);
831         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
832         check_added_monitors!(nodes[1], 1);
833         // AwaitingRemoteRevoke ends here
834
835         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
837         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
838         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
839         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
840         assert_eq!(commitment_update.update_fee.is_none(), true);
841
842         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
843         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
844         check_added_monitors!(nodes[0], 1);
845         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
846
847         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
848         check_added_monitors!(nodes[1], 1);
849         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
850
851         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
852         check_added_monitors!(nodes[1], 1);
853         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
854         // No commitment_signed so get_event_msg's assert(len == 1) passes
855
856         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
857         check_added_monitors!(nodes[0], 1);
858         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
859
860         expect_pending_htlcs_forwardable!(nodes[0]);
861
862         let events = nodes[0].node.get_and_clear_pending_events();
863         assert_eq!(events.len(), 1);
864         match events[0] {
865                 Event::PaymentClaimable { .. } => { },
866                 _ => panic!("Unexpected event"),
867         };
868
869         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
870
871         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
872         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
873         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
874         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
875         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
876 }
877
878 #[test]
879 fn test_update_fee() {
880         let chanmon_cfgs = create_chanmon_cfgs(2);
881         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
882         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
883         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
884         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
885         let channel_id = chan.2;
886
887         // A                                        B
888         // (1) update_fee/commitment_signed      ->
889         //                                       <- (2) revoke_and_ack
890         //                                       .- send (3) commitment_signed
891         // (4) update_fee/commitment_signed      ->
892         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
893         //                                       <- (3) commitment_signed delivered
894         // send (6) revoke_and_ack               -.
895         //                                       <- (5) deliver revoke_and_ack
896         // (6) deliver revoke_and_ack            ->
897         //                                       .- send (7) commitment_signed in response to (4)
898         //                                       <- (7) deliver commitment_signed
899         // revoke_and_ack                        ->
900
901         // Create and deliver (1)...
902         let feerate;
903         {
904                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905                 feerate = *feerate_lock;
906                 *feerate_lock = feerate + 20;
907         }
908         nodes[0].node.timer_tick_occurred();
909         check_added_monitors!(nodes[0], 1);
910
911         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
912         assert_eq!(events_0.len(), 1);
913         let (update_msg, commitment_signed) = match events_0[0] {
914                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
915                         (update_fee.as_ref(), commitment_signed)
916                 },
917                 _ => panic!("Unexpected event"),
918         };
919         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920
921         // Generate (2) and (3):
922         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
923         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
924         check_added_monitors!(nodes[1], 1);
925
926         // Deliver (2):
927         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929         check_added_monitors!(nodes[0], 1);
930
931         // Create and deliver (4)...
932         {
933                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
934                 *feerate_lock = feerate + 30;
935         }
936         nodes[0].node.timer_tick_occurred();
937         check_added_monitors!(nodes[0], 1);
938         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
939         assert_eq!(events_0.len(), 1);
940         let (update_msg, commitment_signed) = match events_0[0] {
941                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
942                         (update_fee.as_ref(), commitment_signed)
943                 },
944                 _ => panic!("Unexpected event"),
945         };
946
947         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
948         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
949         check_added_monitors!(nodes[1], 1);
950         // ... creating (5)
951         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
952         // No commitment_signed so get_event_msg's assert(len == 1) passes
953
954         // Handle (3), creating (6):
955         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
956         check_added_monitors!(nodes[0], 1);
957         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
958         // No commitment_signed so get_event_msg's assert(len == 1) passes
959
960         // Deliver (5):
961         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
962         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
963         check_added_monitors!(nodes[0], 1);
964
965         // Deliver (6), creating (7):
966         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
967         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
968         assert!(commitment_update.update_add_htlcs.is_empty());
969         assert!(commitment_update.update_fulfill_htlcs.is_empty());
970         assert!(commitment_update.update_fail_htlcs.is_empty());
971         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
972         assert!(commitment_update.update_fee.is_none());
973         check_added_monitors!(nodes[1], 1);
974
975         // Deliver (7)
976         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
977         check_added_monitors!(nodes[0], 1);
978         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
979         // No commitment_signed so get_event_msg's assert(len == 1) passes
980
981         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
982         check_added_monitors!(nodes[1], 1);
983         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
984
985         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
986         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
987         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
988         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
989         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
990 }
991
992 #[test]
993 fn fake_network_test() {
994         // Simple test which builds a network of ChannelManagers, connects them to each other, and
995         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
996         let chanmon_cfgs = create_chanmon_cfgs(4);
997         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
998         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
999         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1000
1001         // Create some initial channels
1002         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1003         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1004         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1005
1006         // Rebalance the network a bit by relaying one payment through all the channels...
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1008         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1009         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1010         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1011
1012         // Send some more payments
1013         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1014         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1015         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1016
1017         // Test failure packets
1018         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1019         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1020
1021         // Add a new channel that skips 3
1022         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1023
1024         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1025         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1026         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1027         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1028         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1029         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1030         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1031
1032         // Do some rebalance loop payments, simultaneously
1033         let mut hops = Vec::with_capacity(3);
1034         hops.push(RouteHop {
1035                 pubkey: nodes[2].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_2.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1041                 maybe_announced_channel: true,
1042         });
1043         hops.push(RouteHop {
1044                 pubkey: nodes[3].node.get_our_node_id(),
1045                 node_features: NodeFeatures::empty(),
1046                 short_channel_id: chan_3.0.contents.short_channel_id,
1047                 channel_features: ChannelFeatures::empty(),
1048                 fee_msat: 0,
1049                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1050                 maybe_announced_channel: true,
1051         });
1052         hops.push(RouteHop {
1053                 pubkey: nodes[1].node.get_our_node_id(),
1054                 node_features: nodes[1].node.node_features(),
1055                 short_channel_id: chan_4.0.contents.short_channel_id,
1056                 channel_features: nodes[1].node.channel_features(),
1057                 fee_msat: 1000000,
1058                 cltv_expiry_delta: TEST_FINAL_CLTV,
1059                 maybe_announced_channel: true,
1060         });
1061         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1062         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1063         let payment_preimage_1 = send_along_route(&nodes[1],
1064                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1065                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1066
1067         let mut hops = Vec::with_capacity(3);
1068         hops.push(RouteHop {
1069                 pubkey: nodes[3].node.get_our_node_id(),
1070                 node_features: NodeFeatures::empty(),
1071                 short_channel_id: chan_4.0.contents.short_channel_id,
1072                 channel_features: ChannelFeatures::empty(),
1073                 fee_msat: 0,
1074                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1075                 maybe_announced_channel: true,
1076         });
1077         hops.push(RouteHop {
1078                 pubkey: nodes[2].node.get_our_node_id(),
1079                 node_features: NodeFeatures::empty(),
1080                 short_channel_id: chan_3.0.contents.short_channel_id,
1081                 channel_features: ChannelFeatures::empty(),
1082                 fee_msat: 0,
1083                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1084                 maybe_announced_channel: true,
1085         });
1086         hops.push(RouteHop {
1087                 pubkey: nodes[1].node.get_our_node_id(),
1088                 node_features: nodes[1].node.node_features(),
1089                 short_channel_id: chan_2.0.contents.short_channel_id,
1090                 channel_features: nodes[1].node.channel_features(),
1091                 fee_msat: 1000000,
1092                 cltv_expiry_delta: TEST_FINAL_CLTV,
1093                 maybe_announced_channel: true,
1094         });
1095         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1096         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1097         let payment_hash_2 = send_along_route(&nodes[1],
1098                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1099                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1100
1101         // Claim the rebalances...
1102         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1103         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1104
1105         // Close down the channels...
1106         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1107         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1108         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1109         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1110         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1111         check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1112         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1113         check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1114         check_closed_event!(nodes[3], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1115         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1116         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1117         check_closed_event!(nodes[3], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1118 }
1119
1120 #[test]
1121 fn holding_cell_htlc_counting() {
1122         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1123         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1124         // commitment dance rounds.
1125         let chanmon_cfgs = create_chanmon_cfgs(3);
1126         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1127         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1128         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1129         create_announced_chan_between_nodes(&nodes, 0, 1);
1130         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1131
1132         // Fetch a route in advance as we will be unable to once we're unable to send.
1133         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1134
1135         let mut payments = Vec::new();
1136         for _ in 0..50 {
1137                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1138                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1139                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1140                 payments.push((payment_preimage, payment_hash));
1141         }
1142         check_added_monitors!(nodes[1], 1);
1143
1144         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1145         assert_eq!(events.len(), 1);
1146         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1147         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1148
1149         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1150         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1151         // another HTLC.
1152         {
1153                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1154                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1155                         ), true, APIError::ChannelUnavailable { .. }, {});
1156                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1157         }
1158
1159         // This should also be true if we try to forward a payment.
1160         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1161         {
1162                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1163                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1164                 check_added_monitors!(nodes[0], 1);
1165         }
1166
1167         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1168         assert_eq!(events.len(), 1);
1169         let payment_event = SendEvent::from_event(events.pop().unwrap());
1170         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1171
1172         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1173         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1174         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1175         // fails), the second will process the resulting failure and fail the HTLC backward.
1176         expect_pending_htlcs_forwardable!(nodes[1]);
1177         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1178         check_added_monitors!(nodes[1], 1);
1179
1180         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1181         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1182         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1183
1184         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1185
1186         // Now forward all the pending HTLCs and claim them back
1187         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1188         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1189         check_added_monitors!(nodes[2], 1);
1190
1191         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1192         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1193         check_added_monitors!(nodes[1], 1);
1194         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1195
1196         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1197         check_added_monitors!(nodes[1], 1);
1198         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1199
1200         for ref update in as_updates.update_add_htlcs.iter() {
1201                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1202         }
1203         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1204         check_added_monitors!(nodes[2], 1);
1205         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1206         check_added_monitors!(nodes[2], 1);
1207         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1208
1209         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1210         check_added_monitors!(nodes[1], 1);
1211         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1212         check_added_monitors!(nodes[1], 1);
1213         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1214
1215         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1216         check_added_monitors!(nodes[2], 1);
1217
1218         expect_pending_htlcs_forwardable!(nodes[2]);
1219
1220         let events = nodes[2].node.get_and_clear_pending_events();
1221         assert_eq!(events.len(), payments.len());
1222         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1223                 match event {
1224                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1225                                 assert_eq!(*payment_hash, *hash);
1226                         },
1227                         _ => panic!("Unexpected event"),
1228                 };
1229         }
1230
1231         for (preimage, _) in payments.drain(..) {
1232                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1233         }
1234
1235         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1236 }
1237
1238 #[test]
1239 fn duplicate_htlc_test() {
1240         // Test that we accept duplicate payment_hash HTLCs across the network and that
1241         // claiming/failing them are all separate and don't affect each other
1242         let chanmon_cfgs = create_chanmon_cfgs(6);
1243         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1244         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1245         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1246
1247         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1248         create_announced_chan_between_nodes(&nodes, 0, 3);
1249         create_announced_chan_between_nodes(&nodes, 1, 3);
1250         create_announced_chan_between_nodes(&nodes, 2, 3);
1251         create_announced_chan_between_nodes(&nodes, 3, 4);
1252         create_announced_chan_between_nodes(&nodes, 3, 5);
1253
1254         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1255
1256         *nodes[0].network_payment_count.borrow_mut() -= 1;
1257         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1258
1259         *nodes[0].network_payment_count.borrow_mut() -= 1;
1260         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1261
1262         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1263         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1264         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1265 }
1266
1267 #[test]
1268 fn test_duplicate_htlc_different_direction_onchain() {
1269         // Test that ChannelMonitor doesn't generate 2 preimage txn
1270         // when we have 2 HTLCs with same preimage that go across a node
1271         // in opposite directions, even with the same payment secret.
1272         let chanmon_cfgs = create_chanmon_cfgs(2);
1273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1276
1277         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1278
1279         // balancing
1280         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1281
1282         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1283
1284         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1285         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1286         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1287
1288         // Provide preimage to node 0 by claiming payment
1289         nodes[0].node.claim_funds(payment_preimage);
1290         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1291         check_added_monitors!(nodes[0], 1);
1292
1293         // Broadcast node 1 commitment txn
1294         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1295
1296         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1297         let mut has_both_htlcs = 0; // check htlcs match ones committed
1298         for outp in remote_txn[0].output.iter() {
1299                 if outp.value == 800_000 / 1000 {
1300                         has_both_htlcs += 1;
1301                 } else if outp.value == 900_000 / 1000 {
1302                         has_both_htlcs += 1;
1303                 }
1304         }
1305         assert_eq!(has_both_htlcs, 2);
1306
1307         mine_transaction(&nodes[0], &remote_txn[0]);
1308         check_added_monitors!(nodes[0], 1);
1309         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1310         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1311
1312         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1313         assert_eq!(claim_txn.len(), 3);
1314
1315         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1316         check_spends!(claim_txn[1], remote_txn[0]);
1317         check_spends!(claim_txn[2], remote_txn[0]);
1318         let preimage_tx = &claim_txn[0];
1319         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1320                 (&claim_txn[1], &claim_txn[2])
1321         } else {
1322                 (&claim_txn[2], &claim_txn[1])
1323         };
1324
1325         assert_eq!(preimage_tx.input.len(), 1);
1326         assert_eq!(preimage_bump_tx.input.len(), 1);
1327
1328         assert_eq!(preimage_tx.input.len(), 1);
1329         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1330         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1331
1332         assert_eq!(timeout_tx.input.len(), 1);
1333         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1334         check_spends!(timeout_tx, remote_txn[0]);
1335         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1336
1337         let events = nodes[0].node.get_and_clear_pending_msg_events();
1338         assert_eq!(events.len(), 3);
1339         for e in events {
1340                 match e {
1341                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1342                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1343                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1344                                 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1345                         },
1346                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1347                                 assert!(update_add_htlcs.is_empty());
1348                                 assert!(update_fail_htlcs.is_empty());
1349                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1350                                 assert!(update_fail_malformed_htlcs.is_empty());
1351                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1352                         },
1353                         _ => panic!("Unexpected event"),
1354                 }
1355         }
1356 }
1357
1358 #[test]
1359 fn test_basic_channel_reserve() {
1360         let chanmon_cfgs = create_chanmon_cfgs(2);
1361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1365
1366         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1367         let channel_reserve = chan_stat.channel_reserve_msat;
1368
1369         // The 2* and +1 are for the fee spike reserve.
1370         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, &get_channel_type_features!(nodes[0], nodes[1], chan.2));
1371         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1372         let (mut route, our_payment_hash, _, our_payment_secret) =
1373                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1374         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1375         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1376                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1377         match err {
1378                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1379                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1380                         else { panic!("Unexpected error variant"); }
1381                 },
1382                 _ => panic!("Unexpected error variant"),
1383         }
1384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1385
1386         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1387 }
1388
1389 #[test]
1390 fn test_fee_spike_violation_fails_htlc() {
1391         let chanmon_cfgs = create_chanmon_cfgs(2);
1392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1395         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1396
1397         let (mut route, payment_hash, _, payment_secret) =
1398                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1399         route.paths[0].hops[0].fee_msat += 1;
1400         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1401         let secp_ctx = Secp256k1::new();
1402         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1403
1404         let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;
1405
1406         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1407         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1408                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1409         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1410         let msg = msgs::UpdateAddHTLC {
1411                 channel_id: chan.2,
1412                 htlc_id: 0,
1413                 amount_msat: htlc_msat,
1414                 payment_hash: payment_hash,
1415                 cltv_expiry: htlc_cltv,
1416                 onion_routing_packet: onion_packet,
1417                 skimmed_fee_msat: None,
1418                 blinding_point: None,
1419         };
1420
1421         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1422
1423         // Now manually create the commitment_signed message corresponding to the update_add
1424         // nodes[0] just sent. In the code for construction of this message, "local" refers
1425         // to the sender of the message, and "remote" refers to the receiver.
1426
1427         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1428
1429         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1430
1431         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1432         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1433         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1434                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1435                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1436                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1437                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1438                 ).flatten().unwrap();
1439                 let chan_signer = local_chan.get_signer();
1440                 // Make the signer believe we validated another commitment, so we can release the secret
1441                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1442
1443                 let pubkeys = chan_signer.as_ref().pubkeys();
1444                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1445                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1446                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1447                  chan_signer.as_ref().pubkeys().funding_pubkey)
1448         };
1449         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1450                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1451                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1452                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1453                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1454                 ).flatten().unwrap();
1455                 let chan_signer = remote_chan.get_signer();
1456                 let pubkeys = chan_signer.as_ref().pubkeys();
1457                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1458                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1459                  chan_signer.as_ref().pubkeys().funding_pubkey)
1460         };
1461
1462         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1463         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1464                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1465
1466         // Build the remote commitment transaction so we can sign it, and then later use the
1467         // signature for the commitment_signed message.
1468         let local_chan_balance = 1313;
1469
1470         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1471                 offered: false,
1472                 amount_msat: 3460001,
1473                 cltv_expiry: htlc_cltv,
1474                 payment_hash,
1475                 transaction_output_index: Some(1),
1476         };
1477
1478         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1479
1480         let res = {
1481                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1482                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1483                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1484                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1485                 ).flatten().unwrap();
1486                 let local_chan_signer = local_chan.get_signer();
1487                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1488                         commitment_number,
1489                         95000,
1490                         local_chan_balance,
1491                         local_funding, remote_funding,
1492                         commit_tx_keys.clone(),
1493                         feerate_per_kw,
1494                         &mut vec![(accepted_htlc_info, ())],
1495                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1496                 );
1497                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
1498         };
1499
1500         let commit_signed_msg = msgs::CommitmentSigned {
1501                 channel_id: chan.2,
1502                 signature: res.0,
1503                 htlc_signatures: res.1,
1504                 #[cfg(taproot)]
1505                 partial_signature_with_nonce: None,
1506         };
1507
1508         // Send the commitment_signed message to the nodes[1].
1509         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1510         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1511
1512         // Send the RAA to nodes[1].
1513         let raa_msg = msgs::RevokeAndACK {
1514                 channel_id: chan.2,
1515                 per_commitment_secret: local_secret,
1516                 next_per_commitment_point: next_local_point,
1517                 #[cfg(taproot)]
1518                 next_local_nonce: None,
1519         };
1520         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1521
1522         let events = nodes[1].node.get_and_clear_pending_msg_events();
1523         assert_eq!(events.len(), 1);
1524         // Make sure the HTLC failed in the way we expect.
1525         match events[0] {
1526                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1527                         assert_eq!(update_fail_htlcs.len(), 1);
1528                         update_fail_htlcs[0].clone()
1529                 },
1530                 _ => panic!("Unexpected event"),
1531         };
1532         nodes[1].logger.assert_log("lightning::ln::channel",
1533                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1534
1535         check_added_monitors!(nodes[1], 2);
1536 }
1537
1538 #[test]
1539 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1540         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1541         // Set the fee rate for the channel very high, to the point where the fundee
1542         // sending any above-dust amount would result in a channel reserve violation.
1543         // In this test we check that we would be prevented from sending an HTLC in
1544         // this situation.
1545         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1548         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1549         let default_config = UserConfig::default();
1550         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1551
1552         let mut push_amt = 100_000_000;
1553         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1554
1555         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1556
1557         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1558
1559         // Fetch a route in advance as we will be unable to once we're unable to send.
1560         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1561         // Sending exactly enough to hit the reserve amount should be accepted
1562         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1564         }
1565
1566         // However one more HTLC should be significantly over the reserve amount and fail.
1567         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1568                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1569                 ), true, APIError::ChannelUnavailable { .. }, {});
1570         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1571 }
1572
1573 #[test]
1574 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1575         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1576         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1579         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1580         let default_config = UserConfig::default();
1581         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1582
1583         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1584         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1585         // transaction fee with 0 HTLCs (183 sats)).
1586         let mut push_amt = 100_000_000;
1587         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1588         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1589         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1590
1591         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1592         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1593                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1594         }
1595
1596         let (mut route, payment_hash, _, payment_secret) =
1597                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1598         route.paths[0].hops[0].fee_msat = 700_000;
1599         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1600         let secp_ctx = Secp256k1::new();
1601         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1602         let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;
1603         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1604         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1605                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1606         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1607         let msg = msgs::UpdateAddHTLC {
1608                 channel_id: chan.2,
1609                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1610                 amount_msat: htlc_msat,
1611                 payment_hash: payment_hash,
1612                 cltv_expiry: htlc_cltv,
1613                 onion_routing_packet: onion_packet,
1614                 skimmed_fee_msat: None,
1615                 blinding_point: None,
1616         };
1617
1618         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1619         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1620         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value", 3);
1621         assert_eq!(nodes[0].node.list_channels().len(), 0);
1622         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1623         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1624         check_added_monitors!(nodes[0], 1);
1625         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() },
1626                 [nodes[1].node.get_our_node_id()], 100000);
1627 }
1628
1629 #[test]
1630 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1631         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1632         // calculating our commitment transaction fee (this was previously broken).
1633         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1634         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1635
1636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1639         let default_config = UserConfig::default();
1640         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1641
1642         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1643         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1644         // transaction fee with 0 HTLCs (183 sats)).
1645         let mut push_amt = 100_000_000;
1646         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1647         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1648         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1649
1650         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1651                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1652         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1653         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1654         // commitment transaction fee.
1655         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1656
1657         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1658         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1659                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1660         }
1661
1662         // One more than the dust amt should fail, however.
1663         let (mut route, our_payment_hash, _, our_payment_secret) =
1664                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1665         route.paths[0].hops[0].fee_msat += 1;
1666         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1667                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1668                 ), true, APIError::ChannelUnavailable { .. }, {});
1669 }
1670
1671 #[test]
1672 fn test_chan_init_feerate_unaffordability() {
1673         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1674         // channel reserve and feerate requirements.
1675         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1676         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680         let default_config = UserConfig::default();
1681         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1682
1683         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1684         // HTLC.
1685         let mut push_amt = 100_000_000;
1686         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1687         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1688                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1689
1690         // During open, we don't have a "counterparty channel reserve" to check against, so that
1691         // requirement only comes into play on the open_channel handling side.
1692         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1693         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1694         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1695         open_channel_msg.push_msat += 1;
1696         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1697
1698         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1699         assert_eq!(msg_events.len(), 1);
1700         match msg_events[0] {
1701                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1702                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1703                 },
1704                 _ => panic!("Unexpected event"),
1705         }
1706 }
1707
1708 #[test]
1709 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1710         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1711         // calculating our counterparty's commitment transaction fee (this was previously broken).
1712         let chanmon_cfgs = create_chanmon_cfgs(2);
1713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1715         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1716         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1717
1718         let payment_amt = 46000; // Dust amount
1719         // In the previous code, these first four payments would succeed.
1720         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1722         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1723         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1724
1725         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1726         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1728         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1729         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1730         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1731
1732         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1733         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1734         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1735         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1736 }
1737
1738 #[test]
1739 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1740         let chanmon_cfgs = create_chanmon_cfgs(3);
1741         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1742         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1743         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1744         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1745         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1746
1747         let feemsat = 239;
1748         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1749         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1750         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1751         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1752
1753         // Add a 2* and +1 for the fee spike reserve.
1754         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1755         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1756         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1757
1758         // Add a pending HTLC.
1759         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1760         let payment_event_1 = {
1761                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1762                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1763                 check_added_monitors!(nodes[0], 1);
1764
1765                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1766                 assert_eq!(events.len(), 1);
1767                 SendEvent::from_event(events.remove(0))
1768         };
1769         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1770
1771         // Attempt to trigger a channel reserve violation --> payment failure.
1772         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1773         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1774         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1775         let mut route_2 = route_1.clone();
1776         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1777
1778         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1779         let secp_ctx = Secp256k1::new();
1780         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1781         let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
1782         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1783         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1784                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1785         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1786         let msg = msgs::UpdateAddHTLC {
1787                 channel_id: chan.2,
1788                 htlc_id: 1,
1789                 amount_msat: htlc_msat + 1,
1790                 payment_hash: our_payment_hash_1,
1791                 cltv_expiry: htlc_cltv,
1792                 onion_routing_packet: onion_packet,
1793                 skimmed_fee_msat: None,
1794                 blinding_point: None,
1795         };
1796
1797         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1798         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1799         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value", 3);
1800         assert_eq!(nodes[1].node.list_channels().len(), 1);
1801         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1802         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1803         check_added_monitors!(nodes[1], 1);
1804         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1805                 [nodes[0].node.get_our_node_id()], 100000);
1806 }
1807
1808 #[test]
1809 fn test_inbound_outbound_capacity_is_not_zero() {
1810         let chanmon_cfgs = create_chanmon_cfgs(2);
1811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1814         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1815         let channels0 = node_chanmgrs[0].list_channels();
1816         let channels1 = node_chanmgrs[1].list_channels();
1817         let default_config = UserConfig::default();
1818         assert_eq!(channels0.len(), 1);
1819         assert_eq!(channels1.len(), 1);
1820
1821         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1822         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1823         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1824
1825         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1826         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1827 }
1828
1829 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1830         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1831 }
1832
1833 #[test]
1834 fn test_channel_reserve_holding_cell_htlcs() {
1835         let chanmon_cfgs = create_chanmon_cfgs(3);
1836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837         // When this test was written, the default base fee floated based on the HTLC count.
1838         // It is now fixed, so we simply set the fee to the expected value here.
1839         let mut config = test_default_channel_config();
1840         config.channel_config.forwarding_fee_base_msat = 239;
1841         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1842         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1843         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1844         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1845
1846         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1847         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1848
1849         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1850         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1851
1852         macro_rules! expect_forward {
1853                 ($node: expr) => {{
1854                         let mut events = $node.node.get_and_clear_pending_msg_events();
1855                         assert_eq!(events.len(), 1);
1856                         check_added_monitors!($node, 1);
1857                         let payment_event = SendEvent::from_event(events.remove(0));
1858                         payment_event
1859                 }}
1860         }
1861
1862         let feemsat = 239; // set above
1863         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1864         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1865         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1866
1867         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1868
1869         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1870         {
1871                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1872                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1873                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1874                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1875                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1876
1877                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1878                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1879                         ), true, APIError::ChannelUnavailable { .. }, {});
1880                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1881         }
1882
1883         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1884         // nodes[0]'s wealth
1885         loop {
1886                 let amt_msat = recv_value_0 + total_fee_msat;
1887                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1888                 // Also, ensure that each payment has enough to be over the dust limit to
1889                 // ensure it'll be included in each commit tx fee calculation.
1890                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1891                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1892                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1893                         break;
1894                 }
1895
1896                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1897                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1898                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1899                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1900                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1901
1902                 let (stat01_, stat11_, stat12_, stat22_) = (
1903                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1904                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1905                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1906                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1907                 );
1908
1909                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1910                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1911                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1912                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1913                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1914         }
1915
1916         // adding pending output.
1917         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1918         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1919         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1920         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1921         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1922         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1923         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1924         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1925         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1926         // policy.
1927         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1928         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1929         let amt_msat_1 = recv_value_1 + total_fee_msat;
1930
1931         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1932         let payment_event_1 = {
1933                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1934                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1935                 check_added_monitors!(nodes[0], 1);
1936
1937                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1938                 assert_eq!(events.len(), 1);
1939                 SendEvent::from_event(events.remove(0))
1940         };
1941         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1942
1943         // channel reserve test with htlc pending output > 0
1944         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1945         {
1946                 let mut route = route_1.clone();
1947                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1948                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1949                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1950                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1951                         ), true, APIError::ChannelUnavailable { .. }, {});
1952                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1953         }
1954
1955         // split the rest to test holding cell
1956         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1957         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1958         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1959         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1960         {
1961                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1962                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1963         }
1964
1965         // now see if they go through on both sides
1966         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1967         // but this will stuck in the holding cell
1968         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1969                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1970         check_added_monitors!(nodes[0], 0);
1971         let events = nodes[0].node.get_and_clear_pending_events();
1972         assert_eq!(events.len(), 0);
1973
1974         // test with outbound holding cell amount > 0
1975         {
1976                 let (mut route, our_payment_hash, _, our_payment_secret) =
1977                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1978                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1979                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1980                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1981                         ), true, APIError::ChannelUnavailable { .. }, {});
1982                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1983         }
1984
1985         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1986         // this will also stuck in the holding cell
1987         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1988                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1989         check_added_monitors!(nodes[0], 0);
1990         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1991         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1992
1993         // flush the pending htlc
1994         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1995         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1996         check_added_monitors!(nodes[1], 1);
1997
1998         // the pending htlc should be promoted to committed
1999         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2000         check_added_monitors!(nodes[0], 1);
2001         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2002
2003         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2004         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2005         // No commitment_signed so get_event_msg's assert(len == 1) passes
2006         check_added_monitors!(nodes[0], 1);
2007
2008         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2009         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2010         check_added_monitors!(nodes[1], 1);
2011
2012         expect_pending_htlcs_forwardable!(nodes[1]);
2013
2014         let ref payment_event_11 = expect_forward!(nodes[1]);
2015         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2016         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2017
2018         expect_pending_htlcs_forwardable!(nodes[2]);
2019         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2020
2021         // flush the htlcs in the holding cell
2022         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2023         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2024         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2025         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2026         expect_pending_htlcs_forwardable!(nodes[1]);
2027
2028         let ref payment_event_3 = expect_forward!(nodes[1]);
2029         assert_eq!(payment_event_3.msgs.len(), 2);
2030         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2031         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2032
2033         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2034         expect_pending_htlcs_forwardable!(nodes[2]);
2035
2036         let events = nodes[2].node.get_and_clear_pending_events();
2037         assert_eq!(events.len(), 2);
2038         match events[0] {
2039                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2040                         assert_eq!(our_payment_hash_21, *payment_hash);
2041                         assert_eq!(recv_value_21, amount_msat);
2042                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2043                         assert_eq!(via_channel_id, Some(chan_2.2));
2044                         match &purpose {
2045                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2046                                         assert!(payment_preimage.is_none());
2047                                         assert_eq!(our_payment_secret_21, *payment_secret);
2048                                 },
2049                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2050                         }
2051                 },
2052                 _ => panic!("Unexpected event"),
2053         }
2054         match events[1] {
2055                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2056                         assert_eq!(our_payment_hash_22, *payment_hash);
2057                         assert_eq!(recv_value_22, amount_msat);
2058                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2059                         assert_eq!(via_channel_id, Some(chan_2.2));
2060                         match &purpose {
2061                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2062                                         assert!(payment_preimage.is_none());
2063                                         assert_eq!(our_payment_secret_22, *payment_secret);
2064                                 },
2065                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2066                         }
2067                 },
2068                 _ => panic!("Unexpected event"),
2069         }
2070
2071         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2072         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2073         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2074
2075         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2076         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2077         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2078
2079         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2080         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2081         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2082         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2083         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2084
2085         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2086         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2087 }
2088
2089 #[test]
2090 fn channel_reserve_in_flight_removes() {
2091         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2092         // can send to its counterparty, but due to update ordering, the other side may not yet have
2093         // considered those HTLCs fully removed.
2094         // This tests that we don't count HTLCs which will not be included in the next remote
2095         // commitment transaction towards the reserve value (as it implies no commitment transaction
2096         // will be generated which violates the remote reserve value).
2097         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2098         // To test this we:
2099         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2100         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2101         //    you only consider the value of the first HTLC, it may not),
2102         //  * start routing a third HTLC from A to B,
2103         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2104         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2105         //  * deliver the first fulfill from B
2106         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2107         //    claim,
2108         //  * deliver A's response CS and RAA.
2109         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2110         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2111         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2112         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2113         let chanmon_cfgs = create_chanmon_cfgs(2);
2114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2116         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2117         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2118
2119         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2120         // Route the first two HTLCs.
2121         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2122         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2123         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2124
2125         // Start routing the third HTLC (this is just used to get everyone in the right state).
2126         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2127         let send_1 = {
2128                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2129                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2130                 check_added_monitors!(nodes[0], 1);
2131                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2132                 assert_eq!(events.len(), 1);
2133                 SendEvent::from_event(events.remove(0))
2134         };
2135
2136         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2137         // initial fulfill/CS.
2138         nodes[1].node.claim_funds(payment_preimage_1);
2139         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2140         check_added_monitors!(nodes[1], 1);
2141         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2142
2143         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2144         // remove the second HTLC when we send the HTLC back from B to A.
2145         nodes[1].node.claim_funds(payment_preimage_2);
2146         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2147         check_added_monitors!(nodes[1], 1);
2148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2149
2150         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2151         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2152         check_added_monitors!(nodes[0], 1);
2153         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2154         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2155
2156         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2157         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2158         check_added_monitors!(nodes[1], 1);
2159         // B is already AwaitingRAA, so cant generate a CS here
2160         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2161
2162         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2163         check_added_monitors!(nodes[1], 1);
2164         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2165
2166         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2167         check_added_monitors!(nodes[0], 1);
2168         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2169
2170         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2171         check_added_monitors!(nodes[1], 1);
2172         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2173
2174         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2175         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2176         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2177         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2178         // on-chain as necessary).
2179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2180         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2181         check_added_monitors!(nodes[0], 1);
2182         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2183         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2184
2185         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2186         check_added_monitors!(nodes[1], 1);
2187         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2188
2189         expect_pending_htlcs_forwardable!(nodes[1]);
2190         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2191
2192         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2193         // resolve the second HTLC from A's point of view.
2194         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2195         check_added_monitors!(nodes[0], 1);
2196         expect_payment_path_successful!(nodes[0]);
2197         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2198
2199         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2200         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2201         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2202         let send_2 = {
2203                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2204                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2205                 check_added_monitors!(nodes[1], 1);
2206                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2207                 assert_eq!(events.len(), 1);
2208                 SendEvent::from_event(events.remove(0))
2209         };
2210
2211         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2212         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2213         check_added_monitors!(nodes[0], 1);
2214         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2215
2216         // Now just resolve all the outstanding messages/HTLCs for completeness...
2217
2218         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2219         check_added_monitors!(nodes[1], 1);
2220         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2221
2222         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2223         check_added_monitors!(nodes[1], 1);
2224
2225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2226         check_added_monitors!(nodes[0], 1);
2227         expect_payment_path_successful!(nodes[0]);
2228         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2229
2230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2231         check_added_monitors!(nodes[1], 1);
2232         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2233
2234         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2235         check_added_monitors!(nodes[0], 1);
2236
2237         expect_pending_htlcs_forwardable!(nodes[0]);
2238         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2239
2240         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2241         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2242 }
2243
2244 #[test]
2245 fn channel_monitor_network_test() {
2246         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2247         // tests that ChannelMonitor is able to recover from various states.
2248         let chanmon_cfgs = create_chanmon_cfgs(5);
2249         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2250         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2251         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2252
2253         // Create some initial channels
2254         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2255         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2256         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2257         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2258
2259         // Make sure all nodes are at the same starting height
2260         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2261         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2262         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2263         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2264         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2265
2266         // Rebalance the network a bit by relaying one payment through all the channels...
2267         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2268         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2269         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2270         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2271
2272         // Simple case with no pending HTLCs:
2273         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2274         check_added_monitors!(nodes[1], 1);
2275         check_closed_broadcast!(nodes[1], true);
2276         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2277         {
2278                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2279                 assert_eq!(node_txn.len(), 1);
2280                 mine_transaction(&nodes[1], &node_txn[0]);
2281                 if nodes[1].connect_style.borrow().updates_best_block_first() {
2282                         let _ = nodes[1].tx_broadcaster.txn_broadcast();
2283                 }
2284
2285                 mine_transaction(&nodes[0], &node_txn[0]);
2286                 check_added_monitors!(nodes[0], 1);
2287                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2288         }
2289         check_closed_broadcast!(nodes[0], true);
2290         assert_eq!(nodes[0].node.list_channels().len(), 0);
2291         assert_eq!(nodes[1].node.list_channels().len(), 1);
2292         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2293
2294         // One pending HTLC is discarded by the force-close:
2295         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2296
2297         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2298         // broadcasted until we reach the timelock time).
2299         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2300         check_closed_broadcast!(nodes[1], true);
2301         check_added_monitors!(nodes[1], 1);
2302         {
2303                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2304                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2305                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2306                 mine_transaction(&nodes[2], &node_txn[0]);
2307                 check_added_monitors!(nodes[2], 1);
2308                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2309         }
2310         check_closed_broadcast!(nodes[2], true);
2311         assert_eq!(nodes[1].node.list_channels().len(), 0);
2312         assert_eq!(nodes[2].node.list_channels().len(), 1);
2313         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2314         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2315
2316         macro_rules! claim_funds {
2317                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2318                         {
2319                                 $node.node.claim_funds($preimage);
2320                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2321                                 check_added_monitors!($node, 1);
2322
2323                                 let events = $node.node.get_and_clear_pending_msg_events();
2324                                 assert_eq!(events.len(), 1);
2325                                 match events[0] {
2326                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2327                                                 assert!(update_add_htlcs.is_empty());
2328                                                 assert!(update_fail_htlcs.is_empty());
2329                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2330                                         },
2331                                         _ => panic!("Unexpected event"),
2332                                 };
2333                         }
2334                 }
2335         }
2336
2337         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2338         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2339         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2340         check_added_monitors!(nodes[2], 1);
2341         check_closed_broadcast!(nodes[2], true);
2342         let node2_commitment_txid;
2343         {
2344                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2345                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2346                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2347                 node2_commitment_txid = node_txn[0].txid();
2348
2349                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2350                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2351                 mine_transaction(&nodes[3], &node_txn[0]);
2352                 check_added_monitors!(nodes[3], 1);
2353                 check_preimage_claim(&nodes[3], &node_txn);
2354         }
2355         check_closed_broadcast!(nodes[3], true);
2356         assert_eq!(nodes[2].node.list_channels().len(), 0);
2357         assert_eq!(nodes[3].node.list_channels().len(), 1);
2358         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2359         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2360
2361         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2362         // confusing us in the following tests.
2363         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2364
2365         // One pending HTLC to time out:
2366         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2367         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2368         // buffer space).
2369
2370         let (close_chan_update_1, close_chan_update_2) = {
2371                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2372                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2373                 assert_eq!(events.len(), 2);
2374                 let close_chan_update_1 = match events[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 = UserConfig::default();
2440         alice_config.channel_handshake_config.announced_channel = true;
2441         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2442         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2443         let mut bob_config = UserConfig::default();
2444         bob_config.channel_handshake_config.announced_channel = true;
2445         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2446         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2447         let user_cfgs = [Some(alice_config), Some(bob_config)];
2448         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2449         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2450         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2453         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2454         // Create some new channels:
2455         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2456
2457         // A pending HTLC which will be revoked:
2458         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2459         // Get the will-be-revoked local txn from nodes[0]
2460         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2461         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2462         assert_eq!(revoked_local_txn[0].input.len(), 1);
2463         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2464         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2465         assert_eq!(revoked_local_txn[1].input.len(), 1);
2466         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2467         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2468         // Revoke the old state
2469         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2470
2471         {
2472                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2473                 {
2474                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2475                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2476                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2477                         check_spends!(node_txn[0], revoked_local_txn[0]);
2478                         node_txn.swap_remove(0);
2479                 }
2480                 check_added_monitors!(nodes[1], 1);
2481                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2482                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2483
2484                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2485                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2486                 // Verify broadcast of revoked HTLC-timeout
2487                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2488                 check_added_monitors!(nodes[0], 1);
2489                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2490                 // Broadcast revoked HTLC-timeout on node 1
2491                 mine_transaction(&nodes[1], &node_txn[1]);
2492                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2493         }
2494         get_announce_close_broadcast_events(&nodes, 0, 1);
2495         assert_eq!(nodes[0].node.list_channels().len(), 0);
2496         assert_eq!(nodes[1].node.list_channels().len(), 0);
2497 }
2498
2499 #[test]
2500 fn test_justice_tx_htlc_success() {
2501         // Test justice txn built on revoked HTLC-Success tx, against both sides
2502         let mut alice_config = UserConfig::default();
2503         alice_config.channel_handshake_config.announced_channel = true;
2504         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2505         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2506         let mut bob_config = UserConfig::default();
2507         bob_config.channel_handshake_config.announced_channel = true;
2508         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2509         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2510         let user_cfgs = [Some(alice_config), Some(bob_config)];
2511         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2512         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2513         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2516         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2517         // Create some new channels:
2518         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2519
2520         // A pending HTLC which will be revoked:
2521         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2522         // Get the will-be-revoked local txn from B
2523         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2524         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2525         assert_eq!(revoked_local_txn[0].input.len(), 1);
2526         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2527         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2528         // Revoke the old state
2529         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2530         {
2531                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532                 {
2533                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2534                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2535                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2536
2537                         check_spends!(node_txn[0], revoked_local_txn[0]);
2538                         node_txn.swap_remove(0);
2539                 }
2540                 check_added_monitors!(nodes[0], 1);
2541                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2542
2543                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2544                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2545                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2546                 check_added_monitors!(nodes[1], 1);
2547                 mine_transaction(&nodes[0], &node_txn[1]);
2548                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2549                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2550         }
2551         get_announce_close_broadcast_events(&nodes, 0, 1);
2552         assert_eq!(nodes[0].node.list_channels().len(), 0);
2553         assert_eq!(nodes[1].node.list_channels().len(), 0);
2554 }
2555
2556 #[test]
2557 fn revoked_output_claim() {
2558         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2559         // transaction is broadcast by its counterparty
2560         let chanmon_cfgs = create_chanmon_cfgs(2);
2561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2563         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2564         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2565         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2566         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2567         assert_eq!(revoked_local_txn.len(), 1);
2568         // Only output is the full channel value back to nodes[0]:
2569         assert_eq!(revoked_local_txn[0].output.len(), 1);
2570         // Send a payment through, updating everyone's latest commitment txn
2571         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2572
2573         // Inform nodes[1] that nodes[0] broadcast a stale tx
2574         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2575         check_added_monitors!(nodes[1], 1);
2576         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2577         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2578         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2579
2580         check_spends!(node_txn[0], revoked_local_txn[0]);
2581
2582         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2583         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2584         get_announce_close_broadcast_events(&nodes, 0, 1);
2585         check_added_monitors!(nodes[0], 1);
2586         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2587 }
2588
2589 #[test]
2590 fn test_forming_justice_tx_from_monitor_updates() {
2591         do_test_forming_justice_tx_from_monitor_updates(true);
2592         do_test_forming_justice_tx_from_monitor_updates(false);
2593 }
2594
2595 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2596         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2597         // is properly formed and can be broadcasted/confirmed successfully in the event
2598         // that a revoked commitment transaction is broadcasted
2599         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2600         let chanmon_cfgs = create_chanmon_cfgs(2);
2601         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2602         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2603         let persisters = vec![WatchtowerPersister::new(destination_script0),
2604                 WatchtowerPersister::new(destination_script1)];
2605         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2606         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2607         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2608         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2609         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2610
2611         if !broadcast_initial_commitment {
2612                 // Send a payment to move the channel forward
2613                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2614         }
2615
2616         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2617         // We'll keep this commitment transaction to broadcast once it's revoked.
2618         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2619         assert_eq!(revoked_local_txn.len(), 1);
2620         let revoked_commitment_tx = &revoked_local_txn[0];
2621
2622         // Send another payment, now revoking the previous commitment tx
2623         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2624
2625         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2626         check_spends!(justice_tx, revoked_commitment_tx);
2627
2628         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2629         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2630
2631         check_added_monitors!(nodes[1], 1);
2632         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2633                 &[nodes[0].node.get_our_node_id()], 100_000);
2634         get_announce_close_broadcast_events(&nodes, 1, 0);
2635
2636         check_added_monitors!(nodes[0], 1);
2637         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2638                 &[nodes[1].node.get_our_node_id()], 100_000);
2639
2640         // Check that the justice tx has sent the revoked output value to nodes[1]
2641         let monitor = get_monitor!(nodes[1], channel_id);
2642         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2643                 match balance {
2644                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2645                         _ => panic!("Unexpected balance type"),
2646                 }
2647         });
2648         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2649         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2650         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2651         assert_eq!(total_claimable_balance, expected_claimable_balance);
2652 }
2653
2654
2655 #[test]
2656 fn claim_htlc_outputs_shared_tx() {
2657         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2658         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2659         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2660         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2661         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2662         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2663
2664         // Create some new channel:
2665         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2666
2667         // Rebalance the network to generate htlc in the two directions
2668         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2669         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2670         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2671         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2672
2673         // Get the will-be-revoked local txn from node[0]
2674         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2675         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2676         assert_eq!(revoked_local_txn[0].input.len(), 1);
2677         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2678         assert_eq!(revoked_local_txn[1].input.len(), 1);
2679         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2680         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2681         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2682
2683         //Revoke the old state
2684         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2685
2686         {
2687                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2688                 check_added_monitors!(nodes[0], 1);
2689                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2690                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2691                 check_added_monitors!(nodes[1], 1);
2692                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2693                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2694                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2695
2696                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2697                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2698
2699                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2700                 check_spends!(node_txn[0], revoked_local_txn[0]);
2701
2702                 let mut witness_lens = BTreeSet::new();
2703                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2704                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2705                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2706                 assert_eq!(witness_lens.len(), 3);
2707                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2708                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2709                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2710
2711                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2712                 // ANTI_REORG_DELAY confirmations.
2713                 mine_transaction(&nodes[1], &node_txn[0]);
2714                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2715                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2716         }
2717         get_announce_close_broadcast_events(&nodes, 0, 1);
2718         assert_eq!(nodes[0].node.list_channels().len(), 0);
2719         assert_eq!(nodes[1].node.list_channels().len(), 0);
2720 }
2721
2722 #[test]
2723 fn claim_htlc_outputs_single_tx() {
2724         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2725         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2726         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2729         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2730
2731         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2732
2733         // Rebalance the network to generate htlc in the two directions
2734         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2735         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2736         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2737         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2738         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2739
2740         // Get the will-be-revoked local txn from node[0]
2741         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2742
2743         //Revoke the old state
2744         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2745
2746         {
2747                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2748                 check_added_monitors!(nodes[0], 1);
2749                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2750                 check_added_monitors!(nodes[1], 1);
2751                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2752                 let mut events = nodes[0].node.get_and_clear_pending_events();
2753                 expect_pending_htlcs_forwardable_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 (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3508                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3509                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3510                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3511
3512                 // Send a 0-msat update_add_htlc to fail the channel.
3513                 let update_add_htlc = msgs::UpdateAddHTLC {
3514                         channel_id: chan.2,
3515                         htlc_id: 0,
3516                         amount_msat: 0,
3517                         payment_hash,
3518                         cltv_expiry,
3519                         onion_routing_packet,
3520                         skimmed_fee_msat: None,
3521                         blinding_point: None,
3522                 };
3523                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3524         }
3525         let events = nodes[0].node.get_and_clear_pending_events();
3526         assert_eq!(events.len(), 3);
3527         // Check that Alice fails backward the pending HTLC from the second payment.
3528         match events[0] {
3529                 Event::PaymentPathFailed { payment_hash, .. } => {
3530                         assert_eq!(payment_hash, failed_payment_hash);
3531                 },
3532                 _ => panic!("Unexpected event"),
3533         }
3534         match events[1] {
3535                 Event::PaymentFailed { payment_hash, .. } => {
3536                         assert_eq!(payment_hash, failed_payment_hash);
3537                 },
3538                 _ => panic!("Unexpected event"),
3539         }
3540         match events[2] {
3541                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3542                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3543                 },
3544                 _ => panic!("Unexpected event {:?}", events[1]),
3545         }
3546         check_closed_broadcast!(nodes[0], true);
3547         check_added_monitors!(nodes[0], 1);
3548 }
3549
3550 #[test]
3551 fn test_htlc_ignore_latest_remote_commitment() {
3552         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3553         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3554         let chanmon_cfgs = create_chanmon_cfgs(2);
3555         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3556         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3557         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3558         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3559                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3560                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3561                 // connect_style.
3562                 return;
3563         }
3564         let funding_tx = create_announced_chan_between_nodes(&nodes, 0, 1).3;
3565
3566         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3567         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3568         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3569         check_closed_broadcast!(nodes[0], true);
3570         check_added_monitors!(nodes[0], 1);
3571         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3572
3573         let node_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
3574         assert_eq!(node_txn.len(), 2);
3575         check_spends!(node_txn[0], funding_tx);
3576         check_spends!(node_txn[1], node_txn[0]);
3577
3578         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone()]);
3579         connect_block(&nodes[1], &block);
3580         check_closed_broadcast!(nodes[1], true);
3581         check_added_monitors!(nodes[1], 1);
3582         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3583
3584         // Duplicate the connect_block call since this may happen due to other listeners
3585         // registering new transactions
3586         connect_block(&nodes[1], &block);
3587 }
3588
3589 #[test]
3590 fn test_force_close_fail_back() {
3591         // Check which HTLCs are failed-backwards on channel force-closure
3592         let chanmon_cfgs = create_chanmon_cfgs(3);
3593         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3594         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3595         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3596         create_announced_chan_between_nodes(&nodes, 0, 1);
3597         create_announced_chan_between_nodes(&nodes, 1, 2);
3598
3599         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3600
3601         let mut payment_event = {
3602                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3603                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3604                 check_added_monitors!(nodes[0], 1);
3605
3606                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3607                 assert_eq!(events.len(), 1);
3608                 SendEvent::from_event(events.remove(0))
3609         };
3610
3611         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3612         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3613
3614         expect_pending_htlcs_forwardable!(nodes[1]);
3615
3616         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3617         assert_eq!(events_2.len(), 1);
3618         payment_event = SendEvent::from_event(events_2.remove(0));
3619         assert_eq!(payment_event.msgs.len(), 1);
3620
3621         check_added_monitors!(nodes[1], 1);
3622         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3623         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3624         check_added_monitors!(nodes[2], 1);
3625         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3626
3627         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3628         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3629         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3630
3631         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3632         check_closed_broadcast!(nodes[2], true);
3633         check_added_monitors!(nodes[2], 1);
3634         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3635         let commitment_tx = {
3636                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3637                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3638                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3639                 // back to nodes[1] upon timeout otherwise.
3640                 assert_eq!(node_txn.len(), 1);
3641                 node_txn.remove(0)
3642         };
3643
3644         mine_transaction(&nodes[1], &commitment_tx);
3645
3646         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3647         check_closed_broadcast!(nodes[1], true);
3648         check_added_monitors!(nodes[1], 1);
3649         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3650
3651         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3652         {
3653                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3654                         .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);
3655         }
3656         mine_transaction(&nodes[2], &commitment_tx);
3657         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcast();
3658         assert_eq!(node_txn.len(), if nodes[2].connect_style.borrow().updates_best_block_first() { 2 } else { 1 });
3659         let htlc_tx = node_txn.pop().unwrap();
3660         assert_eq!(htlc_tx.input.len(), 1);
3661         assert_eq!(htlc_tx.input[0].previous_output.txid, commitment_tx.txid());
3662         assert_eq!(htlc_tx.lock_time, LockTime::ZERO); // Must be an HTLC-Success
3663         assert_eq!(htlc_tx.input[0].witness.len(), 5); // Must be an HTLC-Success
3664
3665         check_spends!(htlc_tx, commitment_tx);
3666 }
3667
3668 #[test]
3669 fn test_dup_events_on_peer_disconnect() {
3670         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3671         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3672         // as we used to generate the event immediately upon receipt of the payment preimage in the
3673         // update_fulfill_htlc message.
3674
3675         let chanmon_cfgs = create_chanmon_cfgs(2);
3676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3678         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3679         create_announced_chan_between_nodes(&nodes, 0, 1);
3680
3681         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3682
3683         nodes[1].node.claim_funds(payment_preimage);
3684         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3685         check_added_monitors!(nodes[1], 1);
3686         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3687         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3688         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3689
3690         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3691         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3692
3693         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3694         reconnect_args.pending_htlc_claims.0 = 1;
3695         reconnect_nodes(reconnect_args);
3696         expect_payment_path_successful!(nodes[0]);
3697 }
3698
3699 #[test]
3700 fn test_peer_disconnected_before_funding_broadcasted() {
3701         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3702         // before the funding transaction has been broadcasted, and doesn't reconnect back within time.
3703         let chanmon_cfgs = create_chanmon_cfgs(2);
3704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3706         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3707
3708         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3709         // broadcasted, even though it's created by `nodes[0]`.
3710         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();
3711         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3712         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3713         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3714         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3715
3716         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3717         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3718
3719         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3720
3721         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3722         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3723
3724         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3725         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3726         // broadcasted.
3727         {
3728                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3729         }
3730
3731         // The peers disconnect before the funding is broadcasted.
3732         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3733         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3734
3735         // The time for peers to reconnect expires.
3736         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
3737                 nodes[0].node.timer_tick_occurred();
3738         }
3739
3740         // Ensure that the channel is closed with `ClosureReason::HolderForceClosed`
3741         // when the peers are disconnected and do not reconnect before the funding
3742         // transaction is broadcasted.
3743         check_closed_event!(&nodes[0], 2, ClosureReason::HolderForceClosed, true
3744                 , [nodes[1].node.get_our_node_id()], 1000000);
3745         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3746                 , [nodes[0].node.get_our_node_id()], 1000000);
3747 }
3748
3749 #[test]
3750 fn test_simple_peer_disconnect() {
3751         // Test that we can reconnect when there are no lost messages
3752         let chanmon_cfgs = create_chanmon_cfgs(3);
3753         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3754         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3755         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3756         create_announced_chan_between_nodes(&nodes, 0, 1);
3757         create_announced_chan_between_nodes(&nodes, 1, 2);
3758
3759         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3760         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3761         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3762         reconnect_args.send_channel_ready = (true, true);
3763         reconnect_nodes(reconnect_args);
3764
3765         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3766         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3767         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3768         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3769
3770         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3771         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3772         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3773
3774         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3775         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3776         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3777         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3778
3779         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3780         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3781
3782         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3783         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3784
3785         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3786         reconnect_args.pending_cell_htlc_fails.0 = 1;
3787         reconnect_args.pending_cell_htlc_claims.0 = 1;
3788         reconnect_nodes(reconnect_args);
3789         {
3790                 let events = nodes[0].node.get_and_clear_pending_events();
3791                 assert_eq!(events.len(), 4);
3792                 match events[0] {
3793                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3794                                 assert_eq!(payment_preimage, payment_preimage_3);
3795                                 assert_eq!(payment_hash, payment_hash_3);
3796                         },
3797                         _ => panic!("Unexpected event"),
3798                 }
3799                 match events[1] {
3800                         Event::PaymentPathSuccessful { .. } => {},
3801                         _ => panic!("Unexpected event"),
3802                 }
3803                 match events[2] {
3804                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3805                                 assert_eq!(payment_hash, payment_hash_5);
3806                                 assert!(payment_failed_permanently);
3807                         },
3808                         _ => panic!("Unexpected event"),
3809                 }
3810                 match events[3] {
3811                         Event::PaymentFailed { payment_hash, .. } => {
3812                                 assert_eq!(payment_hash, payment_hash_5);
3813                         },
3814                         _ => panic!("Unexpected event"),
3815                 }
3816         }
3817         check_added_monitors(&nodes[0], 1);
3818
3819         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3820         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3821 }
3822
3823 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3824         // Test that we can reconnect when in-flight HTLC updates get dropped
3825         let chanmon_cfgs = create_chanmon_cfgs(2);
3826         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3827         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3828         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3829
3830         let mut as_channel_ready = None;
3831         let channel_id = if messages_delivered == 0 {
3832                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3833                 as_channel_ready = Some(channel_ready);
3834                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3835                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3836                 // it before the channel_reestablish message.
3837                 chan_id
3838         } else {
3839                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3840         };
3841
3842         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3843
3844         let payment_event = {
3845                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3846                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3847                 check_added_monitors!(nodes[0], 1);
3848
3849                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3850                 assert_eq!(events.len(), 1);
3851                 SendEvent::from_event(events.remove(0))
3852         };
3853         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3854
3855         if messages_delivered < 2 {
3856                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3857         } else {
3858                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3859                 if messages_delivered >= 3 {
3860                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3861                         check_added_monitors!(nodes[1], 1);
3862                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3863
3864                         if messages_delivered >= 4 {
3865                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3866                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3867                                 check_added_monitors!(nodes[0], 1);
3868
3869                                 if messages_delivered >= 5 {
3870                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3871                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3872                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3873                                         check_added_monitors!(nodes[0], 1);
3874
3875                                         if messages_delivered >= 6 {
3876                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3877                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3878                                                 check_added_monitors!(nodes[1], 1);
3879                                         }
3880                                 }
3881                         }
3882                 }
3883         }
3884
3885         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3886         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3887         if messages_delivered < 3 {
3888                 if simulate_broken_lnd {
3889                         // lnd has a long-standing bug where they send a channel_ready prior to a
3890                         // channel_reestablish if you reconnect prior to channel_ready time.
3891                         //
3892                         // Here we simulate that behavior, delivering a channel_ready immediately on
3893                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3894                         // in `reconnect_nodes` but we currently don't fail based on that.
3895                         //
3896                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3897                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3898                 }
3899                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3900                 // received on either side, both sides will need to resend them.
3901                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3902                 reconnect_args.send_channel_ready = (true, true);
3903                 reconnect_args.pending_htlc_adds.1 = 1;
3904                 reconnect_nodes(reconnect_args);
3905         } else if messages_delivered == 3 {
3906                 // nodes[0] still wants its RAA + commitment_signed
3907                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3908                 reconnect_args.pending_responding_commitment_signed.0 = true;
3909                 reconnect_args.pending_raa.0 = true;
3910                 reconnect_nodes(reconnect_args);
3911         } else if messages_delivered == 4 {
3912                 // nodes[0] still wants its commitment_signed
3913                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3914                 reconnect_args.pending_responding_commitment_signed.0 = true;
3915                 reconnect_nodes(reconnect_args);
3916         } else if messages_delivered == 5 {
3917                 // nodes[1] still wants its final RAA
3918                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3919                 reconnect_args.pending_raa.1 = true;
3920                 reconnect_nodes(reconnect_args);
3921         } else if messages_delivered == 6 {
3922                 // Everything was delivered...
3923                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3924         }
3925
3926         let events_1 = nodes[1].node.get_and_clear_pending_events();
3927         if messages_delivered == 0 {
3928                 assert_eq!(events_1.len(), 2);
3929                 match events_1[0] {
3930                         Event::ChannelReady { .. } => { },
3931                         _ => panic!("Unexpected event"),
3932                 };
3933                 match events_1[1] {
3934                         Event::PendingHTLCsForwardable { .. } => { },
3935                         _ => panic!("Unexpected event"),
3936                 };
3937         } else {
3938                 assert_eq!(events_1.len(), 1);
3939                 match events_1[0] {
3940                         Event::PendingHTLCsForwardable { .. } => { },
3941                         _ => panic!("Unexpected event"),
3942                 };
3943         }
3944
3945         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3946         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3947         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3948
3949         nodes[1].node.process_pending_htlc_forwards();
3950
3951         let events_2 = nodes[1].node.get_and_clear_pending_events();
3952         assert_eq!(events_2.len(), 1);
3953         match events_2[0] {
3954                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3955                         assert_eq!(payment_hash_1, *payment_hash);
3956                         assert_eq!(amount_msat, 1_000_000);
3957                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3958                         assert_eq!(via_channel_id, Some(channel_id));
3959                         match &purpose {
3960                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3961                                         assert!(payment_preimage.is_none());
3962                                         assert_eq!(payment_secret_1, *payment_secret);
3963                                 },
3964                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3965                         }
3966                 },
3967                 _ => panic!("Unexpected event"),
3968         }
3969
3970         nodes[1].node.claim_funds(payment_preimage_1);
3971         check_added_monitors!(nodes[1], 1);
3972         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3973
3974         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3975         assert_eq!(events_3.len(), 1);
3976         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3977                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3978                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3979                         assert!(updates.update_add_htlcs.is_empty());
3980                         assert!(updates.update_fail_htlcs.is_empty());
3981                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3982                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3983                         assert!(updates.update_fee.is_none());
3984                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3985                 },
3986                 _ => panic!("Unexpected event"),
3987         };
3988
3989         if messages_delivered >= 1 {
3990                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3991
3992                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3993                 assert_eq!(events_4.len(), 1);
3994                 match events_4[0] {
3995                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3996                                 assert_eq!(payment_preimage_1, *payment_preimage);
3997                                 assert_eq!(payment_hash_1, *payment_hash);
3998                         },
3999                         _ => panic!("Unexpected event"),
4000                 }
4001
4002                 if messages_delivered >= 2 {
4003                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
4004                         check_added_monitors!(nodes[0], 1);
4005                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4006
4007                         if messages_delivered >= 3 {
4008                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4009                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4010                                 check_added_monitors!(nodes[1], 1);
4011
4012                                 if messages_delivered >= 4 {
4013                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4014                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4015                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4016                                         check_added_monitors!(nodes[1], 1);
4017
4018                                         if messages_delivered >= 5 {
4019                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4020                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4021                                                 check_added_monitors!(nodes[0], 1);
4022                                         }
4023                                 }
4024                         }
4025                 }
4026         }
4027
4028         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4029         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4030         if messages_delivered < 2 {
4031                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4032                 reconnect_args.pending_htlc_claims.0 = 1;
4033                 reconnect_nodes(reconnect_args);
4034                 if messages_delivered < 1 {
4035                         expect_payment_sent!(nodes[0], payment_preimage_1);
4036                 } else {
4037                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4038                 }
4039         } else if messages_delivered == 2 {
4040                 // nodes[0] still wants its RAA + commitment_signed
4041                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4042                 reconnect_args.pending_responding_commitment_signed.1 = true;
4043                 reconnect_args.pending_raa.1 = true;
4044                 reconnect_nodes(reconnect_args);
4045         } else if messages_delivered == 3 {
4046                 // nodes[0] still wants its commitment_signed
4047                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4048                 reconnect_args.pending_responding_commitment_signed.1 = true;
4049                 reconnect_nodes(reconnect_args);
4050         } else if messages_delivered == 4 {
4051                 // nodes[1] still wants its final RAA
4052                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4053                 reconnect_args.pending_raa.0 = true;
4054                 reconnect_nodes(reconnect_args);
4055         } else if messages_delivered == 5 {
4056                 // Everything was delivered...
4057                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4058         }
4059
4060         if messages_delivered == 1 || messages_delivered == 2 {
4061                 expect_payment_path_successful!(nodes[0]);
4062         }
4063         if messages_delivered <= 5 {
4064                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4065                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4066         }
4067         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4068
4069         if messages_delivered > 2 {
4070                 expect_payment_path_successful!(nodes[0]);
4071         }
4072
4073         // Channel should still work fine...
4074         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4075         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4076         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4077 }
4078
4079 #[test]
4080 fn test_drop_messages_peer_disconnect_a() {
4081         do_test_drop_messages_peer_disconnect(0, true);
4082         do_test_drop_messages_peer_disconnect(0, false);
4083         do_test_drop_messages_peer_disconnect(1, false);
4084         do_test_drop_messages_peer_disconnect(2, false);
4085 }
4086
4087 #[test]
4088 fn test_drop_messages_peer_disconnect_b() {
4089         do_test_drop_messages_peer_disconnect(3, false);
4090         do_test_drop_messages_peer_disconnect(4, false);
4091         do_test_drop_messages_peer_disconnect(5, false);
4092         do_test_drop_messages_peer_disconnect(6, false);
4093 }
4094
4095 #[test]
4096 fn test_channel_ready_without_best_block_updated() {
4097         // Previously, if we were offline when a funding transaction was locked in, and then we came
4098         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4099         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4100         // channel_ready immediately instead.
4101         let chanmon_cfgs = create_chanmon_cfgs(2);
4102         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4103         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4104         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4105         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4106
4107         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4108
4109         let conf_height = nodes[0].best_block_info().1 + 1;
4110         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4111         let block_txn = [funding_tx];
4112         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4113         let conf_block_header = nodes[0].get_block_header(conf_height);
4114         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4115
4116         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4117         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4118         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4119 }
4120
4121 #[test]
4122 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4123         let chanmon_cfgs = create_chanmon_cfgs(2);
4124         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4125         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4126         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4127
4128         // Let channel_manager get ahead of chain_monitor by 1 block.
4129         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4130         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4131         let height_1 = nodes[0].best_block_info().1 + 1;
4132         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4133
4134         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4135         nodes[0].node.block_connected(&block_1, height_1);
4136
4137         // Create channel, and it gets added to chain_monitor in funding_created.
4138         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4139
4140         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4141         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4142         // was running ahead of chain_monitor at the time of funding_created.
4143         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4144         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4145         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4146         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4147
4148         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4149         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4150         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4151 }
4152
4153 #[test]
4154 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4155         let chanmon_cfgs = create_chanmon_cfgs(2);
4156         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4157         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4158         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4159
4160         // Let chain_monitor get ahead of channel_manager by 1 block.
4161         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4162         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4163         let height_1 = nodes[0].best_block_info().1 + 1;
4164         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4165
4166         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4167         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4168
4169         // Create channel, and it gets added to chain_monitor in funding_created.
4170         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4171
4172         // channel_manager can't really skip block_1, it should get it eventually.
4173         nodes[0].node.block_connected(&block_1, height_1);
4174
4175         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4176         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4177         // running behind at the time of funding_created.
4178         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4179         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4180         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4181         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4182
4183         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4184         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4185         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4186 }
4187
4188 #[test]
4189 fn test_drop_messages_peer_disconnect_dual_htlc() {
4190         // Test that we can handle reconnecting when both sides of a channel have pending
4191         // commitment_updates when we disconnect.
4192         let chanmon_cfgs = create_chanmon_cfgs(2);
4193         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4194         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4195         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4196         create_announced_chan_between_nodes(&nodes, 0, 1);
4197
4198         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4199
4200         // Now try to send a second payment which will fail to send
4201         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4202         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4203                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4204         check_added_monitors!(nodes[0], 1);
4205
4206         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4207         assert_eq!(events_1.len(), 1);
4208         match events_1[0] {
4209                 MessageSendEvent::UpdateHTLCs { .. } => {},
4210                 _ => panic!("Unexpected event"),
4211         }
4212
4213         nodes[1].node.claim_funds(payment_preimage_1);
4214         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4215         check_added_monitors!(nodes[1], 1);
4216
4217         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4218         assert_eq!(events_2.len(), 1);
4219         match events_2[0] {
4220                 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 } } => {
4221                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4222                         assert!(update_add_htlcs.is_empty());
4223                         assert_eq!(update_fulfill_htlcs.len(), 1);
4224                         assert!(update_fail_htlcs.is_empty());
4225                         assert!(update_fail_malformed_htlcs.is_empty());
4226                         assert!(update_fee.is_none());
4227
4228                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4229                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4230                         assert_eq!(events_3.len(), 1);
4231                         match events_3[0] {
4232                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4233                                         assert_eq!(*payment_preimage, payment_preimage_1);
4234                                         assert_eq!(*payment_hash, payment_hash_1);
4235                                 },
4236                                 _ => panic!("Unexpected event"),
4237                         }
4238
4239                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4240                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4241                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4242                         check_added_monitors!(nodes[0], 1);
4243                 },
4244                 _ => panic!("Unexpected event"),
4245         }
4246
4247         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4248         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4249
4250         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4251                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4252         }, true).unwrap();
4253         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4254         assert_eq!(reestablish_1.len(), 1);
4255         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4256                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4257         }, false).unwrap();
4258         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4259         assert_eq!(reestablish_2.len(), 1);
4260
4261         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4262         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4263         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4264         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4265
4266         assert!(as_resp.0.is_none());
4267         assert!(bs_resp.0.is_none());
4268
4269         assert!(bs_resp.1.is_none());
4270         assert!(bs_resp.2.is_none());
4271
4272         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4273
4274         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4275         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4276         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4277         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4278         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4279         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4280         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4281         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4282         // No commitment_signed so get_event_msg's assert(len == 1) passes
4283         check_added_monitors!(nodes[1], 1);
4284
4285         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4286         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4287         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4288         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4289         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4290         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4291         assert!(bs_second_commitment_signed.update_fee.is_none());
4292         check_added_monitors!(nodes[1], 1);
4293
4294         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4295         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4296         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4297         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4298         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4299         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4300         assert!(as_commitment_signed.update_fee.is_none());
4301         check_added_monitors!(nodes[0], 1);
4302
4303         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4304         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4305         // No commitment_signed so get_event_msg's assert(len == 1) passes
4306         check_added_monitors!(nodes[0], 1);
4307
4308         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4309         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4310         // No commitment_signed so get_event_msg's assert(len == 1) passes
4311         check_added_monitors!(nodes[1], 1);
4312
4313         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4314         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4315         check_added_monitors!(nodes[1], 1);
4316
4317         expect_pending_htlcs_forwardable!(nodes[1]);
4318
4319         let events_5 = nodes[1].node.get_and_clear_pending_events();
4320         assert_eq!(events_5.len(), 1);
4321         match events_5[0] {
4322                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4323                         assert_eq!(payment_hash_2, *payment_hash);
4324                         match &purpose {
4325                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4326                                         assert!(payment_preimage.is_none());
4327                                         assert_eq!(payment_secret_2, *payment_secret);
4328                                 },
4329                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4330                         }
4331                 },
4332                 _ => panic!("Unexpected event"),
4333         }
4334
4335         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4336         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4337         check_added_monitors!(nodes[0], 1);
4338
4339         expect_payment_path_successful!(nodes[0]);
4340         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4341 }
4342
4343 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4344         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4345         // to avoid our counterparty failing the channel.
4346         let chanmon_cfgs = create_chanmon_cfgs(2);
4347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4349         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4350
4351         create_announced_chan_between_nodes(&nodes, 0, 1);
4352
4353         let our_payment_hash = if send_partial_mpp {
4354                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4355                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4356                 // indicates there are more HTLCs coming.
4357                 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.
4358                 let payment_id = PaymentId([42; 32]);
4359                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4360                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4361                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4362                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4363                         &None, session_privs[0]).unwrap();
4364                 check_added_monitors!(nodes[0], 1);
4365                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4366                 assert_eq!(events.len(), 1);
4367                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4368                 // hop should *not* yet generate any PaymentClaimable event(s).
4369                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4370                 our_payment_hash
4371         } else {
4372                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4373         };
4374
4375         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4376         connect_block(&nodes[0], &block);
4377         connect_block(&nodes[1], &block);
4378         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4379         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4380                 block.header.prev_blockhash = block.block_hash();
4381                 connect_block(&nodes[0], &block);
4382                 connect_block(&nodes[1], &block);
4383         }
4384
4385         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4386
4387         check_added_monitors!(nodes[1], 1);
4388         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4389         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4390         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4391         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4392         assert!(htlc_timeout_updates.update_fee.is_none());
4393
4394         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4395         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4396         // 100_000 msat as u64, followed by the height at which we failed back above
4397         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4398         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4399         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4400 }
4401
4402 #[test]
4403 fn test_htlc_timeout() {
4404         do_test_htlc_timeout(true);
4405         do_test_htlc_timeout(false);
4406 }
4407
4408 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4409         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4410         let chanmon_cfgs = create_chanmon_cfgs(3);
4411         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4412         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4413         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4414         create_announced_chan_between_nodes(&nodes, 0, 1);
4415         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4416
4417         // Make sure all nodes are at the same starting height
4418         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4419         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4420         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4421
4422         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4423         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4424         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4425                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4426         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4427         check_added_monitors!(nodes[1], 1);
4428
4429         // Now attempt to route a second payment, which should be placed in the holding cell
4430         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4431         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4432         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4433                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4434         if forwarded_htlc {
4435                 check_added_monitors!(nodes[0], 1);
4436                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4437                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4438                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4439                 expect_pending_htlcs_forwardable!(nodes[1]);
4440         }
4441         check_added_monitors!(nodes[1], 0);
4442
4443         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4444         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4445         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4446         connect_blocks(&nodes[1], 1);
4447
4448         if forwarded_htlc {
4449                 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 }]);
4450                 check_added_monitors!(nodes[1], 1);
4451                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4452                 assert_eq!(fail_commit.len(), 1);
4453                 match fail_commit[0] {
4454                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4455                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4456                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4457                         },
4458                         _ => unreachable!(),
4459                 }
4460                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4461         } else {
4462                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4463         }
4464 }
4465
4466 #[test]
4467 fn test_holding_cell_htlc_add_timeouts() {
4468         do_test_holding_cell_htlc_add_timeouts(false);
4469         do_test_holding_cell_htlc_add_timeouts(true);
4470 }
4471
4472 macro_rules! check_spendable_outputs {
4473         ($node: expr, $keysinterface: expr) => {
4474                 {
4475                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4476                         let mut txn = Vec::new();
4477                         let mut all_outputs = Vec::new();
4478                         let secp_ctx = Secp256k1::new();
4479                         for event in events.drain(..) {
4480                                 match event {
4481                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4482                                                 for outp in outputs.drain(..) {
4483                                                         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());
4484                                                         all_outputs.push(outp);
4485                                                 }
4486                                         },
4487                                         _ => panic!("Unexpected event"),
4488                                 };
4489                         }
4490                         if all_outputs.len() > 1 {
4491                                 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) {
4492                                         txn.push(tx);
4493                                 }
4494                         }
4495                         txn
4496                 }
4497         }
4498 }
4499
4500 #[test]
4501 fn test_claim_sizeable_push_msat() {
4502         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4503         let chanmon_cfgs = create_chanmon_cfgs(2);
4504         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4505         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4506         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4507
4508         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4509         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4510         check_closed_broadcast!(nodes[1], true);
4511         check_added_monitors!(nodes[1], 1);
4512         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4513         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4514         assert_eq!(node_txn.len(), 1);
4515         check_spends!(node_txn[0], chan.3);
4516         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
4517
4518         mine_transaction(&nodes[1], &node_txn[0]);
4519         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4520
4521         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4522         assert_eq!(spend_txn.len(), 1);
4523         assert_eq!(spend_txn[0].input.len(), 1);
4524         check_spends!(spend_txn[0], node_txn[0]);
4525         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4526 }
4527
4528 #[test]
4529 fn test_claim_on_remote_sizeable_push_msat() {
4530         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4531         // to_remote output is encumbered by a P2WPKH
4532         let chanmon_cfgs = create_chanmon_cfgs(2);
4533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4535         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4536
4537         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4538         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4539         check_closed_broadcast!(nodes[0], true);
4540         check_added_monitors!(nodes[0], 1);
4541         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4542
4543         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4544         assert_eq!(node_txn.len(), 1);
4545         check_spends!(node_txn[0], chan.3);
4546         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
4547
4548         mine_transaction(&nodes[1], &node_txn[0]);
4549         check_closed_broadcast!(nodes[1], true);
4550         check_added_monitors!(nodes[1], 1);
4551         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4552         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4553
4554         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4555         assert_eq!(spend_txn.len(), 1);
4556         check_spends!(spend_txn[0], node_txn[0]);
4557 }
4558
4559 #[test]
4560 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4561         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4562         // to_remote output is encumbered by a P2WPKH
4563
4564         let chanmon_cfgs = create_chanmon_cfgs(2);
4565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4568
4569         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4570         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4571         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4572         assert_eq!(revoked_local_txn[0].input.len(), 1);
4573         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4574
4575         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4576         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4577         check_closed_broadcast!(nodes[1], true);
4578         check_added_monitors!(nodes[1], 1);
4579         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4580
4581         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4582         mine_transaction(&nodes[1], &node_txn[0]);
4583         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4584
4585         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4586         assert_eq!(spend_txn.len(), 3);
4587         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4588         check_spends!(spend_txn[1], node_txn[0]);
4589         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4590 }
4591
4592 #[test]
4593 fn test_static_spendable_outputs_preimage_tx() {
4594         let chanmon_cfgs = create_chanmon_cfgs(2);
4595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4597         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4598
4599         // Create some initial channels
4600         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4601
4602         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4603
4604         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4605         assert_eq!(commitment_tx[0].input.len(), 1);
4606         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4607
4608         // Settle A's commitment tx on B's chain
4609         nodes[1].node.claim_funds(payment_preimage);
4610         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4611         check_added_monitors!(nodes[1], 1);
4612         mine_transaction(&nodes[1], &commitment_tx[0]);
4613         check_added_monitors!(nodes[1], 1);
4614         let events = nodes[1].node.get_and_clear_pending_msg_events();
4615         match events[0] {
4616                 MessageSendEvent::UpdateHTLCs { .. } => {},
4617                 _ => panic!("Unexpected event"),
4618         }
4619         match events[2] {
4620                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4621                 _ => panic!("Unexepected event"),
4622         }
4623
4624         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4625         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4626         assert_eq!(node_txn.len(), 1);
4627         check_spends!(node_txn[0], commitment_tx[0]);
4628         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4629
4630         mine_transaction(&nodes[1], &node_txn[0]);
4631         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4632         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4633
4634         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4635         assert_eq!(spend_txn.len(), 1);
4636         check_spends!(spend_txn[0], node_txn[0]);
4637 }
4638
4639 #[test]
4640 fn test_static_spendable_outputs_timeout_tx() {
4641         let chanmon_cfgs = create_chanmon_cfgs(2);
4642         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4643         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4644         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4645
4646         // Create some initial channels
4647         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4648
4649         // Rebalance the network a bit by relaying one payment through all the channels ...
4650         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4651
4652         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4653
4654         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4655         assert_eq!(commitment_tx[0].input.len(), 1);
4656         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4657
4658         // Settle A's commitment tx on B' chain
4659         mine_transaction(&nodes[1], &commitment_tx[0]);
4660         check_added_monitors!(nodes[1], 1);
4661         let events = nodes[1].node.get_and_clear_pending_msg_events();
4662         match events[1] {
4663                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4664                 _ => panic!("Unexpected event"),
4665         }
4666         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4667
4668         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4669         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4670         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4671         check_spends!(node_txn[0],  commitment_tx[0].clone());
4672         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4673
4674         mine_transaction(&nodes[1], &node_txn[0]);
4675         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4676         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4677         expect_payment_failed!(nodes[1], our_payment_hash, false);
4678
4679         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4680         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4681         check_spends!(spend_txn[0], commitment_tx[0]);
4682         check_spends!(spend_txn[1], node_txn[0]);
4683         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4684 }
4685
4686 #[test]
4687 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4688         let chanmon_cfgs = create_chanmon_cfgs(2);
4689         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4690         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4691         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4692
4693         // Create some initial channels
4694         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4695
4696         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4697         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4698         assert_eq!(revoked_local_txn[0].input.len(), 1);
4699         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4700
4701         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4702
4703         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4704         check_closed_broadcast!(nodes[1], true);
4705         check_added_monitors!(nodes[1], 1);
4706         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4707
4708         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4709         assert_eq!(node_txn.len(), 1);
4710         assert_eq!(node_txn[0].input.len(), 2);
4711         check_spends!(node_txn[0], revoked_local_txn[0]);
4712
4713         mine_transaction(&nodes[1], &node_txn[0]);
4714         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4715
4716         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4717         assert_eq!(spend_txn.len(), 1);
4718         check_spends!(spend_txn[0], node_txn[0]);
4719 }
4720
4721 #[test]
4722 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4723         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4724         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4725         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4726         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4727         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4728
4729         // Create some initial channels
4730         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4731
4732         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4733         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4734         assert_eq!(revoked_local_txn[0].input.len(), 1);
4735         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4736
4737         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4738
4739         // A will generate HTLC-Timeout from revoked commitment tx
4740         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4741         check_closed_broadcast!(nodes[0], true);
4742         check_added_monitors!(nodes[0], 1);
4743         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4744         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4745
4746         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4747         assert_eq!(revoked_htlc_txn.len(), 1);
4748         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4749         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4750         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4751         assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4752
4753         // B will generate justice tx from A's revoked commitment/HTLC tx
4754         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4755         check_closed_broadcast!(nodes[1], true);
4756         check_added_monitors!(nodes[1], 1);
4757         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4758
4759         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4760         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4761         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4762         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4763         // transactions next...
4764         assert_eq!(node_txn[0].input.len(), 3);
4765         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4766
4767         assert_eq!(node_txn[1].input.len(), 2);
4768         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4769         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4770                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4771         } else {
4772                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4773                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4774         }
4775
4776         mine_transaction(&nodes[1], &node_txn[1]);
4777         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4778
4779         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4780         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4781         assert_eq!(spend_txn.len(), 1);
4782         assert_eq!(spend_txn[0].input.len(), 1);
4783         check_spends!(spend_txn[0], node_txn[1]);
4784 }
4785
4786 #[test]
4787 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4788         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4789         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4790         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4791         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4792         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4793
4794         // Create some initial channels
4795         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4796
4797         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4798         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4799         assert_eq!(revoked_local_txn[0].input.len(), 1);
4800         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4801
4802         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4803         assert_eq!(revoked_local_txn[0].output.len(), 2);
4804
4805         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4806
4807         // B will generate HTLC-Success from revoked commitment tx
4808         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4809         check_closed_broadcast!(nodes[1], true);
4810         check_added_monitors!(nodes[1], 1);
4811         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4812         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4813
4814         assert_eq!(revoked_htlc_txn.len(), 1);
4815         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4816         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4817         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4818
4819         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4820         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4821         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4822
4823         // A will generate justice tx from B's revoked commitment/HTLC tx
4824         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4825         check_closed_broadcast!(nodes[0], true);
4826         check_added_monitors!(nodes[0], 1);
4827         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4828
4829         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4830         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4831
4832         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4833         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4834         // transactions next...
4835         assert_eq!(node_txn[0].input.len(), 2);
4836         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4837         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4838                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4839         } else {
4840                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4841                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4842         }
4843
4844         assert_eq!(node_txn[1].input.len(), 1);
4845         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4846
4847         mine_transaction(&nodes[0], &node_txn[1]);
4848         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4849
4850         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4851         // didn't try to generate any new transactions.
4852
4853         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4854         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4855         assert_eq!(spend_txn.len(), 3);
4856         assert_eq!(spend_txn[0].input.len(), 1);
4857         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4858         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4859         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4860         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4861 }
4862
4863 #[test]
4864 fn test_onchain_to_onchain_claim() {
4865         // Test that in case of channel closure, we detect the state of output and claim HTLC
4866         // on downstream peer's remote commitment tx.
4867         // First, have C claim an HTLC against its own latest commitment transaction.
4868         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4869         // channel.
4870         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4871         // gets broadcast.
4872
4873         let chanmon_cfgs = create_chanmon_cfgs(3);
4874         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4875         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4876         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4877
4878         // Create some initial channels
4879         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4880         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4881
4882         // Ensure all nodes are at the same height
4883         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4884         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4885         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4886         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4887
4888         // Rebalance the network a bit by relaying one payment through all the channels ...
4889         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4890         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4891
4892         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4893         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4894         check_spends!(commitment_tx[0], chan_2.3);
4895         nodes[2].node.claim_funds(payment_preimage);
4896         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4897         check_added_monitors!(nodes[2], 1);
4898         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4899         assert!(updates.update_add_htlcs.is_empty());
4900         assert!(updates.update_fail_htlcs.is_empty());
4901         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4902         assert!(updates.update_fail_malformed_htlcs.is_empty());
4903
4904         mine_transaction(&nodes[2], &commitment_tx[0]);
4905         check_closed_broadcast!(nodes[2], true);
4906         check_added_monitors!(nodes[2], 1);
4907         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4908
4909         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4910         assert_eq!(c_txn.len(), 1);
4911         check_spends!(c_txn[0], commitment_tx[0]);
4912         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4913         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4914         assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4915
4916         // 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
4917         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4918         check_added_monitors!(nodes[1], 1);
4919         let events = nodes[1].node.get_and_clear_pending_events();
4920         assert_eq!(events.len(), 2);
4921         match events[0] {
4922                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4923                 _ => panic!("Unexpected event"),
4924         }
4925         match events[1] {
4926                 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
4927                         next_channel_id, outbound_amount_forwarded_msat, ..
4928                 } => {
4929                         assert_eq!(total_fee_earned_msat, Some(1000));
4930                         assert_eq!(prev_channel_id, Some(chan_1.2));
4931                         assert_eq!(claim_from_onchain_tx, true);
4932                         assert_eq!(next_channel_id, Some(chan_2.2));
4933                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4934                 },
4935                 _ => panic!("Unexpected event"),
4936         }
4937         check_added_monitors!(nodes[1], 1);
4938         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4939         assert_eq!(msg_events.len(), 3);
4940         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4941         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4942
4943         match nodes_2_event {
4944                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4945                 _ => panic!("Unexpected event"),
4946         }
4947
4948         match nodes_0_event {
4949                 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, .. } } => {
4950                         assert!(update_add_htlcs.is_empty());
4951                         assert!(update_fail_htlcs.is_empty());
4952                         assert_eq!(update_fulfill_htlcs.len(), 1);
4953                         assert!(update_fail_malformed_htlcs.is_empty());
4954                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4955                 },
4956                 _ => panic!("Unexpected event"),
4957         };
4958
4959         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4960         match msg_events[0] {
4961                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4962                 _ => panic!("Unexpected event"),
4963         }
4964
4965         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4966         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4967         mine_transaction(&nodes[1], &commitment_tx[0]);
4968         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4969         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4970         // ChannelMonitor: HTLC-Success tx
4971         assert_eq!(b_txn.len(), 1);
4972         check_spends!(b_txn[0], commitment_tx[0]);
4973         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4974         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4975         assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
4976
4977         check_closed_broadcast!(nodes[1], true);
4978         check_added_monitors!(nodes[1], 1);
4979 }
4980
4981 #[test]
4982 fn test_duplicate_payment_hash_one_failure_one_success() {
4983         // Topology : A --> B --> C --> D
4984         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4985         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4986         // we forward one of the payments onwards to D.
4987         let chanmon_cfgs = create_chanmon_cfgs(4);
4988         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4989         // When this test was written, the default base fee floated based on the HTLC count.
4990         // It is now fixed, so we simply set the fee to the expected value here.
4991         let mut config = test_default_channel_config();
4992         config.channel_config.forwarding_fee_base_msat = 196;
4993         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4994                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4995         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4996
4997         create_announced_chan_between_nodes(&nodes, 0, 1);
4998         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4999         create_announced_chan_between_nodes(&nodes, 2, 3);
5000
5001         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5002         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5003         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5004         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5005         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5006
5007         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5008
5009         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
5010         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5011         // script push size limit so that the below script length checks match
5012         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5013         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
5014                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
5015         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5016         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5017
5018         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5019         assert_eq!(commitment_txn[0].input.len(), 1);
5020         check_spends!(commitment_txn[0], chan_2.3);
5021
5022         mine_transaction(&nodes[1], &commitment_txn[0]);
5023         check_closed_broadcast!(nodes[1], true);
5024         check_added_monitors!(nodes[1], 1);
5025         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5026         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5027
5028         let htlc_timeout_tx;
5029         { // Extract one of the two HTLC-Timeout transaction
5030                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5031                 // ChannelMonitor: timeout tx * 2-or-3
5032                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5033
5034                 check_spends!(node_txn[0], commitment_txn[0]);
5035                 assert_eq!(node_txn[0].input.len(), 1);
5036                 assert_eq!(node_txn[0].output.len(), 1);
5037
5038                 if node_txn.len() > 2 {
5039                         check_spends!(node_txn[1], commitment_txn[0]);
5040                         assert_eq!(node_txn[1].input.len(), 1);
5041                         assert_eq!(node_txn[1].output.len(), 1);
5042                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5043
5044                         check_spends!(node_txn[2], commitment_txn[0]);
5045                         assert_eq!(node_txn[2].input.len(), 1);
5046                         assert_eq!(node_txn[2].output.len(), 1);
5047                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5048                 } else {
5049                         check_spends!(node_txn[1], commitment_txn[0]);
5050                         assert_eq!(node_txn[1].input.len(), 1);
5051                         assert_eq!(node_txn[1].output.len(), 1);
5052                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5053                 }
5054
5055                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5056                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5057                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5058                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5059                 if node_txn.len() > 2 {
5060                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5061                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5062                 } else {
5063                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5064                 }
5065         }
5066
5067         nodes[2].node.claim_funds(our_payment_preimage);
5068         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5069
5070         mine_transaction(&nodes[2], &commitment_txn[0]);
5071         check_added_monitors!(nodes[2], 2);
5072         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5073         let events = nodes[2].node.get_and_clear_pending_msg_events();
5074         match events[0] {
5075                 MessageSendEvent::UpdateHTLCs { .. } => {},
5076                 _ => panic!("Unexpected event"),
5077         }
5078         match events[2] {
5079                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5080                 _ => panic!("Unexepected event"),
5081         }
5082         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5083         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5084         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5085         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5086         assert_eq!(htlc_success_txn[0].input.len(), 1);
5087         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5088         assert_eq!(htlc_success_txn[1].input.len(), 1);
5089         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5090         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5091         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5092
5093         mine_transaction(&nodes[1], &htlc_timeout_tx);
5094         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5095         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 }]);
5096         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5097         assert!(htlc_updates.update_add_htlcs.is_empty());
5098         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5099         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5100         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5101         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5102         check_added_monitors!(nodes[1], 1);
5103
5104         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5105         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5106         {
5107                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5108         }
5109         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5110
5111         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5112         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5113         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5114         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5115         assert!(updates.update_add_htlcs.is_empty());
5116         assert!(updates.update_fail_htlcs.is_empty());
5117         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5118         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5119         assert!(updates.update_fail_malformed_htlcs.is_empty());
5120         check_added_monitors!(nodes[1], 1);
5121
5122         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5123         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5124         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5125 }
5126
5127 #[test]
5128 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5129         let chanmon_cfgs = create_chanmon_cfgs(2);
5130         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5131         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5132         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5133
5134         // Create some initial channels
5135         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5136
5137         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5138         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5139         assert_eq!(local_txn.len(), 1);
5140         assert_eq!(local_txn[0].input.len(), 1);
5141         check_spends!(local_txn[0], chan_1.3);
5142
5143         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5144         nodes[1].node.claim_funds(payment_preimage);
5145         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5146         check_added_monitors!(nodes[1], 1);
5147
5148         mine_transaction(&nodes[1], &local_txn[0]);
5149         check_added_monitors!(nodes[1], 1);
5150         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5151         let events = nodes[1].node.get_and_clear_pending_msg_events();
5152         match events[0] {
5153                 MessageSendEvent::UpdateHTLCs { .. } => {},
5154                 _ => panic!("Unexpected event"),
5155         }
5156         match events[2] {
5157                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5158                 _ => panic!("Unexepected event"),
5159         }
5160         let node_tx = {
5161                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5162                 assert_eq!(node_txn.len(), 1);
5163                 assert_eq!(node_txn[0].input.len(), 1);
5164                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5165                 check_spends!(node_txn[0], local_txn[0]);
5166                 node_txn[0].clone()
5167         };
5168
5169         mine_transaction(&nodes[1], &node_tx);
5170         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5171
5172         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5173         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5174         assert_eq!(spend_txn.len(), 1);
5175         assert_eq!(spend_txn[0].input.len(), 1);
5176         check_spends!(spend_txn[0], node_tx);
5177         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5178 }
5179
5180 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5181         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5182         // unrevoked commitment transaction.
5183         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5184         // a remote RAA before they could be failed backwards (and combinations thereof).
5185         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5186         // use the same payment hashes.
5187         // Thus, we use a six-node network:
5188         //
5189         // A \         / E
5190         //    - C - D -
5191         // B /         \ F
5192         // And test where C fails back to A/B when D announces its latest commitment transaction
5193         let chanmon_cfgs = create_chanmon_cfgs(6);
5194         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5195         // When this test was written, the default base fee floated based on the HTLC count.
5196         // It is now fixed, so we simply set the fee to the expected value here.
5197         let mut config = test_default_channel_config();
5198         config.channel_config.forwarding_fee_base_msat = 196;
5199         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5200                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5201         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5202
5203         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5204         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5205         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5206         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5207         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5208
5209         // Rebalance and check output sanity...
5210         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5211         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5212         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5213
5214         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5215                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5216         // 0th HTLC:
5217         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
5218         // 1st HTLC:
5219         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
5220         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5221         // 2nd HTLC:
5222         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
5223         // 3rd HTLC:
5224         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
5225         // 4th HTLC:
5226         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5227         // 5th HTLC:
5228         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5229         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5230         // 6th HTLC:
5231         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());
5232         // 7th HTLC:
5233         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());
5234
5235         // 8th HTLC:
5236         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5237         // 9th HTLC:
5238         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5239         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
5240
5241         // 10th HTLC:
5242         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
5243         // 11th HTLC:
5244         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5245         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());
5246
5247         // Double-check that six of the new HTLC were added
5248         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5249         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5250         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5251         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5252
5253         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5254         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5255         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5256         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5257         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5258         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5259         check_added_monitors!(nodes[4], 0);
5260
5261         let failed_destinations = vec![
5262                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5263                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5264                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5265                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5266         ];
5267         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5268         check_added_monitors!(nodes[4], 1);
5269
5270         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5271         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5272         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5273         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5274         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5275         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5276
5277         // Fail 3rd below-dust and 7th above-dust HTLCs
5278         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5279         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5280         check_added_monitors!(nodes[5], 0);
5281
5282         let failed_destinations_2 = vec![
5283                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5284                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5285         ];
5286         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5287         check_added_monitors!(nodes[5], 1);
5288
5289         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5290         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5291         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5292         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5293
5294         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5295
5296         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5297         let failed_destinations_3 = vec![
5298                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
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[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5303                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5304         ];
5305         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5306         check_added_monitors!(nodes[3], 1);
5307         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5308         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5309         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5310         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5311         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5312         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5313         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5314         if deliver_last_raa {
5315                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5316         } else {
5317                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5318         }
5319
5320         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5321         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5322         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5323         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5324         //
5325         // We now broadcast the latest commitment transaction, which *should* result in failures for
5326         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5327         // the non-broadcast above-dust HTLCs.
5328         //
5329         // Alternatively, we may broadcast the previous commitment transaction, which should only
5330         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5331         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5332
5333         if announce_latest {
5334                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5335         } else {
5336                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5337         }
5338         let events = nodes[2].node.get_and_clear_pending_events();
5339         let close_event = if deliver_last_raa {
5340                 assert_eq!(events.len(), 2 + 6);
5341                 events.last().clone().unwrap()
5342         } else {
5343                 assert_eq!(events.len(), 1);
5344                 events.last().clone().unwrap()
5345         };
5346         match close_event {
5347                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5348                 _ => panic!("Unexpected event"),
5349         }
5350
5351         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5352         check_closed_broadcast!(nodes[2], true);
5353         if deliver_last_raa {
5354                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[1..2], true);
5355
5356                 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();
5357                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5358         } else {
5359                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5360                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5361                 } else {
5362                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5363                 };
5364
5365                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5366         }
5367         check_added_monitors!(nodes[2], 3);
5368
5369         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5370         assert_eq!(cs_msgs.len(), 2);
5371         let mut a_done = false;
5372         for msg in cs_msgs {
5373                 match msg {
5374                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5375                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5376                                 // should be failed-backwards here.
5377                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5378                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5379                                         for htlc in &updates.update_fail_htlcs {
5380                                                 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 });
5381                                         }
5382                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5383                                         assert!(!a_done);
5384                                         a_done = true;
5385                                         &nodes[0]
5386                                 } else {
5387                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5388                                         for htlc in &updates.update_fail_htlcs {
5389                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5390                                         }
5391                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5392                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5393                                         &nodes[1]
5394                                 };
5395                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5396                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5397                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5398                                 if announce_latest {
5399                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5400                                         if *node_id == nodes[0].node.get_our_node_id() {
5401                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5402                                         }
5403                                 }
5404                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5405                         },
5406                         _ => panic!("Unexpected event"),
5407                 }
5408         }
5409
5410         let as_events = nodes[0].node.get_and_clear_pending_events();
5411         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5412         let mut as_faileds = new_hash_set();
5413         let mut as_updates = 0;
5414         for event in as_events.iter() {
5415                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5416                         assert!(as_faileds.insert(*payment_hash));
5417                         if *payment_hash != payment_hash_2 {
5418                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5419                         } else {
5420                                 assert!(!payment_failed_permanently);
5421                         }
5422                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5423                                 as_updates += 1;
5424                         }
5425                 } else if let &Event::PaymentFailed { .. } = event {
5426                 } else { panic!("Unexpected event"); }
5427         }
5428         assert!(as_faileds.contains(&payment_hash_1));
5429         assert!(as_faileds.contains(&payment_hash_2));
5430         if announce_latest {
5431                 assert!(as_faileds.contains(&payment_hash_3));
5432                 assert!(as_faileds.contains(&payment_hash_5));
5433         }
5434         assert!(as_faileds.contains(&payment_hash_6));
5435
5436         let bs_events = nodes[1].node.get_and_clear_pending_events();
5437         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5438         let mut bs_faileds = new_hash_set();
5439         let mut bs_updates = 0;
5440         for event in bs_events.iter() {
5441                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5442                         assert!(bs_faileds.insert(*payment_hash));
5443                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5444                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5445                         } else {
5446                                 assert!(!payment_failed_permanently);
5447                         }
5448                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5449                                 bs_updates += 1;
5450                         }
5451                 } else if let &Event::PaymentFailed { .. } = event {
5452                 } else { panic!("Unexpected event"); }
5453         }
5454         assert!(bs_faileds.contains(&payment_hash_1));
5455         assert!(bs_faileds.contains(&payment_hash_2));
5456         if announce_latest {
5457                 assert!(bs_faileds.contains(&payment_hash_4));
5458         }
5459         assert!(bs_faileds.contains(&payment_hash_5));
5460
5461         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5462         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5463         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5464         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5465         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5466         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5467 }
5468
5469 #[test]
5470 fn test_fail_backwards_latest_remote_announce_a() {
5471         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5472 }
5473
5474 #[test]
5475 fn test_fail_backwards_latest_remote_announce_b() {
5476         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5477 }
5478
5479 #[test]
5480 fn test_fail_backwards_previous_remote_announce() {
5481         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5482         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5483         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5484 }
5485
5486 #[test]
5487 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5488         let chanmon_cfgs = create_chanmon_cfgs(2);
5489         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5490         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5491         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5492
5493         // Create some initial channels
5494         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5495
5496         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5497         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5498         assert_eq!(local_txn[0].input.len(), 1);
5499         check_spends!(local_txn[0], chan_1.3);
5500
5501         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5502         mine_transaction(&nodes[0], &local_txn[0]);
5503         check_closed_broadcast!(nodes[0], true);
5504         check_added_monitors!(nodes[0], 1);
5505         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5506         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5507
5508         let htlc_timeout = {
5509                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5510                 assert_eq!(node_txn.len(), 1);
5511                 assert_eq!(node_txn[0].input.len(), 1);
5512                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5513                 check_spends!(node_txn[0], local_txn[0]);
5514                 node_txn[0].clone()
5515         };
5516
5517         mine_transaction(&nodes[0], &htlc_timeout);
5518         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5519         expect_payment_failed!(nodes[0], our_payment_hash, false);
5520
5521         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5522         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5523         assert_eq!(spend_txn.len(), 3);
5524         check_spends!(spend_txn[0], local_txn[0]);
5525         assert_eq!(spend_txn[1].input.len(), 1);
5526         check_spends!(spend_txn[1], htlc_timeout);
5527         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5528         assert_eq!(spend_txn[2].input.len(), 2);
5529         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5530         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5531                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5532 }
5533
5534 #[test]
5535 fn test_key_derivation_params() {
5536         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5537         // manager rotation to test that `channel_keys_id` returned in
5538         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5539         // then derive a `delayed_payment_key`.
5540
5541         let chanmon_cfgs = create_chanmon_cfgs(3);
5542
5543         // We manually create the node configuration to backup the seed.
5544         let seed = [42; 32];
5545         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5546         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);
5547         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5548         let scorer = RwLock::new(test_utils::TestScorer::new());
5549         let router = test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[0].logger, &scorer);
5550         let message_router = test_utils::TestMessageRouter::new(network_graph.clone(), &keys_manager);
5551         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)) };
5552         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5553         node_cfgs.remove(0);
5554         node_cfgs.insert(0, node);
5555
5556         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5557         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5558
5559         // Create some initial channels
5560         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5561         // for node 0
5562         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5563         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5564         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5565
5566         // Ensure all nodes are at the same height
5567         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5568         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5569         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5570         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5571
5572         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5573         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5574         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5575         assert_eq!(local_txn_1[0].input.len(), 1);
5576         check_spends!(local_txn_1[0], chan_1.3);
5577
5578         // We check funding pubkey are unique
5579         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]));
5580         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]));
5581         if from_0_funding_key_0 == from_1_funding_key_0
5582             || from_0_funding_key_0 == from_1_funding_key_1
5583             || from_0_funding_key_1 == from_1_funding_key_0
5584             || from_0_funding_key_1 == from_1_funding_key_1 {
5585                 panic!("Funding pubkeys aren't unique");
5586         }
5587
5588         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5589         mine_transaction(&nodes[0], &local_txn_1[0]);
5590         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5591         check_closed_broadcast!(nodes[0], true);
5592         check_added_monitors!(nodes[0], 1);
5593         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5594
5595         let htlc_timeout = {
5596                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5597                 assert_eq!(node_txn.len(), 1);
5598                 assert_eq!(node_txn[0].input.len(), 1);
5599                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5600                 check_spends!(node_txn[0], local_txn_1[0]);
5601                 node_txn[0].clone()
5602         };
5603
5604         mine_transaction(&nodes[0], &htlc_timeout);
5605         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5606         expect_payment_failed!(nodes[0], our_payment_hash, false);
5607
5608         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5609         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5610         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5611         assert_eq!(spend_txn.len(), 3);
5612         check_spends!(spend_txn[0], local_txn_1[0]);
5613         assert_eq!(spend_txn[1].input.len(), 1);
5614         check_spends!(spend_txn[1], htlc_timeout);
5615         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5616         assert_eq!(spend_txn[2].input.len(), 2);
5617         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5618         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5619                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5620 }
5621
5622 #[test]
5623 fn test_static_output_closing_tx() {
5624         let chanmon_cfgs = create_chanmon_cfgs(2);
5625         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5626         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5627         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5628
5629         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5630
5631         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5632         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5633
5634         mine_transaction(&nodes[0], &closing_tx);
5635         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5636         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5637
5638         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5639         assert_eq!(spend_txn.len(), 1);
5640         check_spends!(spend_txn[0], closing_tx);
5641
5642         mine_transaction(&nodes[1], &closing_tx);
5643         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5644         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5645
5646         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5647         assert_eq!(spend_txn.len(), 1);
5648         check_spends!(spend_txn[0], closing_tx);
5649 }
5650
5651 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5652         let chanmon_cfgs = create_chanmon_cfgs(2);
5653         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5654         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5655         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5656         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5657
5658         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5659
5660         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5661         // present in B's local commitment transaction, but none of A's commitment transactions.
5662         nodes[1].node.claim_funds(payment_preimage);
5663         check_added_monitors!(nodes[1], 1);
5664         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5665
5666         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5667         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5668         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5669
5670         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5671         check_added_monitors!(nodes[0], 1);
5672         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5673         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5674         check_added_monitors!(nodes[1], 1);
5675
5676         let starting_block = nodes[1].best_block_info();
5677         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5678         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5679                 connect_block(&nodes[1], &block);
5680                 block.header.prev_blockhash = block.block_hash();
5681         }
5682         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5683         check_closed_broadcast!(nodes[1], true);
5684         check_added_monitors!(nodes[1], 1);
5685         check_closed_event!(nodes[1], 1, ClosureReason::HTLCsTimedOut, [nodes[0].node.get_our_node_id()], 100000);
5686 }
5687
5688 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5689         let chanmon_cfgs = create_chanmon_cfgs(2);
5690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5692         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5693         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5694
5695         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5696         nodes[0].node.send_payment_with_route(&route, payment_hash,
5697                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5698         check_added_monitors!(nodes[0], 1);
5699
5700         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5701
5702         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5703         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5704         // to "time out" the HTLC.
5705
5706         let starting_block = nodes[1].best_block_info();
5707         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5708
5709         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5710                 connect_block(&nodes[0], &block);
5711                 block.header.prev_blockhash = block.block_hash();
5712         }
5713         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5714         check_closed_broadcast!(nodes[0], true);
5715         check_added_monitors!(nodes[0], 1);
5716         check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5717 }
5718
5719 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5720         let chanmon_cfgs = create_chanmon_cfgs(3);
5721         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5722         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5723         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5724         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5725
5726         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5727         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5728         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5729         // actually revoked.
5730         let htlc_value = if use_dust { 50000 } else { 3000000 };
5731         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5732         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5733         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5734         check_added_monitors!(nodes[1], 1);
5735
5736         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5737         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5738         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5739         check_added_monitors!(nodes[0], 1);
5740         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5741         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5742         check_added_monitors!(nodes[1], 1);
5743         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5744         check_added_monitors!(nodes[1], 1);
5745         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5746
5747         if check_revoke_no_close {
5748                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5749                 check_added_monitors!(nodes[0], 1);
5750         }
5751
5752         let starting_block = nodes[1].best_block_info();
5753         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5754         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5755                 connect_block(&nodes[0], &block);
5756                 block.header.prev_blockhash = block.block_hash();
5757         }
5758         if !check_revoke_no_close {
5759                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5760                 check_closed_broadcast!(nodes[0], true);
5761                 check_added_monitors!(nodes[0], 1);
5762                 check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5763         } else {
5764                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5765         }
5766 }
5767
5768 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5769 // There are only a few cases to test here:
5770 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5771 //    broadcastable commitment transactions result in channel closure,
5772 //  * its included in an unrevoked-but-previous remote commitment transaction,
5773 //  * its included in the latest remote or local commitment transactions.
5774 // We test each of the three possible commitment transactions individually and use both dust and
5775 // non-dust HTLCs.
5776 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5777 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5778 // tested for at least one of the cases in other tests.
5779 #[test]
5780 fn htlc_claim_single_commitment_only_a() {
5781         do_htlc_claim_local_commitment_only(true);
5782         do_htlc_claim_local_commitment_only(false);
5783
5784         do_htlc_claim_current_remote_commitment_only(true);
5785         do_htlc_claim_current_remote_commitment_only(false);
5786 }
5787
5788 #[test]
5789 fn htlc_claim_single_commitment_only_b() {
5790         do_htlc_claim_previous_remote_commitment_only(true, false);
5791         do_htlc_claim_previous_remote_commitment_only(false, false);
5792         do_htlc_claim_previous_remote_commitment_only(true, true);
5793         do_htlc_claim_previous_remote_commitment_only(false, true);
5794 }
5795
5796 #[test]
5797 #[should_panic]
5798 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5799         let chanmon_cfgs = create_chanmon_cfgs(2);
5800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5803         // Force duplicate randomness for every get-random call
5804         for node in nodes.iter() {
5805                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5806         }
5807
5808         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5809         let channel_value_satoshis=10000;
5810         let push_msat=10001;
5811         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5812         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5813         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5814         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5815
5816         // Create a second channel with the same random values. This used to panic due to a colliding
5817         // channel_id, but now panics due to a colliding outbound SCID alias.
5818         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5819 }
5820
5821 #[test]
5822 fn bolt2_open_channel_sending_node_checks_part2() {
5823         let chanmon_cfgs = create_chanmon_cfgs(2);
5824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5826         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5827
5828         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5829         let channel_value_satoshis=2^24;
5830         let push_msat=10001;
5831         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5832
5833         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5834         let channel_value_satoshis=10000;
5835         // Test when push_msat is equal to 1000 * funding_satoshis.
5836         let push_msat=1000*channel_value_satoshis+1;
5837         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5838
5839         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5840         let channel_value_satoshis=10000;
5841         let push_msat=10001;
5842         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
5843         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5844         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.common_fields.dust_limit_satoshis);
5845
5846         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5847         // 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
5848         assert!(node0_to_1_send_open_channel.common_fields.channel_flags<=1);
5849
5850         // 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.
5851         assert!(BREAKDOWN_TIMEOUT>0);
5852         assert!(node0_to_1_send_open_channel.common_fields.to_self_delay==BREAKDOWN_TIMEOUT);
5853
5854         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5855         let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5856         assert_eq!(node0_to_1_send_open_channel.common_fields.chain_hash, chain_hash);
5857
5858         // 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.
5859         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.funding_pubkey.serialize()).is_ok());
5860         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.revocation_basepoint.serialize()).is_ok());
5861         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.htlc_basepoint.serialize()).is_ok());
5862         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.payment_basepoint.serialize()).is_ok());
5863         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.delayed_payment_basepoint.serialize()).is_ok());
5864 }
5865
5866 #[test]
5867 fn bolt2_open_channel_sane_dust_limit() {
5868         let chanmon_cfgs = create_chanmon_cfgs(2);
5869         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5870         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5871         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5872
5873         let channel_value_satoshis=1000000;
5874         let push_msat=10001;
5875         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5876         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5877         node0_to_1_send_open_channel.common_fields.dust_limit_satoshis = 547;
5878         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5879
5880         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5881         let events = nodes[1].node.get_and_clear_pending_msg_events();
5882         let err_msg = match events[0] {
5883                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5884                         msg.clone()
5885                 },
5886                 _ => panic!("Unexpected event"),
5887         };
5888         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5889 }
5890
5891 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5892 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5893 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5894 // is no longer affordable once it's freed.
5895 #[test]
5896 fn test_fail_holding_cell_htlc_upon_free() {
5897         let chanmon_cfgs = create_chanmon_cfgs(2);
5898         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5899         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5900         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5901         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5902
5903         // First nodes[0] generates an update_fee, setting the channel's
5904         // pending_update_fee.
5905         {
5906                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5907                 *feerate_lock += 20;
5908         }
5909         nodes[0].node.timer_tick_occurred();
5910         check_added_monitors!(nodes[0], 1);
5911
5912         let events = nodes[0].node.get_and_clear_pending_msg_events();
5913         assert_eq!(events.len(), 1);
5914         let (update_msg, commitment_signed) = match events[0] {
5915                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5916                         (update_fee.as_ref(), commitment_signed)
5917                 },
5918                 _ => panic!("Unexpected event"),
5919         };
5920
5921         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5922
5923         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5924         let channel_reserve = chan_stat.channel_reserve_msat;
5925         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5926         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5927
5928         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5929         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5930         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5931
5932         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5933         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5934                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5935         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5936         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5937
5938         // Flush the pending fee update.
5939         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5940         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5941         check_added_monitors!(nodes[1], 1);
5942         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5943         check_added_monitors!(nodes[0], 1);
5944
5945         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5946         // HTLC, but now that the fee has been raised the payment will now fail, causing
5947         // us to surface its failure to the user.
5948         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5949         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5950         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5951
5952         // Check that the payment failed to be sent out.
5953         let events = nodes[0].node.get_and_clear_pending_events();
5954         assert_eq!(events.len(), 2);
5955         match &events[0] {
5956                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5957                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5958                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5959                         assert_eq!(*payment_failed_permanently, false);
5960                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5961                 },
5962                 _ => panic!("Unexpected event"),
5963         }
5964         match &events[1] {
5965                 &Event::PaymentFailed { ref payment_hash, .. } => {
5966                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5967                 },
5968                 _ => panic!("Unexpected event"),
5969         }
5970 }
5971
5972 // Test that if multiple HTLCs are released from the holding cell and one is
5973 // valid but the other is no longer valid upon release, the valid HTLC can be
5974 // successfully completed while the other one fails as expected.
5975 #[test]
5976 fn test_free_and_fail_holding_cell_htlcs() {
5977         let chanmon_cfgs = create_chanmon_cfgs(2);
5978         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5979         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5980         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5981         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5982
5983         // First nodes[0] generates an update_fee, setting the channel's
5984         // pending_update_fee.
5985         {
5986                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5987                 *feerate_lock += 200;
5988         }
5989         nodes[0].node.timer_tick_occurred();
5990         check_added_monitors!(nodes[0], 1);
5991
5992         let events = nodes[0].node.get_and_clear_pending_msg_events();
5993         assert_eq!(events.len(), 1);
5994         let (update_msg, commitment_signed) = match events[0] {
5995                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5996                         (update_fee.as_ref(), commitment_signed)
5997                 },
5998                 _ => panic!("Unexpected event"),
5999         };
6000
6001         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6002
6003         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6004         let channel_reserve = chan_stat.channel_reserve_msat;
6005         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6006         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6007
6008         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6009         let amt_1 = 20000;
6010         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
6011         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6012         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6013
6014         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6015         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
6016                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6017         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6018         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6019         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6020         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6021                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6022         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6023         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6024
6025         // Flush the pending fee update.
6026         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6027         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6028         check_added_monitors!(nodes[1], 1);
6029         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6030         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6031         check_added_monitors!(nodes[0], 2);
6032
6033         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6034         // but now that the fee has been raised the second payment will now fail, causing us
6035         // to surface its failure to the user. The first payment should succeed.
6036         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6037         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6038         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6039
6040         // Check that the second payment failed to be sent out.
6041         let events = nodes[0].node.get_and_clear_pending_events();
6042         assert_eq!(events.len(), 2);
6043         match &events[0] {
6044                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6045                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6046                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6047                         assert_eq!(*payment_failed_permanently, false);
6048                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6049                 },
6050                 _ => panic!("Unexpected event"),
6051         }
6052         match &events[1] {
6053                 &Event::PaymentFailed { ref payment_hash, .. } => {
6054                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6055                 },
6056                 _ => panic!("Unexpected event"),
6057         }
6058
6059         // Complete the first payment and the RAA from the fee update.
6060         let (payment_event, send_raa_event) = {
6061                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6062                 assert_eq!(msgs.len(), 2);
6063                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6064         };
6065         let raa = match send_raa_event {
6066                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6067                 _ => panic!("Unexpected event"),
6068         };
6069         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6070         check_added_monitors!(nodes[1], 1);
6071         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6072         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6073         let events = nodes[1].node.get_and_clear_pending_events();
6074         assert_eq!(events.len(), 1);
6075         match events[0] {
6076                 Event::PendingHTLCsForwardable { .. } => {},
6077                 _ => panic!("Unexpected event"),
6078         }
6079         nodes[1].node.process_pending_htlc_forwards();
6080         let events = nodes[1].node.get_and_clear_pending_events();
6081         assert_eq!(events.len(), 1);
6082         match events[0] {
6083                 Event::PaymentClaimable { .. } => {},
6084                 _ => panic!("Unexpected event"),
6085         }
6086         nodes[1].node.claim_funds(payment_preimage_1);
6087         check_added_monitors!(nodes[1], 1);
6088         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6089
6090         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6091         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6092         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6093         expect_payment_sent!(nodes[0], payment_preimage_1);
6094 }
6095
6096 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6097 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6098 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6099 // once it's freed.
6100 #[test]
6101 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6102         let chanmon_cfgs = create_chanmon_cfgs(3);
6103         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6104         // Avoid having to include routing fees in calculations
6105         let mut config = test_default_channel_config();
6106         config.channel_config.forwarding_fee_base_msat = 0;
6107         config.channel_config.forwarding_fee_proportional_millionths = 0;
6108         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6109         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6110         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6111         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6112
6113         // First nodes[1] generates an update_fee, setting the channel's
6114         // pending_update_fee.
6115         {
6116                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6117                 *feerate_lock += 20;
6118         }
6119         nodes[1].node.timer_tick_occurred();
6120         check_added_monitors!(nodes[1], 1);
6121
6122         let events = nodes[1].node.get_and_clear_pending_msg_events();
6123         assert_eq!(events.len(), 1);
6124         let (update_msg, commitment_signed) = match events[0] {
6125                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6126                         (update_fee.as_ref(), commitment_signed)
6127                 },
6128                 _ => panic!("Unexpected event"),
6129         };
6130
6131         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6132
6133         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6134         let channel_reserve = chan_stat.channel_reserve_msat;
6135         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6136         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6137
6138         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6139         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6140         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6141         let payment_event = {
6142                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6143                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6144                 check_added_monitors!(nodes[0], 1);
6145
6146                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6147                 assert_eq!(events.len(), 1);
6148
6149                 SendEvent::from_event(events.remove(0))
6150         };
6151         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6152         check_added_monitors!(nodes[1], 0);
6153         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6154         expect_pending_htlcs_forwardable!(nodes[1]);
6155
6156         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6157         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6158
6159         // Flush the pending fee update.
6160         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6161         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6162         check_added_monitors!(nodes[2], 1);
6163         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6164         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6165         check_added_monitors!(nodes[1], 2);
6166
6167         // A final RAA message is generated to finalize the fee update.
6168         let events = nodes[1].node.get_and_clear_pending_msg_events();
6169         assert_eq!(events.len(), 1);
6170
6171         let raa_msg = match &events[0] {
6172                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6173                         msg.clone()
6174                 },
6175                 _ => panic!("Unexpected event"),
6176         };
6177
6178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6179         check_added_monitors!(nodes[2], 1);
6180         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6181
6182         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6183         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6184         assert_eq!(process_htlc_forwards_event.len(), 2);
6185         match &process_htlc_forwards_event[1] {
6186                 &Event::PendingHTLCsForwardable { .. } => {},
6187                 _ => panic!("Unexpected event"),
6188         }
6189
6190         // In response, we call ChannelManager's process_pending_htlc_forwards
6191         nodes[1].node.process_pending_htlc_forwards();
6192         check_added_monitors!(nodes[1], 1);
6193
6194         // This causes the HTLC to be failed backwards.
6195         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6196         assert_eq!(fail_event.len(), 1);
6197         let (fail_msg, commitment_signed) = match &fail_event[0] {
6198                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6199                         assert_eq!(updates.update_add_htlcs.len(), 0);
6200                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6201                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6202                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6203                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6204                 },
6205                 _ => panic!("Unexpected event"),
6206         };
6207
6208         // Pass the failure messages back to nodes[0].
6209         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6210         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6211
6212         // Complete the HTLC failure+removal process.
6213         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6214         check_added_monitors!(nodes[0], 1);
6215         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6216         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6217         check_added_monitors!(nodes[1], 2);
6218         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6219         assert_eq!(final_raa_event.len(), 1);
6220         let raa = match &final_raa_event[0] {
6221                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6222                 _ => panic!("Unexpected event"),
6223         };
6224         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6225         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6226         check_added_monitors!(nodes[0], 1);
6227 }
6228
6229 #[test]
6230 fn test_payment_route_reaching_same_channel_twice() {
6231         //A route should not go through the same channel twice
6232         //It is enforced when constructing a route.
6233         let chanmon_cfgs = create_chanmon_cfgs(2);
6234         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6235         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6236         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6237         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6238
6239         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6240                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6241         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6242
6243         // Extend the path by itself, essentially simulating route going through same channel twice
6244         let cloned_hops = route.paths[0].hops.clone();
6245         route.paths[0].hops.extend_from_slice(&cloned_hops);
6246
6247         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6248                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6249         ), false, APIError::InvalidRoute { ref err },
6250         assert_eq!(err, &"Path went through the same channel twice"));
6251 }
6252
6253 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6254 // 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.
6255 //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.
6256
6257 #[test]
6258 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6259         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6260         let chanmon_cfgs = create_chanmon_cfgs(2);
6261         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6262         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6263         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6264         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6265
6266         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6267         route.paths[0].hops[0].fee_msat = 100;
6268
6269         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6270                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6271                 ), true, APIError::ChannelUnavailable { .. }, {});
6272         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6273 }
6274
6275 #[test]
6276 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6277         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6278         let chanmon_cfgs = create_chanmon_cfgs(2);
6279         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6280         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6281         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6282         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6283
6284         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6285         route.paths[0].hops[0].fee_msat = 0;
6286         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6287                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6288                 true, APIError::ChannelUnavailable { ref err },
6289                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6290
6291         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6292         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6293 }
6294
6295 #[test]
6296 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6297         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6298         let chanmon_cfgs = create_chanmon_cfgs(2);
6299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6301         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6302         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6303
6304         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6305         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6306                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6307         check_added_monitors!(nodes[0], 1);
6308         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6309         updates.update_add_htlcs[0].amount_msat = 0;
6310
6311         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6312         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC", 3);
6313         check_closed_broadcast!(nodes[1], true).unwrap();
6314         check_added_monitors!(nodes[1], 1);
6315         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6316                 [nodes[0].node.get_our_node_id()], 100000);
6317 }
6318
6319 #[test]
6320 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6321         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6322         //It is enforced when constructing a route.
6323         let chanmon_cfgs = create_chanmon_cfgs(2);
6324         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6325         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6326         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6327         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6328
6329         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6330                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6331         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6332         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6333         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6334                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6335                 ), true, APIError::InvalidRoute { ref err },
6336                 assert_eq!(err, &"Channel CLTV overflowed?"));
6337 }
6338
6339 #[test]
6340 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6341         //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.
6342         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6343         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6344         let chanmon_cfgs = create_chanmon_cfgs(2);
6345         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6346         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6347         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6348         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6349         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6350                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6351
6352         // Fetch a route in advance as we will be unable to once we're unable to send.
6353         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6354         for i in 0..max_accepted_htlcs {
6355                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6356                 let payment_event = {
6357                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6358                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6359                         check_added_monitors!(nodes[0], 1);
6360
6361                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6362                         assert_eq!(events.len(), 1);
6363                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6364                                 assert_eq!(htlcs[0].htlc_id, i);
6365                         } else {
6366                                 assert!(false);
6367                         }
6368                         SendEvent::from_event(events.remove(0))
6369                 };
6370                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6371                 check_added_monitors!(nodes[1], 0);
6372                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6373
6374                 expect_pending_htlcs_forwardable!(nodes[1]);
6375                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6376         }
6377         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6378                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6379                 ), true, APIError::ChannelUnavailable { .. }, {});
6380
6381         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6382 }
6383
6384 #[test]
6385 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6386         //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.
6387         let chanmon_cfgs = create_chanmon_cfgs(2);
6388         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6389         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6390         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6391         let channel_value = 100000;
6392         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6393         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6394
6395         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6396
6397         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6398         // Manually create a route over our max in flight (which our router normally automatically
6399         // limits us to.
6400         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6401         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6402                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6403                 ), true, APIError::ChannelUnavailable { .. }, {});
6404         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6405
6406         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6407 }
6408
6409 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6410 #[test]
6411 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6412         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6413         let chanmon_cfgs = create_chanmon_cfgs(2);
6414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6416         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6417         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6418         let htlc_minimum_msat: u64;
6419         {
6420                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6421                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6422                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6423                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6424         }
6425
6426         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6427         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6428                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6429         check_added_monitors!(nodes[0], 1);
6430         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6431         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6432         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6433         assert!(nodes[1].node.list_channels().is_empty());
6434         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6435         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()));
6436         check_added_monitors!(nodes[1], 1);
6437         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6438 }
6439
6440 #[test]
6441 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6442         //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
6443         let chanmon_cfgs = create_chanmon_cfgs(2);
6444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6446         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6447         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6448
6449         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6450         let channel_reserve = chan_stat.channel_reserve_msat;
6451         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6452         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6453         // The 2* and +1 are for the fee spike reserve.
6454         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6455
6456         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6457         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6458         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6459                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6460         check_added_monitors!(nodes[0], 1);
6461         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6462
6463         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6464         // at this time channel-initiatee receivers are not required to enforce that senders
6465         // respect the fee_spike_reserve.
6466         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6467         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6468
6469         assert!(nodes[1].node.list_channels().is_empty());
6470         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6471         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6472         check_added_monitors!(nodes[1], 1);
6473         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6474 }
6475
6476 #[test]
6477 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6478         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6479         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6480         let chanmon_cfgs = create_chanmon_cfgs(2);
6481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6483         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6484         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6485
6486         let send_amt = 3999999;
6487         let (mut route, our_payment_hash, _, our_payment_secret) =
6488                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6489         route.paths[0].hops[0].fee_msat = send_amt;
6490         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6491         let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
6492         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6493         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6494                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6495         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6496
6497         let mut msg = msgs::UpdateAddHTLC {
6498                 channel_id: chan.2,
6499                 htlc_id: 0,
6500                 amount_msat: 1000,
6501                 payment_hash: our_payment_hash,
6502                 cltv_expiry: htlc_cltv,
6503                 onion_routing_packet: onion_packet.clone(),
6504                 skimmed_fee_msat: None,
6505                 blinding_point: None,
6506         };
6507
6508         for i in 0..50 {
6509                 msg.htlc_id = i as u64;
6510                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6511         }
6512         msg.htlc_id = (50) as u64;
6513         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6514
6515         assert!(nodes[1].node.list_channels().is_empty());
6516         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6517         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6518         check_added_monitors!(nodes[1], 1);
6519         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6520 }
6521
6522 #[test]
6523 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6524         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6525         let chanmon_cfgs = create_chanmon_cfgs(2);
6526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6528         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6529         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6530
6531         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6532         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6533                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6534         check_added_monitors!(nodes[0], 1);
6535         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6536         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;
6537         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6538
6539         assert!(nodes[1].node.list_channels().is_empty());
6540         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6541         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6542         check_added_monitors!(nodes[1], 1);
6543         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6544 }
6545
6546 #[test]
6547 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6548         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6549         let chanmon_cfgs = create_chanmon_cfgs(2);
6550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6552         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553
6554         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6555         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6556         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6557                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6558         check_added_monitors!(nodes[0], 1);
6559         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6560         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6561         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6562
6563         assert!(nodes[1].node.list_channels().is_empty());
6564         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6565         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6566         check_added_monitors!(nodes[1], 1);
6567         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6568 }
6569
6570 #[test]
6571 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6572         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6573         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6574         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6575         let chanmon_cfgs = create_chanmon_cfgs(2);
6576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6578         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6579
6580         create_announced_chan_between_nodes(&nodes, 0, 1);
6581         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6582         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6583                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6584         check_added_monitors!(nodes[0], 1);
6585         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6586         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6587
6588         //Disconnect and Reconnect
6589         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6590         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6591         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6592                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6593         }, true).unwrap();
6594         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6595         assert_eq!(reestablish_1.len(), 1);
6596         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6597                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6598         }, false).unwrap();
6599         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6600         assert_eq!(reestablish_2.len(), 1);
6601         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6602         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6603         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6604         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6605
6606         //Resend HTLC
6607         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6608         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6609         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6610         check_added_monitors!(nodes[1], 1);
6611         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6612
6613         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6614
6615         assert!(nodes[1].node.list_channels().is_empty());
6616         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6617         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6618         check_added_monitors!(nodes[1], 1);
6619         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6620 }
6621
6622 #[test]
6623 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6624         //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.
6625
6626         let chanmon_cfgs = create_chanmon_cfgs(2);
6627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6629         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6630         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6631         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6632         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6633                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6634
6635         check_added_monitors!(nodes[0], 1);
6636         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6637         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6638
6639         let update_msg = msgs::UpdateFulfillHTLC{
6640                 channel_id: chan.2,
6641                 htlc_id: 0,
6642                 payment_preimage: our_payment_preimage,
6643         };
6644
6645         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6646
6647         assert!(nodes[0].node.list_channels().is_empty());
6648         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6649         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()));
6650         check_added_monitors!(nodes[0], 1);
6651         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6652 }
6653
6654 #[test]
6655 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6656         //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.
6657
6658         let chanmon_cfgs = create_chanmon_cfgs(2);
6659         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6660         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6661         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6662         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6663
6664         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6665         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6666                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6667         check_added_monitors!(nodes[0], 1);
6668         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6669         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6670
6671         let update_msg = msgs::UpdateFailHTLC{
6672                 channel_id: chan.2,
6673                 htlc_id: 0,
6674                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6675         };
6676
6677         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6678
6679         assert!(nodes[0].node.list_channels().is_empty());
6680         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6681         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()));
6682         check_added_monitors!(nodes[0], 1);
6683         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6684 }
6685
6686 #[test]
6687 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6688         //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.
6689
6690         let chanmon_cfgs = create_chanmon_cfgs(2);
6691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6693         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6694         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6695
6696         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6697         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6698                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6699         check_added_monitors!(nodes[0], 1);
6700         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6701         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6702         let update_msg = msgs::UpdateFailMalformedHTLC{
6703                 channel_id: chan.2,
6704                 htlc_id: 0,
6705                 sha256_of_onion: [1; 32],
6706                 failure_code: 0x8000,
6707         };
6708
6709         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6710
6711         assert!(nodes[0].node.list_channels().is_empty());
6712         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6713         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()));
6714         check_added_monitors!(nodes[0], 1);
6715         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6716 }
6717
6718 #[test]
6719 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6720         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6721
6722         let chanmon_cfgs = create_chanmon_cfgs(2);
6723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6725         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6726         create_announced_chan_between_nodes(&nodes, 0, 1);
6727
6728         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6729
6730         nodes[1].node.claim_funds(our_payment_preimage);
6731         check_added_monitors!(nodes[1], 1);
6732         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6733
6734         let events = nodes[1].node.get_and_clear_pending_msg_events();
6735         assert_eq!(events.len(), 1);
6736         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6737                 match events[0] {
6738                         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, .. } } => {
6739                                 assert!(update_add_htlcs.is_empty());
6740                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6741                                 assert!(update_fail_htlcs.is_empty());
6742                                 assert!(update_fail_malformed_htlcs.is_empty());
6743                                 assert!(update_fee.is_none());
6744                                 update_fulfill_htlcs[0].clone()
6745                         },
6746                         _ => panic!("Unexpected event"),
6747                 }
6748         };
6749
6750         update_fulfill_msg.htlc_id = 1;
6751
6752         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6753
6754         assert!(nodes[0].node.list_channels().is_empty());
6755         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6756         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6757         check_added_monitors!(nodes[0], 1);
6758         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6759 }
6760
6761 #[test]
6762 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6763         //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.
6764
6765         let chanmon_cfgs = create_chanmon_cfgs(2);
6766         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6767         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6768         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6769         create_announced_chan_between_nodes(&nodes, 0, 1);
6770
6771         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6772
6773         nodes[1].node.claim_funds(our_payment_preimage);
6774         check_added_monitors!(nodes[1], 1);
6775         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6776
6777         let events = nodes[1].node.get_and_clear_pending_msg_events();
6778         assert_eq!(events.len(), 1);
6779         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6780                 match events[0] {
6781                         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, .. } } => {
6782                                 assert!(update_add_htlcs.is_empty());
6783                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6784                                 assert!(update_fail_htlcs.is_empty());
6785                                 assert!(update_fail_malformed_htlcs.is_empty());
6786                                 assert!(update_fee.is_none());
6787                                 update_fulfill_htlcs[0].clone()
6788                         },
6789                         _ => panic!("Unexpected event"),
6790                 }
6791         };
6792
6793         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6794
6795         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6796
6797         assert!(nodes[0].node.list_channels().is_empty());
6798         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6799         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6800         check_added_monitors!(nodes[0], 1);
6801         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6802 }
6803
6804 #[test]
6805 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6806         //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.
6807
6808         let chanmon_cfgs = create_chanmon_cfgs(2);
6809         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6810         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6811         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6812         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6813
6814         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6815         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6816                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6817         check_added_monitors!(nodes[0], 1);
6818
6819         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6820         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6821
6822         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6823         check_added_monitors!(nodes[1], 0);
6824         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6825
6826         let events = nodes[1].node.get_and_clear_pending_msg_events();
6827
6828         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6829                 match events[0] {
6830                         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, .. } } => {
6831                                 assert!(update_add_htlcs.is_empty());
6832                                 assert!(update_fulfill_htlcs.is_empty());
6833                                 assert!(update_fail_htlcs.is_empty());
6834                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6835                                 assert!(update_fee.is_none());
6836                                 update_fail_malformed_htlcs[0].clone()
6837                         },
6838                         _ => panic!("Unexpected event"),
6839                 }
6840         };
6841         update_msg.failure_code &= !0x8000;
6842         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6843
6844         assert!(nodes[0].node.list_channels().is_empty());
6845         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6846         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6847         check_added_monitors!(nodes[0], 1);
6848         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6849 }
6850
6851 #[test]
6852 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6853         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6854         //    * 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.
6855
6856         let chanmon_cfgs = create_chanmon_cfgs(3);
6857         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6858         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6859         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6860         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6861         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6862
6863         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6864
6865         //First hop
6866         let mut payment_event = {
6867                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6868                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6869                 check_added_monitors!(nodes[0], 1);
6870                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6871                 assert_eq!(events.len(), 1);
6872                 SendEvent::from_event(events.remove(0))
6873         };
6874         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6875         check_added_monitors!(nodes[1], 0);
6876         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6877         expect_pending_htlcs_forwardable!(nodes[1]);
6878         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6879         assert_eq!(events_2.len(), 1);
6880         check_added_monitors!(nodes[1], 1);
6881         payment_event = SendEvent::from_event(events_2.remove(0));
6882         assert_eq!(payment_event.msgs.len(), 1);
6883
6884         //Second Hop
6885         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6886         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6887         check_added_monitors!(nodes[2], 0);
6888         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6889
6890         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6891         assert_eq!(events_3.len(), 1);
6892         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6893                 match events_3[0] {
6894                         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 } } => {
6895                                 assert!(update_add_htlcs.is_empty());
6896                                 assert!(update_fulfill_htlcs.is_empty());
6897                                 assert!(update_fail_htlcs.is_empty());
6898                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6899                                 assert!(update_fee.is_none());
6900                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6901                         },
6902                         _ => panic!("Unexpected event"),
6903                 }
6904         };
6905
6906         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6907
6908         check_added_monitors!(nodes[1], 0);
6909         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6910         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 }]);
6911         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6912         assert_eq!(events_4.len(), 1);
6913
6914         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6915         match events_4[0] {
6916                 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, .. } } => {
6917                         assert!(update_add_htlcs.is_empty());
6918                         assert!(update_fulfill_htlcs.is_empty());
6919                         assert_eq!(update_fail_htlcs.len(), 1);
6920                         assert!(update_fail_malformed_htlcs.is_empty());
6921                         assert!(update_fee.is_none());
6922                 },
6923                 _ => panic!("Unexpected event"),
6924         };
6925
6926         check_added_monitors!(nodes[1], 1);
6927 }
6928
6929 #[test]
6930 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6931         let chanmon_cfgs = create_chanmon_cfgs(3);
6932         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6933         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6934         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6935         create_announced_chan_between_nodes(&nodes, 0, 1);
6936         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6937
6938         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6939
6940         // First hop
6941         let mut payment_event = {
6942                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6943                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6944                 check_added_monitors!(nodes[0], 1);
6945                 SendEvent::from_node(&nodes[0])
6946         };
6947
6948         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6949         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6950         expect_pending_htlcs_forwardable!(nodes[1]);
6951         check_added_monitors!(nodes[1], 1);
6952         payment_event = SendEvent::from_node(&nodes[1]);
6953         assert_eq!(payment_event.msgs.len(), 1);
6954
6955         // Second Hop
6956         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6957         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6958         check_added_monitors!(nodes[2], 0);
6959         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6960
6961         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6962         assert_eq!(events_3.len(), 1);
6963         match events_3[0] {
6964                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6965                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6966                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6967                         update_msg.failure_code |= 0x2000;
6968
6969                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6970                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6971                 },
6972                 _ => panic!("Unexpected event"),
6973         }
6974
6975         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6976                 vec![HTLCDestination::NextHopChannel {
6977                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6978         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6979         assert_eq!(events_4.len(), 1);
6980         check_added_monitors!(nodes[1], 1);
6981
6982         match events_4[0] {
6983                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6984                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6985                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6986                 },
6987                 _ => panic!("Unexpected event"),
6988         }
6989
6990         let events_5 = nodes[0].node.get_and_clear_pending_events();
6991         assert_eq!(events_5.len(), 2);
6992
6993         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6994         // the node originating the error to its next hop.
6995         match events_5[0] {
6996                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6997                 } => {
6998                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6999                         assert!(is_permanent);
7000                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7001                 },
7002                 _ => panic!("Unexpected event"),
7003         }
7004         match events_5[1] {
7005                 Event::PaymentFailed { payment_hash, .. } => {
7006                         assert_eq!(payment_hash, our_payment_hash);
7007                 },
7008                 _ => panic!("Unexpected event"),
7009         }
7010
7011         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7012 }
7013
7014 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7015         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7016         // 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
7017         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7018
7019         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7020         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7021         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7022         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7023         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7024         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7025
7026         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7027                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7028
7029         // We route 2 dust-HTLCs between A and B
7030         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7031         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7032         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7033
7034         // Cache one local commitment tx as previous
7035         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7036
7037         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7038         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7039         check_added_monitors!(nodes[1], 0);
7040         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7041         check_added_monitors!(nodes[1], 1);
7042
7043         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7044         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7045         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7046         check_added_monitors!(nodes[0], 1);
7047
7048         // Cache one local commitment tx as lastest
7049         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7050
7051         let events = nodes[0].node.get_and_clear_pending_msg_events();
7052         match events[0] {
7053                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7054                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7055                 },
7056                 _ => panic!("Unexpected event"),
7057         }
7058         match events[1] {
7059                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7060                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7061                 },
7062                 _ => panic!("Unexpected event"),
7063         }
7064
7065         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7066         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7067         if announce_latest {
7068                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7069         } else {
7070                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7071         }
7072
7073         check_closed_broadcast!(nodes[0], true);
7074         check_added_monitors!(nodes[0], 1);
7075         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7076
7077         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7078         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7079         let events = nodes[0].node.get_and_clear_pending_events();
7080         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7081         assert_eq!(events.len(), 4);
7082         let mut first_failed = false;
7083         for event in events {
7084                 match event {
7085                         Event::PaymentPathFailed { payment_hash, .. } => {
7086                                 if payment_hash == payment_hash_1 {
7087                                         assert!(!first_failed);
7088                                         first_failed = true;
7089                                 } else {
7090                                         assert_eq!(payment_hash, payment_hash_2);
7091                                 }
7092                         },
7093                         Event::PaymentFailed { .. } => {}
7094                         _ => panic!("Unexpected event"),
7095                 }
7096         }
7097 }
7098
7099 #[test]
7100 fn test_failure_delay_dust_htlc_local_commitment() {
7101         do_test_failure_delay_dust_htlc_local_commitment(true);
7102         do_test_failure_delay_dust_htlc_local_commitment(false);
7103 }
7104
7105 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7106         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7107         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7108         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7109         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7110         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7111         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7112
7113         let chanmon_cfgs = create_chanmon_cfgs(3);
7114         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7115         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7116         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7117         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7118
7119         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7120                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7121
7122         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7123         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7124
7125         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7126         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7127
7128         // We revoked bs_commitment_tx
7129         if revoked {
7130                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7131                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7132         }
7133
7134         let mut timeout_tx = Vec::new();
7135         if local {
7136                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7137                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7138                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7139                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7140                 expect_payment_failed!(nodes[0], dust_hash, false);
7141
7142                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7143                 check_closed_broadcast!(nodes[0], true);
7144                 check_added_monitors!(nodes[0], 1);
7145                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7146                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7147                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7148                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7149                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7150                 mine_transaction(&nodes[0], &timeout_tx[0]);
7151                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7152                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7153         } else {
7154                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7155                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7156                 check_closed_broadcast!(nodes[0], true);
7157                 check_added_monitors!(nodes[0], 1);
7158                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7159                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7160
7161                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7162                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7163                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7164                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7165                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7166                 // dust HTLC should have been failed.
7167                 expect_payment_failed!(nodes[0], dust_hash, false);
7168
7169                 if !revoked {
7170                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7171                 } else {
7172                         assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7173                 }
7174                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7175                 mine_transaction(&nodes[0], &timeout_tx[0]);
7176                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7177                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7178                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7179         }
7180 }
7181
7182 #[test]
7183 fn test_sweep_outbound_htlc_failure_update() {
7184         do_test_sweep_outbound_htlc_failure_update(false, true);
7185         do_test_sweep_outbound_htlc_failure_update(false, false);
7186         do_test_sweep_outbound_htlc_failure_update(true, false);
7187 }
7188
7189 #[test]
7190 fn test_user_configurable_csv_delay() {
7191         // We test our channel constructors yield errors when we pass them absurd csv delay
7192
7193         let mut low_our_to_self_config = UserConfig::default();
7194         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7195         let mut high_their_to_self_config = UserConfig::default();
7196         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7197         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7198         let chanmon_cfgs = create_chanmon_cfgs(2);
7199         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7200         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7201         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7202
7203         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7204         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7205                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7206                 &low_our_to_self_config, 0, 42, None)
7207         {
7208                 match error {
7209                         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())); },
7210                         _ => panic!("Unexpected event"),
7211                 }
7212         } else { assert!(false) }
7213
7214         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7215         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7216         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7217         open_channel.common_fields.to_self_delay = 200;
7218         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7219                 &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,
7220                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7221         {
7222                 match error {
7223                         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()));  },
7224                         _ => panic!("Unexpected event"),
7225                 }
7226         } else { assert!(false); }
7227
7228         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7229         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7230         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()));
7231         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7232         accept_channel.common_fields.to_self_delay = 200;
7233         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7234         let reason_msg;
7235         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7236                 match action {
7237                         &ErrorAction::SendErrorMessage { ref msg } => {
7238                                 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()));
7239                                 reason_msg = msg.data.clone();
7240                         },
7241                         _ => { panic!(); }
7242                 }
7243         } else { panic!(); }
7244         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7245
7246         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7247         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7248         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7249         open_channel.common_fields.to_self_delay = 200;
7250         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7251                 &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,
7252                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7253         {
7254                 match error {
7255                         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())); },
7256                         _ => panic!("Unexpected event"),
7257                 }
7258         } else { assert!(false); }
7259 }
7260
7261 #[test]
7262 fn test_check_htlc_underpaying() {
7263         // Send payment through A -> B but A is maliciously
7264         // sending a probe payment (i.e less than expected value0
7265         // to B, B should refuse payment.
7266
7267         let chanmon_cfgs = create_chanmon_cfgs(2);
7268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7270         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7271
7272         // Create some initial channels
7273         create_announced_chan_between_nodes(&nodes, 0, 1);
7274
7275         let scorer = test_utils::TestScorer::new();
7276         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7277         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7278                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7279         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7280         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7281                 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7282         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7283         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7284         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7285                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7286         check_added_monitors!(nodes[0], 1);
7287
7288         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7289         assert_eq!(events.len(), 1);
7290         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7291         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7292         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7293
7294         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7295         // and then will wait a second random delay before failing the HTLC back:
7296         expect_pending_htlcs_forwardable!(nodes[1]);
7297         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7298
7299         // Node 3 is expecting payment of 100_000 but received 10_000,
7300         // it should fail htlc like we didn't know the preimage.
7301         nodes[1].node.process_pending_htlc_forwards();
7302
7303         let events = nodes[1].node.get_and_clear_pending_msg_events();
7304         assert_eq!(events.len(), 1);
7305         let (update_fail_htlc, commitment_signed) = match events[0] {
7306                 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 } } => {
7307                         assert!(update_add_htlcs.is_empty());
7308                         assert!(update_fulfill_htlcs.is_empty());
7309                         assert_eq!(update_fail_htlcs.len(), 1);
7310                         assert!(update_fail_malformed_htlcs.is_empty());
7311                         assert!(update_fee.is_none());
7312                         (update_fail_htlcs[0].clone(), commitment_signed)
7313                 },
7314                 _ => panic!("Unexpected event"),
7315         };
7316         check_added_monitors!(nodes[1], 1);
7317
7318         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7319         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7320
7321         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7322         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7323         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7324         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7325 }
7326
7327 #[test]
7328 fn test_announce_disable_channels() {
7329         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7330         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7331
7332         let chanmon_cfgs = create_chanmon_cfgs(2);
7333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7335         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7336
7337         // Connect a dummy node for proper future events broadcasting
7338         connect_dummy_node(&nodes[0]);
7339
7340         create_announced_chan_between_nodes(&nodes, 0, 1);
7341         create_announced_chan_between_nodes(&nodes, 1, 0);
7342         create_announced_chan_between_nodes(&nodes, 0, 1);
7343
7344         // Disconnect peers
7345         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7346         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7347
7348         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7349                 nodes[0].node.timer_tick_occurred();
7350         }
7351         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7352         assert_eq!(msg_events.len(), 3);
7353         let mut chans_disabled = new_hash_map();
7354         for e in msg_events {
7355                 match e {
7356                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7357                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7358                                 // Check that each channel gets updated exactly once
7359                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7360                                         panic!("Generated ChannelUpdate for wrong chan!");
7361                                 }
7362                         },
7363                         _ => panic!("Unexpected event"),
7364                 }
7365         }
7366         // Reconnect peers
7367         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7368                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7369         }, true).unwrap();
7370         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7371         assert_eq!(reestablish_1.len(), 3);
7372         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7373                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7374         }, false).unwrap();
7375         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7376         assert_eq!(reestablish_2.len(), 3);
7377
7378         // Reestablish chan_1
7379         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7380         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7381         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7382         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7383         // Reestablish chan_2
7384         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7385         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7386         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7387         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7388         // Reestablish chan_3
7389         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7390         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7391         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7392         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7393
7394         for _ in 0..ENABLE_GOSSIP_TICKS {
7395                 nodes[0].node.timer_tick_occurred();
7396         }
7397         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7398         nodes[0].node.timer_tick_occurred();
7399         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7400         assert_eq!(msg_events.len(), 3);
7401         for e in msg_events {
7402                 match e {
7403                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7404                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7405                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7406                                         // Each update should have a higher timestamp than the previous one, replacing
7407                                         // the old one.
7408                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7409                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7410                                 }
7411                         },
7412                         _ => panic!("Unexpected event"),
7413                 }
7414         }
7415         // Check that each channel gets updated exactly once
7416         assert!(chans_disabled.is_empty());
7417 }
7418
7419 #[test]
7420 fn test_bump_penalty_txn_on_revoked_commitment() {
7421         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7422         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7423
7424         let chanmon_cfgs = create_chanmon_cfgs(2);
7425         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7426         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7427         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7428
7429         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7430
7431         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7432         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7433                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7434         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7435         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7436
7437         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7438         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7439         assert_eq!(revoked_txn[0].output.len(), 4);
7440         assert_eq!(revoked_txn[0].input.len(), 1);
7441         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7442         let revoked_txid = revoked_txn[0].txid();
7443
7444         let mut penalty_sum = 0;
7445         for outp in revoked_txn[0].output.iter() {
7446                 if outp.script_pubkey.is_v0_p2wsh() {
7447                         penalty_sum += outp.value;
7448                 }
7449         }
7450
7451         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7452         let header_114 = connect_blocks(&nodes[1], 14);
7453
7454         // Actually revoke tx by claiming a HTLC
7455         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7456         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7457         check_added_monitors!(nodes[1], 1);
7458
7459         // One or more justice tx should have been broadcast, check it
7460         let penalty_1;
7461         let feerate_1;
7462         {
7463                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7464                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7465                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7466                 assert_eq!(node_txn[0].output.len(), 1);
7467                 check_spends!(node_txn[0], revoked_txn[0]);
7468                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7469                 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7470                 penalty_1 = node_txn[0].txid();
7471                 node_txn.clear();
7472         };
7473
7474         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7475         connect_blocks(&nodes[1], 15);
7476         let mut penalty_2 = penalty_1;
7477         let mut feerate_2 = 0;
7478         {
7479                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7480                 assert_eq!(node_txn.len(), 1);
7481                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7482                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7483                         assert_eq!(node_txn[0].output.len(), 1);
7484                         check_spends!(node_txn[0], revoked_txn[0]);
7485                         penalty_2 = node_txn[0].txid();
7486                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7487                         assert_ne!(penalty_2, penalty_1);
7488                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7489                         feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7490                         // Verify 25% bump heuristic
7491                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7492                         node_txn.clear();
7493                 }
7494         }
7495         assert_ne!(feerate_2, 0);
7496
7497         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7498         connect_blocks(&nodes[1], 1);
7499         let penalty_3;
7500         let mut feerate_3 = 0;
7501         {
7502                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7503                 assert_eq!(node_txn.len(), 1);
7504                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7505                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7506                         assert_eq!(node_txn[0].output.len(), 1);
7507                         check_spends!(node_txn[0], revoked_txn[0]);
7508                         penalty_3 = node_txn[0].txid();
7509                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7510                         assert_ne!(penalty_3, penalty_2);
7511                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7512                         feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7513                         // Verify 25% bump heuristic
7514                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7515                         node_txn.clear();
7516                 }
7517         }
7518         assert_ne!(feerate_3, 0);
7519
7520         nodes[1].node.get_and_clear_pending_events();
7521         nodes[1].node.get_and_clear_pending_msg_events();
7522 }
7523
7524 #[test]
7525 fn test_bump_penalty_txn_on_revoked_htlcs() {
7526         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7527         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7528
7529         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7530         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7531         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7532         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7533         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7534
7535         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7536         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7537         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();
7538         let scorer = test_utils::TestScorer::new();
7539         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7540         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7541         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7542                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7543         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7544         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7545                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7546         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7547         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7548                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7549         let failed_payment_hash = send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000).1;
7550
7551         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7552         assert_eq!(revoked_local_txn[0].input.len(), 1);
7553         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7554
7555         // Revoke local commitment tx
7556         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7557
7558         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7559         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7560         check_closed_broadcast!(nodes[1], true);
7561         check_added_monitors!(nodes[1], 1);
7562         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7563         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7564
7565         let revoked_htlc_txn = {
7566                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7567                 assert_eq!(txn.len(), 2);
7568
7569                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7570                 assert_eq!(txn[0].input.len(), 1);
7571                 check_spends!(txn[0], revoked_local_txn[0]);
7572
7573                 assert_eq!(txn[1].input.len(), 1);
7574                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7575                 assert_eq!(txn[1].output.len(), 1);
7576                 check_spends!(txn[1], revoked_local_txn[0]);
7577
7578                 txn
7579         };
7580
7581         // Broadcast set of revoked txn on A
7582         let hash_128 = connect_blocks(&nodes[0], 40);
7583         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7584         connect_block(&nodes[0], &block_11);
7585         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7586         connect_block(&nodes[0], &block_129);
7587         let events = nodes[0].node.get_and_clear_pending_events();
7588         expect_pending_htlcs_forwardable_conditions(events[0..2].to_vec(), &[HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
7589         match events.last().unwrap() {
7590                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7591                 _ => panic!("Unexpected event"),
7592         }
7593         let first;
7594         let feerate_1;
7595         let penalty_txn;
7596         {
7597                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7598                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7599                 // Verify claim tx are spending revoked HTLC txn
7600
7601                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7602                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7603                 // which are included in the same block (they are broadcasted because we scan the
7604                 // transactions linearly and generate claims as we go, they likely should be removed in the
7605                 // future).
7606                 assert_eq!(node_txn[0].input.len(), 1);
7607                 check_spends!(node_txn[0], revoked_local_txn[0]);
7608                 assert_eq!(node_txn[1].input.len(), 1);
7609                 check_spends!(node_txn[1], revoked_local_txn[0]);
7610                 assert_eq!(node_txn[2].input.len(), 1);
7611                 check_spends!(node_txn[2], revoked_local_txn[0]);
7612
7613                 // Each of the three justice transactions claim a separate (single) output of the three
7614                 // available, which we check here:
7615                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7616                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7617                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7618
7619                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7620                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7621
7622                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7623                 // output, checked above).
7624                 assert_eq!(node_txn[3].input.len(), 2);
7625                 assert_eq!(node_txn[3].output.len(), 1);
7626                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7627
7628                 first = node_txn[3].txid();
7629                 // Store both feerates for later comparison
7630                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7631                 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7632                 penalty_txn = vec![node_txn[2].clone()];
7633                 node_txn.clear();
7634         }
7635
7636         // Connect one more block to see if bumped penalty are issued for HTLC txn
7637         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7638         connect_block(&nodes[0], &block_130);
7639         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7640         connect_block(&nodes[0], &block_131);
7641
7642         // Few more blocks to confirm penalty txn
7643         connect_blocks(&nodes[0], 4);
7644         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7645         let header_144 = connect_blocks(&nodes[0], 9);
7646         let node_txn = {
7647                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7648                 assert_eq!(node_txn.len(), 1);
7649
7650                 assert_eq!(node_txn[0].input.len(), 2);
7651                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7652                 // Verify bumped tx is different and 25% bump heuristic
7653                 assert_ne!(first, node_txn[0].txid());
7654                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7655                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7656                 assert!(feerate_2 * 100 > feerate_1 * 125);
7657                 let txn = vec![node_txn[0].clone()];
7658                 node_txn.clear();
7659                 txn
7660         };
7661         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7662         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7663         connect_blocks(&nodes[0], 20);
7664         {
7665                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7666                 // We verify than no new transaction has been broadcast because previously
7667                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7668                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7669                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7670                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7671                 // up bumped justice generation.
7672                 assert_eq!(node_txn.len(), 0);
7673                 node_txn.clear();
7674         }
7675         check_closed_broadcast!(nodes[0], true);
7676         check_added_monitors!(nodes[0], 1);
7677 }
7678
7679 #[test]
7680 fn test_bump_penalty_txn_on_remote_commitment() {
7681         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7682         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7683
7684         // Create 2 HTLCs
7685         // Provide preimage for one
7686         // Check aggregation
7687
7688         let chanmon_cfgs = create_chanmon_cfgs(2);
7689         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7690         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7691         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7692
7693         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7694         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7695         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7696
7697         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7698         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7699         assert_eq!(remote_txn[0].output.len(), 4);
7700         assert_eq!(remote_txn[0].input.len(), 1);
7701         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7702
7703         // Claim a HTLC without revocation (provide B monitor with preimage)
7704         nodes[1].node.claim_funds(payment_preimage);
7705         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7706         mine_transaction(&nodes[1], &remote_txn[0]);
7707         check_added_monitors!(nodes[1], 2);
7708         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7709
7710         // One or more claim tx should have been broadcast, check it
7711         let timeout;
7712         let preimage;
7713         let preimage_bump;
7714         let feerate_timeout;
7715         let feerate_preimage;
7716         {
7717                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7718                 // 3 transactions including:
7719                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7720                 assert_eq!(node_txn.len(), 3);
7721                 assert_eq!(node_txn[0].input.len(), 1);
7722                 assert_eq!(node_txn[1].input.len(), 1);
7723                 assert_eq!(node_txn[2].input.len(), 1);
7724                 check_spends!(node_txn[0], remote_txn[0]);
7725                 check_spends!(node_txn[1], remote_txn[0]);
7726                 check_spends!(node_txn[2], remote_txn[0]);
7727
7728                 preimage = node_txn[0].txid();
7729                 let index = node_txn[0].input[0].previous_output.vout;
7730                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7731                 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7732
7733                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7734                         (node_txn[2].clone(), node_txn[1].clone())
7735                 } else {
7736                         (node_txn[1].clone(), node_txn[2].clone())
7737                 };
7738
7739                 preimage_bump = preimage_bump_tx;
7740                 check_spends!(preimage_bump, remote_txn[0]);
7741                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7742
7743                 timeout = timeout_tx.txid();
7744                 let index = timeout_tx.input[0].previous_output.vout;
7745                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7746                 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7747
7748                 node_txn.clear();
7749         };
7750         assert_ne!(feerate_timeout, 0);
7751         assert_ne!(feerate_preimage, 0);
7752
7753         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7754         connect_blocks(&nodes[1], 1);
7755         {
7756                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7757                 assert_eq!(node_txn.len(), 1);
7758                 assert_eq!(node_txn[0].input.len(), 1);
7759                 assert_eq!(preimage_bump.input.len(), 1);
7760                 check_spends!(node_txn[0], remote_txn[0]);
7761                 check_spends!(preimage_bump, remote_txn[0]);
7762
7763                 let index = preimage_bump.input[0].previous_output.vout;
7764                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7765                 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7766                 assert!(new_feerate * 100 > feerate_timeout * 125);
7767                 assert_ne!(timeout, preimage_bump.txid());
7768
7769                 let index = node_txn[0].input[0].previous_output.vout;
7770                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7771                 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7772                 assert!(new_feerate * 100 > feerate_preimage * 125);
7773                 assert_ne!(preimage, node_txn[0].txid());
7774
7775                 node_txn.clear();
7776         }
7777
7778         nodes[1].node.get_and_clear_pending_events();
7779         nodes[1].node.get_and_clear_pending_msg_events();
7780 }
7781
7782 #[test]
7783 fn test_counterparty_raa_skip_no_crash() {
7784         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7785         // commitment transaction, we would have happily carried on and provided them the next
7786         // commitment transaction based on one RAA forward. This would probably eventually have led to
7787         // channel closure, but it would not have resulted in funds loss. Still, our
7788         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7789         // check simply that the channel is closed in response to such an RAA, but don't check whether
7790         // we decide to punish our counterparty for revoking their funds (as we don't currently
7791         // implement that).
7792         let chanmon_cfgs = create_chanmon_cfgs(2);
7793         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7794         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7795         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7796         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7797
7798         let per_commitment_secret;
7799         let next_per_commitment_point;
7800         {
7801                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7802                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7803                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7804                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7805                 ).flatten().unwrap().get_signer();
7806
7807                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7808
7809                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7810                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7811                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7812
7813                 // Must revoke without gaps
7814                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7815                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7816
7817                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7818                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7819                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7820         }
7821
7822         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7823                 &msgs::RevokeAndACK {
7824                         channel_id,
7825                         per_commitment_secret,
7826                         next_per_commitment_point,
7827                         #[cfg(taproot)]
7828                         next_local_nonce: None,
7829                 });
7830         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7831         check_added_monitors!(nodes[1], 1);
7832         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7833                 , [nodes[0].node.get_our_node_id()], 100000);
7834 }
7835
7836 #[test]
7837 fn test_bump_txn_sanitize_tracking_maps() {
7838         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7839         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7840
7841         let chanmon_cfgs = create_chanmon_cfgs(2);
7842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7844         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7845
7846         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7847         // Lock HTLC in both directions
7848         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7849         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7850
7851         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7852         assert_eq!(revoked_local_txn[0].input.len(), 1);
7853         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7854
7855         // Revoke local commitment tx
7856         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7857
7858         // Broadcast set of revoked txn on A
7859         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7860         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7861         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7862
7863         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7864         check_closed_broadcast!(nodes[0], true);
7865         check_added_monitors!(nodes[0], 1);
7866         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7867         let penalty_txn = {
7868                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7869                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7870                 check_spends!(node_txn[0], revoked_local_txn[0]);
7871                 check_spends!(node_txn[1], revoked_local_txn[0]);
7872                 check_spends!(node_txn[2], revoked_local_txn[0]);
7873                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7874                 node_txn.clear();
7875                 penalty_txn
7876         };
7877         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7878         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7879         {
7880                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7881                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7882                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7883         }
7884 }
7885
7886 #[test]
7887 fn test_channel_conf_timeout() {
7888         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7889         // confirm within 2016 blocks, as recommended by BOLT 2.
7890         let chanmon_cfgs = create_chanmon_cfgs(2);
7891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7893         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7894
7895         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7896
7897         // The outbound node should wait forever for confirmation:
7898         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7899         // copied here instead of directly referencing the constant.
7900         connect_blocks(&nodes[0], 2016);
7901         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7902
7903         // The inbound node should fail the channel after exactly 2016 blocks
7904         connect_blocks(&nodes[1], 2015);
7905         check_added_monitors!(nodes[1], 0);
7906         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7907
7908         connect_blocks(&nodes[1], 1);
7909         check_added_monitors!(nodes[1], 1);
7910         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7911         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7912         assert_eq!(close_ev.len(), 1);
7913         match close_ev[0] {
7914                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7915                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7916                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7917                 },
7918                 _ => panic!("Unexpected event"),
7919         }
7920 }
7921
7922 #[test]
7923 fn test_override_channel_config() {
7924         let chanmon_cfgs = create_chanmon_cfgs(2);
7925         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7926         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7927         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7928
7929         // Node0 initiates a channel to node1 using the override config.
7930         let mut override_config = UserConfig::default();
7931         override_config.channel_handshake_config.our_to_self_delay = 200;
7932
7933         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7934
7935         // Assert the channel created by node0 is using the override config.
7936         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7937         assert_eq!(res.common_fields.channel_flags, 0);
7938         assert_eq!(res.common_fields.to_self_delay, 200);
7939 }
7940
7941 #[test]
7942 fn test_override_0msat_htlc_minimum() {
7943         let mut zero_config = UserConfig::default();
7944         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7945         let chanmon_cfgs = create_chanmon_cfgs(2);
7946         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7947         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7948         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7949
7950         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7951         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7952         assert_eq!(res.common_fields.htlc_minimum_msat, 1);
7953
7954         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7955         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7956         assert_eq!(res.common_fields.htlc_minimum_msat, 1);
7957 }
7958
7959 #[test]
7960 fn test_channel_update_has_correct_htlc_maximum_msat() {
7961         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7962         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7963         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7964         // 90% of the `channel_value`.
7965         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7966
7967         let mut config_30_percent = UserConfig::default();
7968         config_30_percent.channel_handshake_config.announced_channel = true;
7969         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7970         let mut config_50_percent = UserConfig::default();
7971         config_50_percent.channel_handshake_config.announced_channel = true;
7972         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7973         let mut config_95_percent = UserConfig::default();
7974         config_95_percent.channel_handshake_config.announced_channel = true;
7975         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7976         let mut config_100_percent = UserConfig::default();
7977         config_100_percent.channel_handshake_config.announced_channel = true;
7978         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7979
7980         let chanmon_cfgs = create_chanmon_cfgs(4);
7981         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7982         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)]);
7983         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7984
7985         let channel_value_satoshis = 100000;
7986         let channel_value_msat = channel_value_satoshis * 1000;
7987         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7988         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7989         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7990
7991         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7992         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7993
7994         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7995         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7996         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7997         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7998         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7999         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8000
8001         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8002         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8003         // `channel_value`.
8004         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8005         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8006         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8007         // `channel_value`.
8008         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8009 }
8010
8011 #[test]
8012 fn test_manually_accept_inbound_channel_request() {
8013         let mut manually_accept_conf = UserConfig::default();
8014         manually_accept_conf.manually_accept_inbound_channels = true;
8015         let chanmon_cfgs = create_chanmon_cfgs(2);
8016         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8017         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8018         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8019
8020         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();
8021         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8022
8023         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8024
8025         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8026         // accepting the inbound channel request.
8027         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8028
8029         let events = nodes[1].node.get_and_clear_pending_events();
8030         match events[0] {
8031                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8032                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8033                 }
8034                 _ => panic!("Unexpected event"),
8035         }
8036
8037         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8038         assert_eq!(accept_msg_ev.len(), 1);
8039
8040         match accept_msg_ev[0] {
8041                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8042                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8043                 }
8044                 _ => panic!("Unexpected event"),
8045         }
8046
8047         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8048
8049         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8050         assert_eq!(close_msg_ev.len(), 1);
8051
8052         let events = nodes[1].node.get_and_clear_pending_events();
8053         match events[0] {
8054                 Event::ChannelClosed { user_channel_id, .. } => {
8055                         assert_eq!(user_channel_id, 23);
8056                 }
8057                 _ => panic!("Unexpected event"),
8058         }
8059 }
8060
8061 #[test]
8062 fn test_manually_reject_inbound_channel_request() {
8063         let mut manually_accept_conf = UserConfig::default();
8064         manually_accept_conf.manually_accept_inbound_channels = true;
8065         let chanmon_cfgs = create_chanmon_cfgs(2);
8066         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8067         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8068         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8069
8070         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8071         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8072
8073         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8074
8075         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8076         // rejecting the inbound channel request.
8077         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8078
8079         let events = nodes[1].node.get_and_clear_pending_events();
8080         match events[0] {
8081                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8082                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8083                 }
8084                 _ => panic!("Unexpected event"),
8085         }
8086
8087         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8088         assert_eq!(close_msg_ev.len(), 1);
8089
8090         match close_msg_ev[0] {
8091                 MessageSendEvent::HandleError { ref node_id, .. } => {
8092                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8093                 }
8094                 _ => panic!("Unexpected event"),
8095         }
8096
8097         // There should be no more events to process, as the channel was never opened.
8098         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8099 }
8100
8101 #[test]
8102 fn test_can_not_accept_inbound_channel_twice() {
8103         let mut manually_accept_conf = UserConfig::default();
8104         manually_accept_conf.manually_accept_inbound_channels = true;
8105         let chanmon_cfgs = create_chanmon_cfgs(2);
8106         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8107         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8108         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8109
8110         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8111         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8112
8113         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8114
8115         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8116         // accepting the inbound channel request.
8117         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8118
8119         let events = nodes[1].node.get_and_clear_pending_events();
8120         match events[0] {
8121                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8122                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8123                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8124                         match api_res {
8125                                 Err(APIError::APIMisuseError { err }) => {
8126                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8127                                 },
8128                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8129                                 Err(e) => panic!("Unexpected Error {:?}", e),
8130                         }
8131                 }
8132                 _ => panic!("Unexpected event"),
8133         }
8134
8135         // Ensure that the channel wasn't closed after attempting to accept it twice.
8136         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8137         assert_eq!(accept_msg_ev.len(), 1);
8138
8139         match accept_msg_ev[0] {
8140                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8141                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8142                 }
8143                 _ => panic!("Unexpected event"),
8144         }
8145 }
8146
8147 #[test]
8148 fn test_can_not_accept_unknown_inbound_channel() {
8149         let chanmon_cfg = create_chanmon_cfgs(2);
8150         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8151         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8152         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8153
8154         let unknown_channel_id = ChannelId::new_zero();
8155         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8156         match api_res {
8157                 Err(APIError::APIMisuseError { err }) => {
8158                         assert_eq!(err, "No such channel awaiting to be accepted.");
8159                 },
8160                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8161                 Err(e) => panic!("Unexpected Error: {:?}", e),
8162         }
8163 }
8164
8165 #[test]
8166 fn test_onion_value_mpp_set_calculation() {
8167         // Test that we use the onion value `amt_to_forward` when
8168         // calculating whether we've reached the `total_msat` of an MPP
8169         // by having a routing node forward more than `amt_to_forward`
8170         // and checking that the receiving node doesn't generate
8171         // a PaymentClaimable event too early
8172         let node_count = 4;
8173         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8174         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8175         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8176         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8177
8178         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8179         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8180         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8181         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8182
8183         let total_msat = 100_000;
8184         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8185         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8186         let sample_path = route.paths.pop().unwrap();
8187
8188         let mut path_1 = sample_path.clone();
8189         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8190         path_1.hops[0].short_channel_id = chan_1_id;
8191         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8192         path_1.hops[1].short_channel_id = chan_3_id;
8193         path_1.hops[1].fee_msat = 100_000;
8194         route.paths.push(path_1);
8195
8196         let mut path_2 = sample_path.clone();
8197         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8198         path_2.hops[0].short_channel_id = chan_2_id;
8199         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8200         path_2.hops[1].short_channel_id = chan_4_id;
8201         path_2.hops[1].fee_msat = 1_000;
8202         route.paths.push(path_2);
8203
8204         // Send payment
8205         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8206         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8207                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8208         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8209                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8210         check_added_monitors!(nodes[0], expected_paths.len());
8211
8212         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8213         assert_eq!(events.len(), expected_paths.len());
8214
8215         // First path
8216         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8217         let mut payment_event = SendEvent::from_event(ev);
8218         let mut prev_node = &nodes[0];
8219
8220         for (idx, &node) in expected_paths[0].iter().enumerate() {
8221                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8222
8223                 if idx == 0 { // routing node
8224                         let session_priv = [3; 32];
8225                         let height = nodes[0].best_block_info().1;
8226                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8227                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8228                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8229                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8230                         // Edit amt_to_forward to simulate the sender having set
8231                         // the final amount and the routing node taking less fee
8232                         if let msgs::OutboundOnionPayload::Receive {
8233                                 ref mut sender_intended_htlc_amt_msat, ..
8234                         } = onion_payloads[1] {
8235                                 *sender_intended_htlc_amt_msat = 99_000;
8236                         } else { panic!() }
8237                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8238                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8239                 }
8240
8241                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8242                 check_added_monitors!(node, 0);
8243                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8244                 expect_pending_htlcs_forwardable!(node);
8245
8246                 if idx == 0 {
8247                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8248                         assert_eq!(events_2.len(), 1);
8249                         check_added_monitors!(node, 1);
8250                         payment_event = SendEvent::from_event(events_2.remove(0));
8251                         assert_eq!(payment_event.msgs.len(), 1);
8252                 } else {
8253                         let events_2 = node.node.get_and_clear_pending_events();
8254                         assert!(events_2.is_empty());
8255                 }
8256
8257                 prev_node = node;
8258         }
8259
8260         // Second path
8261         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8262         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8263
8264         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8265 }
8266
8267 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8268
8269         let routing_node_count = msat_amounts.len();
8270         let node_count = routing_node_count + 2;
8271
8272         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8273         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8274         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8275         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8276
8277         let src_idx = 0;
8278         let dst_idx = 1;
8279
8280         // Create channels for each amount
8281         let mut expected_paths = Vec::with_capacity(routing_node_count);
8282         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8283         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8284         for i in 0..routing_node_count {
8285                 let routing_node = 2 + i;
8286                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8287                 src_chan_ids.push(src_chan_id);
8288                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8289                 dst_chan_ids.push(dst_chan_id);
8290                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8291                 expected_paths.push(path);
8292         }
8293         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8294
8295         // Create a route for each amount
8296         let example_amount = 100000;
8297         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);
8298         let sample_path = route.paths.pop().unwrap();
8299         for i in 0..routing_node_count {
8300                 let routing_node = 2 + i;
8301                 let mut path = sample_path.clone();
8302                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8303                 path.hops[0].short_channel_id = src_chan_ids[i];
8304                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8305                 path.hops[1].short_channel_id = dst_chan_ids[i];
8306                 path.hops[1].fee_msat = msat_amounts[i];
8307                 route.paths.push(path);
8308         }
8309
8310         // Send payment with manually set total_msat
8311         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8312         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8313                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8314         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8315                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8316         check_added_monitors!(nodes[src_idx], expected_paths.len());
8317
8318         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8319         assert_eq!(events.len(), expected_paths.len());
8320         let mut amount_received = 0;
8321         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8322                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8323
8324                 let current_path_amount = msat_amounts[path_idx];
8325                 amount_received += current_path_amount;
8326                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8327                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8328         }
8329
8330         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8331 }
8332
8333 #[test]
8334 fn test_overshoot_mpp() {
8335         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8336         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8337 }
8338
8339 #[test]
8340 fn test_simple_mpp() {
8341         // Simple test of sending a multi-path payment.
8342         let chanmon_cfgs = create_chanmon_cfgs(4);
8343         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8344         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8345         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8346
8347         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8348         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8349         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8350         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8351
8352         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8353         let path = route.paths[0].clone();
8354         route.paths.push(path);
8355         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8356         route.paths[0].hops[0].short_channel_id = chan_1_id;
8357         route.paths[0].hops[1].short_channel_id = chan_3_id;
8358         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8359         route.paths[1].hops[0].short_channel_id = chan_2_id;
8360         route.paths[1].hops[1].short_channel_id = chan_4_id;
8361         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8362         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8363 }
8364
8365 #[test]
8366 fn test_preimage_storage() {
8367         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8368         let chanmon_cfgs = create_chanmon_cfgs(2);
8369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8371         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8372
8373         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8374
8375         {
8376                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8377                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8378                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8379                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8380                 check_added_monitors!(nodes[0], 1);
8381                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8382                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8383                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8384                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8385         }
8386         // Note that after leaving the above scope we have no knowledge of any arguments or return
8387         // values from previous calls.
8388         expect_pending_htlcs_forwardable!(nodes[1]);
8389         let events = nodes[1].node.get_and_clear_pending_events();
8390         assert_eq!(events.len(), 1);
8391         match events[0] {
8392                 Event::PaymentClaimable { ref purpose, .. } => {
8393                         match &purpose {
8394                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8395                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8396                                 },
8397                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8398                         }
8399                 },
8400                 _ => panic!("Unexpected event"),
8401         }
8402 }
8403
8404 #[test]
8405 fn test_bad_secret_hash() {
8406         // Simple test of unregistered payment hash/invalid payment secret handling
8407         let chanmon_cfgs = create_chanmon_cfgs(2);
8408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8411
8412         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8413
8414         let random_payment_hash = PaymentHash([42; 32]);
8415         let random_payment_secret = PaymentSecret([43; 32]);
8416         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8417         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8418
8419         // All the below cases should end up being handled exactly identically, so we macro the
8420         // resulting events.
8421         macro_rules! handle_unknown_invalid_payment_data {
8422                 ($payment_hash: expr) => {
8423                         check_added_monitors!(nodes[0], 1);
8424                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8425                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8426                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8427                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8428
8429                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8430                         // again to process the pending backwards-failure of the HTLC
8431                         expect_pending_htlcs_forwardable!(nodes[1]);
8432                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8433                         check_added_monitors!(nodes[1], 1);
8434
8435                         // We should fail the payment back
8436                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8437                         match events.pop().unwrap() {
8438                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8439                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8440                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8441                                 },
8442                                 _ => panic!("Unexpected event"),
8443                         }
8444                 }
8445         }
8446
8447         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8448         // Error data is the HTLC value (100,000) and current block height
8449         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8450
8451         // Send a payment with the right payment hash but the wrong payment secret
8452         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8453                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8454         handle_unknown_invalid_payment_data!(our_payment_hash);
8455         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8456
8457         // Send a payment with a random payment hash, but the right payment secret
8458         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8459                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8460         handle_unknown_invalid_payment_data!(random_payment_hash);
8461         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8462
8463         // Send a payment with a random payment hash and random payment secret
8464         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8465                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8466         handle_unknown_invalid_payment_data!(random_payment_hash);
8467         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8468 }
8469
8470 #[test]
8471 fn test_update_err_monitor_lockdown() {
8472         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8473         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8474         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8475         // error.
8476         //
8477         // This scenario may happen in a watchtower setup, where watchtower process a block height
8478         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8479         // commitment at same time.
8480
8481         let chanmon_cfgs = create_chanmon_cfgs(2);
8482         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8483         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8484         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8485
8486         // Create some initial channel
8487         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8488         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8489
8490         // Rebalance the network to generate htlc in the two directions
8491         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8492
8493         // Route a HTLC from node 0 to node 1 (but don't settle)
8494         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8495
8496         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8497         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8498         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8499         let persister = test_utils::TestPersister::new();
8500         let watchtower = {
8501                 let new_monitor = {
8502                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8503                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8504                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8505                         assert!(new_monitor == *monitor);
8506                         new_monitor
8507                 };
8508                 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);
8509                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8510                 watchtower
8511         };
8512         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8513         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8514         // transaction lock time requirements here.
8515         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8516         watchtower.chain_monitor.block_connected(&block, 200);
8517
8518         // Try to update ChannelMonitor
8519         nodes[1].node.claim_funds(preimage);
8520         check_added_monitors!(nodes[1], 1);
8521         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8522
8523         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8524         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8525         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8526         {
8527                 let mut node_0_per_peer_lock;
8528                 let mut node_0_peer_state_lock;
8529                 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) {
8530                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8531                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8532                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8533                         } else { assert!(false); }
8534                 } else {
8535                         assert!(false);
8536                 }
8537         }
8538         // Our local monitor is in-sync and hasn't processed yet timeout
8539         check_added_monitors!(nodes[0], 1);
8540         let events = nodes[0].node.get_and_clear_pending_events();
8541         assert_eq!(events.len(), 1);
8542 }
8543
8544 #[test]
8545 fn test_concurrent_monitor_claim() {
8546         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8547         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8548         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8549         // state N+1 confirms. Alice claims output from state N+1.
8550
8551         let chanmon_cfgs = create_chanmon_cfgs(2);
8552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8554         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8555
8556         // Create some initial channel
8557         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8558         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8559
8560         // Rebalance the network to generate htlc in the two directions
8561         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8562
8563         // Route a HTLC from node 0 to node 1 (but don't settle)
8564         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8565
8566         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8567         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8568         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8569         let persister = test_utils::TestPersister::new();
8570         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8571                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8572         );
8573         let watchtower_alice = {
8574                 let new_monitor = {
8575                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8576                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8577                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8578                         assert!(new_monitor == *monitor);
8579                         new_monitor
8580                 };
8581                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8582                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8583                 watchtower
8584         };
8585         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8586         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8587         // requirements here.
8588         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8589         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8590         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8591
8592         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8593         {
8594                 let mut txn = alice_broadcaster.txn_broadcast();
8595                 assert_eq!(txn.len(), 2);
8596                 check_spends!(txn[0], chan_1.3);
8597                 check_spends!(txn[1], txn[0]);
8598         };
8599
8600         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8601         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8602         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8603         let persister = test_utils::TestPersister::new();
8604         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8605         let watchtower_bob = {
8606                 let new_monitor = {
8607                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8608                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8609                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8610                         assert!(new_monitor == *monitor);
8611                         new_monitor
8612                 };
8613                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8614                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8615                 watchtower
8616         };
8617         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8618
8619         // Route another payment to generate another update with still previous HTLC pending
8620         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8621         nodes[1].node.send_payment_with_route(&route, payment_hash,
8622                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8623         check_added_monitors!(nodes[1], 1);
8624
8625         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8626         assert_eq!(updates.update_add_htlcs.len(), 1);
8627         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8628         {
8629                 let mut node_0_per_peer_lock;
8630                 let mut node_0_peer_state_lock;
8631                 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) {
8632                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8633                                 // Watchtower Alice should already have seen the block and reject the update
8634                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8635                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8636                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8637                         } else { assert!(false); }
8638                 } else {
8639                         assert!(false);
8640                 }
8641         }
8642         // Our local monitor is in-sync and hasn't processed yet timeout
8643         check_added_monitors!(nodes[0], 1);
8644
8645         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8646         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8647
8648         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8649         let bob_state_y;
8650         {
8651                 let mut txn = bob_broadcaster.txn_broadcast();
8652                 assert_eq!(txn.len(), 2);
8653                 bob_state_y = txn.remove(0);
8654         };
8655
8656         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8657         let height = HTLC_TIMEOUT_BROADCAST + 1;
8658         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8659         check_closed_broadcast(&nodes[0], 1, true);
8660         check_closed_event!(&nodes[0], 1, ClosureReason::HTLCsTimedOut, false,
8661                 [nodes[1].node.get_our_node_id()], 100000);
8662         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8663         check_added_monitors(&nodes[0], 1);
8664         {
8665                 let htlc_txn = alice_broadcaster.txn_broadcast();
8666                 assert_eq!(htlc_txn.len(), 1);
8667                 check_spends!(htlc_txn[0], bob_state_y);
8668         }
8669 }
8670
8671 #[test]
8672 fn test_pre_lockin_no_chan_closed_update() {
8673         // Test that if a peer closes a channel in response to a funding_created message we don't
8674         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8675         // message).
8676         //
8677         // Doing so would imply a channel monitor update before the initial channel monitor
8678         // registration, violating our API guarantees.
8679         //
8680         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8681         // then opening a second channel with the same funding output as the first (which is not
8682         // rejected because the first channel does not exist in the ChannelManager) and closing it
8683         // before receiving funding_signed.
8684         let chanmon_cfgs = create_chanmon_cfgs(2);
8685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8687         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8688
8689         // Create an initial channel
8690         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8691         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8692         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8693         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8694         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8695
8696         // Move the first channel through the funding flow...
8697         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8698
8699         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8700         check_added_monitors!(nodes[0], 0);
8701
8702         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8703         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 });
8704         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8705         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8706         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8707                 [nodes[1].node.get_our_node_id()], 100000);
8708 }
8709
8710 #[test]
8711 fn test_htlc_no_detection() {
8712         // This test is a mutation to underscore the detection logic bug we had
8713         // before #653. HTLC value routed is above the remaining balance, thus
8714         // inverting HTLC and `to_remote` output. HTLC will come second and
8715         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8716         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8717         // outputs order detection for correct spending children filtring.
8718
8719         let chanmon_cfgs = create_chanmon_cfgs(2);
8720         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8721         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8722         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8723
8724         // Create some initial channels
8725         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8726
8727         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8728         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8729         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8730         assert_eq!(local_txn[0].input.len(), 1);
8731         assert_eq!(local_txn[0].output.len(), 3);
8732         check_spends!(local_txn[0], chan_1.3);
8733
8734         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8735         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8736         connect_block(&nodes[0], &block);
8737         // We deliberately connect the local tx twice as this should provoke a failure calling
8738         // this test before #653 fix.
8739         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8740         check_closed_broadcast!(nodes[0], true);
8741         check_added_monitors!(nodes[0], 1);
8742         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8743         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8744
8745         let htlc_timeout = {
8746                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8747                 assert_eq!(node_txn.len(), 1);
8748                 assert_eq!(node_txn[0].input.len(), 1);
8749                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8750                 check_spends!(node_txn[0], local_txn[0]);
8751                 node_txn[0].clone()
8752         };
8753
8754         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8755         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8756         expect_payment_failed!(nodes[0], our_payment_hash, false);
8757 }
8758
8759 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8760         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8761         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8762         // Carol, Alice would be the upstream node, and Carol the downstream.)
8763         //
8764         // Steps of the test:
8765         // 1) Alice sends a HTLC to Carol through Bob.
8766         // 2) Carol doesn't settle the HTLC.
8767         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8768         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8769         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8770         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8771         // 5) Carol release the preimage to Bob off-chain.
8772         // 6) Bob claims the offered output on the broadcasted commitment.
8773         let chanmon_cfgs = create_chanmon_cfgs(3);
8774         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8775         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8776         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8777
8778         // Create some initial channels
8779         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8780         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8781
8782         // Steps (1) and (2):
8783         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8784         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8785
8786         // Check that Alice's commitment transaction now contains an output for this HTLC.
8787         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8788         check_spends!(alice_txn[0], chan_ab.3);
8789         assert_eq!(alice_txn[0].output.len(), 2);
8790         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8791         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8792         assert_eq!(alice_txn.len(), 2);
8793
8794         // Steps (3) and (4):
8795         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8796         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8797         let mut force_closing_node = 0; // Alice force-closes
8798         let mut counterparty_node = 1; // Bob if Alice force-closes
8799
8800         // Bob force-closes
8801         if !broadcast_alice {
8802                 force_closing_node = 1;
8803                 counterparty_node = 0;
8804         }
8805         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8806         check_closed_broadcast!(nodes[force_closing_node], true);
8807         check_added_monitors!(nodes[force_closing_node], 1);
8808         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8809         if go_onchain_before_fulfill {
8810                 let txn_to_broadcast = match broadcast_alice {
8811                         true => alice_txn.clone(),
8812                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8813                 };
8814                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8815                 if broadcast_alice {
8816                         check_closed_broadcast!(nodes[1], true);
8817                         check_added_monitors!(nodes[1], 1);
8818                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8819                 }
8820         }
8821
8822         // Step (5):
8823         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8824         // process of removing the HTLC from their commitment transactions.
8825         nodes[2].node.claim_funds(payment_preimage);
8826         check_added_monitors!(nodes[2], 1);
8827         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8828
8829         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8830         assert!(carol_updates.update_add_htlcs.is_empty());
8831         assert!(carol_updates.update_fail_htlcs.is_empty());
8832         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8833         assert!(carol_updates.update_fee.is_none());
8834         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8835
8836         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8837         let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8838         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8839         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8840         if !go_onchain_before_fulfill && broadcast_alice {
8841                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8842                 assert_eq!(events.len(), 1);
8843                 match events[0] {
8844                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8845                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8846                         },
8847                         _ => panic!("Unexpected event"),
8848                 };
8849         }
8850         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8851         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8852         // Carol<->Bob's updated commitment transaction info.
8853         check_added_monitors!(nodes[1], 2);
8854
8855         let events = nodes[1].node.get_and_clear_pending_msg_events();
8856         assert_eq!(events.len(), 2);
8857         let bob_revocation = match events[0] {
8858                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8859                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8860                         (*msg).clone()
8861                 },
8862                 _ => panic!("Unexpected event"),
8863         };
8864         let bob_updates = match events[1] {
8865                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8866                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8867                         (*updates).clone()
8868                 },
8869                 _ => panic!("Unexpected event"),
8870         };
8871
8872         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8873         check_added_monitors!(nodes[2], 1);
8874         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8875         check_added_monitors!(nodes[2], 1);
8876
8877         let events = nodes[2].node.get_and_clear_pending_msg_events();
8878         assert_eq!(events.len(), 1);
8879         let carol_revocation = match events[0] {
8880                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8881                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8882                         (*msg).clone()
8883                 },
8884                 _ => panic!("Unexpected event"),
8885         };
8886         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8887         check_added_monitors!(nodes[1], 1);
8888
8889         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8890         // here's where we put said channel's commitment tx on-chain.
8891         let mut txn_to_broadcast = alice_txn.clone();
8892         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8893         if !go_onchain_before_fulfill {
8894                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8895                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8896                 if broadcast_alice {
8897                         check_closed_broadcast!(nodes[1], true);
8898                         check_added_monitors!(nodes[1], 1);
8899                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8900                 }
8901                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8902                 if broadcast_alice {
8903                         assert_eq!(bob_txn.len(), 1);
8904                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8905                 } else {
8906                         if nodes[1].connect_style.borrow().updates_best_block_first() {
8907                                 assert_eq!(bob_txn.len(), 3);
8908                                 assert_eq!(bob_txn[0].txid(), bob_txn[1].txid());
8909                         } else {
8910                                 assert_eq!(bob_txn.len(), 2);
8911                         }
8912                         check_spends!(bob_txn[0], chan_ab.3);
8913                 }
8914         }
8915
8916         // Step (6):
8917         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8918         // broadcasted commitment transaction.
8919         {
8920                 let script_weight = match broadcast_alice {
8921                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8922                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8923                 };
8924                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8925                 // Bob force-closed and broadcasts the commitment transaction along with a
8926                 // HTLC-output-claiming transaction.
8927                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8928                 if broadcast_alice {
8929                         assert_eq!(bob_txn.len(), 1);
8930                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8931                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8932                 } else {
8933                         assert_eq!(bob_txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
8934                         let htlc_tx = bob_txn.pop().unwrap();
8935                         check_spends!(htlc_tx, txn_to_broadcast[0]);
8936                         assert_eq!(htlc_tx.input[0].witness.last().unwrap().len(), script_weight);
8937                 }
8938         }
8939 }
8940
8941 #[test]
8942 fn test_onchain_htlc_settlement_after_close() {
8943         do_test_onchain_htlc_settlement_after_close(true, true);
8944         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8945         do_test_onchain_htlc_settlement_after_close(true, false);
8946         do_test_onchain_htlc_settlement_after_close(false, false);
8947 }
8948
8949 #[test]
8950 fn test_duplicate_temporary_channel_id_from_different_peers() {
8951         // Tests that we can accept two different `OpenChannel` requests with the same
8952         // `temporary_channel_id`, as long as they are from different peers.
8953         let chanmon_cfgs = create_chanmon_cfgs(3);
8954         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8955         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8956         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8957
8958         // Create an first channel channel
8959         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8960         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8961
8962         // Create an second channel
8963         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8964         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8965
8966         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8967         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8968         open_chan_msg_chan_2_0.common_fields.temporary_channel_id = open_chan_msg_chan_1_0.common_fields.temporary_channel_id;
8969
8970         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8971         // `temporary_channel_id` as they are from different peers.
8972         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8973         {
8974                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8975                 assert_eq!(events.len(), 1);
8976                 match &events[0] {
8977                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8978                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8979                                 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
8980                         },
8981                         _ => panic!("Unexpected event"),
8982                 }
8983         }
8984
8985         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8986         {
8987                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8988                 assert_eq!(events.len(), 1);
8989                 match &events[0] {
8990                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8991                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8992                                 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
8993                         },
8994                         _ => panic!("Unexpected event"),
8995                 }
8996         }
8997 }
8998
8999 #[test]
9000 fn test_peer_funding_sidechannel() {
9001         // Test that if a peer somehow learns which txid we'll use for our channel funding before we
9002         // receive `funding_transaction_generated` the peer cannot cause us to crash. We'd previously
9003         // assumed that LDK would receive `funding_transaction_generated` prior to our peer learning
9004         // the txid and panicked if the peer tried to open a redundant channel to us with the same
9005         // funding outpoint.
9006         //
9007         // While this assumption is generally safe, some users may have out-of-band protocols where
9008         // they notify their LSP about a funding outpoint first, or this may be violated in the future
9009         // with collaborative transaction construction protocols, i.e. dual-funding.
9010         let chanmon_cfgs = create_chanmon_cfgs(3);
9011         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9012         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9013         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9014
9015         let temp_chan_id_ab = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9016         let temp_chan_id_ca = exchange_open_accept_chan(&nodes[2], &nodes[0], 1_000_000, 0);
9017
9018         let (_, tx, funding_output) =
9019                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9020
9021         let cs_funding_events = nodes[2].node.get_and_clear_pending_events();
9022         assert_eq!(cs_funding_events.len(), 1);
9023         match cs_funding_events[0] {
9024                 Event::FundingGenerationReady { .. } => {}
9025                 _ => panic!("Unexpected event {:?}", cs_funding_events),
9026         }
9027
9028         nodes[2].node.funding_transaction_generated_unchecked(&temp_chan_id_ca, &nodes[0].node.get_our_node_id(), tx.clone(), funding_output.index).unwrap();
9029         let funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[0].node.get_our_node_id());
9030         nodes[0].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9031         get_event_msg!(nodes[0], MessageSendEvent::SendFundingSigned, nodes[2].node.get_our_node_id());
9032         expect_channel_pending_event(&nodes[0], &nodes[2].node.get_our_node_id());
9033         check_added_monitors!(nodes[0], 1);
9034
9035         let res = nodes[0].node.funding_transaction_generated(&temp_chan_id_ab, &nodes[1].node.get_our_node_id(), tx.clone());
9036         let err_msg = format!("{:?}", res.unwrap_err());
9037         assert!(err_msg.contains("An existing channel using outpoint "));
9038         assert!(err_msg.contains(" is open with peer"));
9039         // Even though the last funding_transaction_generated errored, it still generated a
9040         // SendFundingCreated. However, when the peer responds with a funding_signed it will send the
9041         // appropriate error message.
9042         let as_funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9043         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &as_funding_created);
9044         check_added_monitors!(nodes[1], 1);
9045         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9046         let reason = ClosureReason::ProcessingError { err: format!("An existing channel using outpoint {} is open with peer {}", funding_output, nodes[2].node.get_our_node_id()), };
9047         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(ChannelId::v1_from_funding_outpoint(funding_output), true, reason)]);
9048
9049         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9050         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9051         get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9052 }
9053
9054 #[test]
9055 fn test_duplicate_conflicting_funding_from_second_peer() {
9056         // Test that if a user tries to fund a channel with a funding outpoint they'd previously used
9057         // we don't try to remove the previous ChannelMonitor. This is largely a test to ensure we
9058         // don't regress in the fuzzer, as such funding getting passed our outpoint-matches checks
9059         // implies the user (and our counterparty) has reused cryptographic keys across channels, which
9060         // we require the user not do.
9061         let chanmon_cfgs = create_chanmon_cfgs(4);
9062         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9063         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9064         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9065
9066         let temp_chan_id = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9067
9068         let (_, tx, funding_output) =
9069                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9070
9071         // Now that we have a funding outpoint, create a dummy `ChannelMonitor` and insert it into
9072         // nodes[0]'s ChainMonitor so that the initial `ChannelMonitor` write fails.
9073         let dummy_chan_id = create_chan_between_nodes(&nodes[2], &nodes[3]).3;
9074         let dummy_monitor = get_monitor!(nodes[2], dummy_chan_id).clone();
9075         nodes[0].chain_monitor.chain_monitor.watch_channel(funding_output, dummy_monitor).unwrap();
9076
9077         nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9078
9079         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9080         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9081         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9082         check_added_monitors!(nodes[1], 1);
9083         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9084
9085         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9086         // At this point, the channel should be closed, after having generated one monitor write (the
9087         // watch_channel call which failed), but zero monitor updates.
9088         check_added_monitors!(nodes[0], 1);
9089         get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9090         let err_reason = ClosureReason::ProcessingError { err: "Channel funding outpoint was a duplicate".to_owned() };
9091         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(funding_signed_msg.channel_id, true, err_reason)]);
9092 }
9093
9094 #[test]
9095 fn test_duplicate_funding_err_in_funding() {
9096         // Test that if we have a live channel with one peer, then another peer comes along and tries
9097         // to create a second channel with the same txid we'll fail and not overwrite the
9098         // outpoint_to_peer map in `ChannelManager`.
9099         //
9100         // This was previously broken.
9101         let chanmon_cfgs = create_chanmon_cfgs(3);
9102         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9103         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9104         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9105
9106         let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
9107         let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
9108         assert_eq!(ChannelId::v1_from_funding_outpoint(real_chan_funding_txo), real_channel_id);
9109
9110         nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9111         let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9112         let node_c_temp_chan_id = open_chan_msg.common_fields.temporary_channel_id;
9113         open_chan_msg.common_fields.temporary_channel_id = real_channel_id;
9114         nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
9115         let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
9116         accept_chan_msg.common_fields.temporary_channel_id = node_c_temp_chan_id;
9117         nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
9118
9119         // Now that we have a second channel with the same funding txo, send a bogus funding message
9120         // and let nodes[1] remove the inbound channel.
9121         let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9122
9123         nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9124
9125         let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9126         funding_created_msg.temporary_channel_id = real_channel_id;
9127         // Make the signature invalid by changing the funding output
9128         funding_created_msg.funding_output_index += 10;
9129         nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9130         get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9131         let err = "Invalid funding_created signature from peer".to_owned();
9132         let reason = ClosureReason::ProcessingError { err };
9133         let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9134         check_closed_events(&nodes[1], &[expected_closing]);
9135
9136         assert_eq!(
9137                 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9138                 nodes[0].node.get_our_node_id()
9139         );
9140 }
9141
9142 #[test]
9143 fn test_duplicate_chan_id() {
9144         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9145         // already open we reject it and keep the old channel.
9146         //
9147         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9148         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9149         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9150         // updating logic for the existing channel.
9151         let chanmon_cfgs = create_chanmon_cfgs(2);
9152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9155
9156         // Create an initial channel
9157         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9158         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9159         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9160         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()));
9161
9162         // Try to create a second channel with the same temporary_channel_id as the first and check
9163         // that it is rejected.
9164         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9165         {
9166                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9167                 assert_eq!(events.len(), 1);
9168                 match events[0] {
9169                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9170                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9171                                 // first (valid) and second (invalid) channels are closed, given they both have
9172                                 // the same non-temporary channel_id. However, currently we do not, so we just
9173                                 // move forward with it.
9174                                 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9175                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9176                         },
9177                         _ => panic!("Unexpected event"),
9178                 }
9179         }
9180
9181         // Move the first channel through the funding flow...
9182         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9183
9184         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9185         check_added_monitors!(nodes[0], 0);
9186
9187         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9188         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9189         {
9190                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9191                 assert_eq!(added_monitors.len(), 1);
9192                 assert_eq!(added_monitors[0].0, funding_output);
9193                 added_monitors.clear();
9194         }
9195         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9196
9197         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9198
9199         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9200         let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
9201
9202         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9203         // temporary one).
9204
9205         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9206         // Technically this is allowed by the spec, but we don't support it and there's little reason
9207         // to. Still, it shouldn't cause any other issues.
9208         open_chan_msg.common_fields.temporary_channel_id = channel_id;
9209         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9210         {
9211                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9212                 assert_eq!(events.len(), 1);
9213                 match events[0] {
9214                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9215                                 // Technically, at this point, nodes[1] would be justified in thinking both
9216                                 // channels are closed, but currently we do not, so we just move forward with it.
9217                                 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9218                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9219                         },
9220                         _ => panic!("Unexpected event"),
9221                 }
9222         }
9223
9224         // Now try to create a second channel which has a duplicate funding output.
9225         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9226         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9227         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9228         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()));
9229         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9230
9231         let funding_created = {
9232                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9233                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9234                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9235                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9236                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9237                 // channelmanager in a possibly nonsense state instead).
9238                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.common_fields.temporary_channel_id).unwrap() {
9239                         ChannelPhase::UnfundedOutboundV1(mut chan) => {
9240                                 let logger = test_utils::TestLogger::new();
9241                                 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9242                         },
9243                         _ => panic!("Unexpected ChannelPhase variant"),
9244                 }.unwrap()
9245         };
9246         check_added_monitors!(nodes[0], 0);
9247         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9248         // At this point we'll look up if the channel_id is present and immediately fail the channel
9249         // without trying to persist the `ChannelMonitor`.
9250         check_added_monitors!(nodes[1], 0);
9251
9252         check_closed_events(&nodes[1], &[
9253                 ExpectedCloseEvent::from_id_reason(funding_created.temporary_channel_id, false, ClosureReason::ProcessingError {
9254                         err: "Already had channel with the new channel_id".to_owned()
9255                 })
9256         ]);
9257
9258         // ...still, nodes[1] will reject the duplicate channel.
9259         {
9260                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9261                 assert_eq!(events.len(), 1);
9262                 match events[0] {
9263                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9264                                 // Technically, at this point, nodes[1] would be justified in thinking both
9265                                 // channels are closed, but currently we do not, so we just move forward with it.
9266                                 assert_eq!(msg.channel_id, channel_id);
9267                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9268                         },
9269                         _ => panic!("Unexpected event"),
9270                 }
9271         }
9272
9273         // finally, finish creating the original channel and send a payment over it to make sure
9274         // everything is functional.
9275         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9276         {
9277                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9278                 assert_eq!(added_monitors.len(), 1);
9279                 assert_eq!(added_monitors[0].0, funding_output);
9280                 added_monitors.clear();
9281         }
9282         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9283
9284         let events_4 = nodes[0].node.get_and_clear_pending_events();
9285         assert_eq!(events_4.len(), 0);
9286         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9287         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9288
9289         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9290         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9291         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9292
9293         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9294 }
9295
9296 #[test]
9297 fn test_error_chans_closed() {
9298         // Test that we properly handle error messages, closing appropriate channels.
9299         //
9300         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9301         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9302         // we can test various edge cases around it to ensure we don't regress.
9303         let chanmon_cfgs = create_chanmon_cfgs(3);
9304         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9305         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9306         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9307
9308         // Create some initial channels
9309         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9310         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9311         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9312
9313         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9314         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9315         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9316
9317         // Closing a channel from a different peer has no effect
9318         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9319         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9320
9321         // Closing one channel doesn't impact others
9322         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9323         check_added_monitors!(nodes[0], 1);
9324         check_closed_broadcast!(nodes[0], false);
9325         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9326                 [nodes[1].node.get_our_node_id()], 100000);
9327         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9328         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9329         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);
9330         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);
9331
9332         // A null channel ID should close all channels
9333         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9334         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9335         check_added_monitors!(nodes[0], 2);
9336         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9337                 [nodes[1].node.get_our_node_id(); 2], 100000);
9338         let events = nodes[0].node.get_and_clear_pending_msg_events();
9339         assert_eq!(events.len(), 2);
9340         match events[0] {
9341                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9342                         assert_eq!(msg.contents.flags & 2, 2);
9343                 },
9344                 _ => panic!("Unexpected event"),
9345         }
9346         match events[1] {
9347                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9348                         assert_eq!(msg.contents.flags & 2, 2);
9349                 },
9350                 _ => panic!("Unexpected event"),
9351         }
9352         // Note that at this point users of a standard PeerHandler will end up calling
9353         // peer_disconnected.
9354         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9355         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9356
9357         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9358         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9359         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9360 }
9361
9362 #[test]
9363 fn test_invalid_funding_tx() {
9364         // Test that we properly handle invalid funding transactions sent to us from a peer.
9365         //
9366         // Previously, all other major lightning implementations had failed to properly sanitize
9367         // funding transactions from their counterparties, leading to a multi-implementation critical
9368         // security vulnerability (though we always sanitized properly, we've previously had
9369         // un-released crashes in the sanitization process).
9370         //
9371         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9372         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9373         // gave up on it. We test this here by generating such a transaction.
9374         let chanmon_cfgs = create_chanmon_cfgs(2);
9375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9377         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9378
9379         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9380         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()));
9381         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()));
9382
9383         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9384
9385         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9386         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9387         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9388         // its length.
9389         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9390         let wit_program_script: ScriptBuf = wit_program.into();
9391         for output in tx.output.iter_mut() {
9392                 // Make the confirmed funding transaction have a bogus script_pubkey
9393                 output.script_pubkey = ScriptBuf::new_v0_p2wsh(&wit_program_script.wscript_hash());
9394         }
9395
9396         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9397         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()));
9398         check_added_monitors!(nodes[1], 1);
9399         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9400
9401         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()));
9402         check_added_monitors!(nodes[0], 1);
9403         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9404
9405         let events_1 = nodes[0].node.get_and_clear_pending_events();
9406         assert_eq!(events_1.len(), 0);
9407
9408         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9409         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9410         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9411
9412         let expected_err = "funding tx had wrong script/value or output index";
9413         confirm_transaction_at(&nodes[1], &tx, 1);
9414         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9415                 [nodes[0].node.get_our_node_id()], 100000);
9416         check_added_monitors!(nodes[1], 1);
9417         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9418         assert_eq!(events_2.len(), 1);
9419         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9420                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9421                 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9422                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9423                 } else { panic!(); }
9424         } else { panic!(); }
9425         assert_eq!(nodes[1].node.list_channels().len(), 0);
9426
9427         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9428         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9429         // as its not 32 bytes long.
9430         let mut spend_tx = Transaction {
9431                 version: 2i32, lock_time: LockTime::ZERO,
9432                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9433                         previous_output: BitcoinOutPoint {
9434                                 txid: tx.txid(),
9435                                 vout: idx as u32,
9436                         },
9437                         script_sig: ScriptBuf::new(),
9438                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9439                         witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9440                 }).collect(),
9441                 output: vec![TxOut {
9442                         value: 1000,
9443                         script_pubkey: ScriptBuf::new(),
9444                 }]
9445         };
9446         check_spends!(spend_tx, tx);
9447         mine_transaction(&nodes[1], &spend_tx);
9448 }
9449
9450 #[test]
9451 fn test_coinbase_funding_tx() {
9452         // Miners are able to fund channels directly from coinbase transactions, however
9453         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9454         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9455         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9456         //
9457         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9458         // immediately operational after opening.
9459         let chanmon_cfgs = create_chanmon_cfgs(2);
9460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9463
9464         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9465         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9466
9467         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9468         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9469
9470         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9471
9472         // Create the coinbase funding transaction.
9473         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9474
9475         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9476         check_added_monitors!(nodes[0], 0);
9477         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9478
9479         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9480         check_added_monitors!(nodes[1], 1);
9481         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9482
9483         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9484
9485         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9486         check_added_monitors!(nodes[0], 1);
9487
9488         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9489         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9490
9491         // Starting at height 0, we "confirm" the coinbase at height 1.
9492         confirm_transaction_at(&nodes[0], &tx, 1);
9493         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9494         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9495         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9496         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9497         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9498         connect_blocks(&nodes[0], 1);
9499         // There should now be a `channel_ready` which can be handled.
9500         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()));
9501
9502         confirm_transaction_at(&nodes[1], &tx, 1);
9503         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9504         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9505         connect_blocks(&nodes[1], 1);
9506         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9507         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9508 }
9509
9510 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9511         // In the first version of the chain::Confirm interface, after a refactor was made to not
9512         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9513         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9514         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9515         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9516         // spending transaction until height N+1 (or greater). This was due to the way
9517         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9518         // spending transaction at the height the input transaction was confirmed at, not whether we
9519         // should broadcast a spending transaction at the current height.
9520         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9521         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9522         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9523         // until we learned about an additional block.
9524         //
9525         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9526         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9527         let chanmon_cfgs = create_chanmon_cfgs(3);
9528         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9529         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9530         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9531         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9532
9533         create_announced_chan_between_nodes(&nodes, 0, 1);
9534         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9535         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9536         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9537         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9538
9539         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9540         check_closed_broadcast!(nodes[1], true);
9541         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9542         check_added_monitors!(nodes[1], 1);
9543         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9544         assert_eq!(node_txn.len(), 1);
9545
9546         let conf_height = nodes[1].best_block_info().1;
9547         if !test_height_before_timelock {
9548                 connect_blocks(&nodes[1], 24 * 6);
9549         }
9550         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9551                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9552         if test_height_before_timelock {
9553                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9554                 // generate any events or broadcast any transactions
9555                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9556                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9557         } else {
9558                 // We should broadcast an HTLC transaction spending our funding transaction first
9559                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9560                 assert_eq!(spending_txn.len(), 2);
9561                 let htlc_tx = if spending_txn[0].txid() == node_txn[0].txid() {
9562                         &spending_txn[1]
9563                 } else {
9564                         &spending_txn[0]
9565                 };
9566                 check_spends!(htlc_tx, node_txn[0]);
9567                 // We should also generate a SpendableOutputs event with the to_self output (as its
9568                 // timelock is up).
9569                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9570                 assert_eq!(descriptor_spend_txn.len(), 1);
9571
9572                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9573                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9574                 // additional block built on top of the current chain.
9575                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9576                         &nodes[1].get_block_header(conf_height + 1), &[(0, htlc_tx)], conf_height + 1);
9577                 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 }]);
9578                 check_added_monitors!(nodes[1], 1);
9579
9580                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9581                 assert!(updates.update_add_htlcs.is_empty());
9582                 assert!(updates.update_fulfill_htlcs.is_empty());
9583                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9584                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9585                 assert!(updates.update_fee.is_none());
9586                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9587                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9588                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9589         }
9590 }
9591
9592 #[test]
9593 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9594         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9595         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9596 }
9597
9598 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9599         let chanmon_cfgs = create_chanmon_cfgs(2);
9600         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9602         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9603
9604         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9605
9606         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9607                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9608         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9609
9610         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9611
9612         {
9613                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9614                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9615                 check_added_monitors!(nodes[0], 1);
9616                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9617                 assert_eq!(events.len(), 1);
9618                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9619                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9620                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9621         }
9622         expect_pending_htlcs_forwardable!(nodes[1]);
9623         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9624
9625         {
9626                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9627                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9628                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9629                 check_added_monitors!(nodes[0], 1);
9630                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9631                 assert_eq!(events.len(), 1);
9632                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9633                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9634                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9635                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9636                 // assume the second is a privacy attack (no longer particularly relevant
9637                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9638                 // the first HTLC delivered above.
9639         }
9640
9641         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9642         nodes[1].node.process_pending_htlc_forwards();
9643
9644         if test_for_second_fail_panic {
9645                 // Now we go fail back the first HTLC from the user end.
9646                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9647
9648                 let expected_destinations = vec![
9649                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9650                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9651                 ];
9652                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9653                 nodes[1].node.process_pending_htlc_forwards();
9654
9655                 check_added_monitors!(nodes[1], 1);
9656                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9657                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9658
9659                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9660                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9661                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9662
9663                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9664                 assert_eq!(failure_events.len(), 4);
9665                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9666                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9667                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9668                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9669         } else {
9670                 // Let the second HTLC fail and claim the first
9671                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9672                 nodes[1].node.process_pending_htlc_forwards();
9673
9674                 check_added_monitors!(nodes[1], 1);
9675                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9676                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9677                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9678
9679                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9680
9681                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9682         }
9683 }
9684
9685 #[test]
9686 fn test_dup_htlc_second_fail_panic() {
9687         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9688         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9689         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9690         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9691         do_test_dup_htlc_second_rejected(true);
9692 }
9693
9694 #[test]
9695 fn test_dup_htlc_second_rejected() {
9696         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9697         // simply reject the second HTLC but are still able to claim the first HTLC.
9698         do_test_dup_htlc_second_rejected(false);
9699 }
9700
9701 #[test]
9702 fn test_inconsistent_mpp_params() {
9703         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9704         // such HTLC and allow the second to stay.
9705         let chanmon_cfgs = create_chanmon_cfgs(4);
9706         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9707         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9708         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9709
9710         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9711         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9712         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9713         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9714
9715         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9716                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9717         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9718         assert_eq!(route.paths.len(), 2);
9719         route.paths.sort_by(|path_a, _| {
9720                 // Sort the path so that the path through nodes[1] comes first
9721                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9722                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9723         });
9724
9725         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9726
9727         let cur_height = nodes[0].best_block_info().1;
9728         let payment_id = PaymentId([42; 32]);
9729
9730         let session_privs = {
9731                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9732                 // ultimately have, just not right away.
9733                 let mut dup_route = route.clone();
9734                 dup_route.paths.push(route.paths[1].clone());
9735                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9736                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9737         };
9738         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9739                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9740                 &None, session_privs[0]).unwrap();
9741         check_added_monitors!(nodes[0], 1);
9742
9743         {
9744                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9745                 assert_eq!(events.len(), 1);
9746                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9747         }
9748         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9749
9750         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9751                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9752         check_added_monitors!(nodes[0], 1);
9753
9754         {
9755                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9756                 assert_eq!(events.len(), 1);
9757                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9758
9759                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9760                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9761
9762                 expect_pending_htlcs_forwardable!(nodes[2]);
9763                 check_added_monitors!(nodes[2], 1);
9764
9765                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9766                 assert_eq!(events.len(), 1);
9767                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9768
9769                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9770                 check_added_monitors!(nodes[3], 0);
9771                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9772
9773                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9774                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9775                 // post-payment_secrets) and fail back the new HTLC.
9776         }
9777         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9778         nodes[3].node.process_pending_htlc_forwards();
9779         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9780         nodes[3].node.process_pending_htlc_forwards();
9781
9782         check_added_monitors!(nodes[3], 1);
9783
9784         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9785         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9786         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9787
9788         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 }]);
9789         check_added_monitors!(nodes[2], 1);
9790
9791         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9792         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9793         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9794
9795         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9796
9797         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9798                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9799                 &None, session_privs[2]).unwrap();
9800         check_added_monitors!(nodes[0], 1);
9801
9802         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9803         assert_eq!(events.len(), 1);
9804         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9805
9806         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9807         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9808 }
9809
9810 #[test]
9811 fn test_double_partial_claim() {
9812         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9813         // time out, the sender resends only some of the MPP parts, then the user processes the
9814         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9815         // amount.
9816         let chanmon_cfgs = create_chanmon_cfgs(4);
9817         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9818         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9819         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9820
9821         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9822         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9823         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9824         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9825
9826         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9827         assert_eq!(route.paths.len(), 2);
9828         route.paths.sort_by(|path_a, _| {
9829                 // Sort the path so that the path through nodes[1] comes first
9830                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9831                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9832         });
9833
9834         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9835         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9836         // amount of time to respond to.
9837
9838         // Connect some blocks to time out the payment
9839         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9840         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9841
9842         let failed_destinations = vec![
9843                 HTLCDestination::FailedPayment { payment_hash },
9844                 HTLCDestination::FailedPayment { payment_hash },
9845         ];
9846         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9847
9848         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9849
9850         // nodes[1] now retries one of the two paths...
9851         nodes[0].node.send_payment_with_route(&route, payment_hash,
9852                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9853         check_added_monitors!(nodes[0], 2);
9854
9855         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9856         assert_eq!(events.len(), 2);
9857         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9858         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9859
9860         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9861         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9862         nodes[3].node.claim_funds(payment_preimage);
9863         check_added_monitors!(nodes[3], 0);
9864         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9865 }
9866
9867 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9868 #[derive(Clone, Copy, PartialEq)]
9869 enum ExposureEvent {
9870         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9871         AtHTLCForward,
9872         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9873         AtHTLCReception,
9874         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9875         AtUpdateFeeOutbound,
9876 }
9877
9878 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9879         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9880         // policy.
9881         //
9882         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9883         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9884         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9885         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9886         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9887         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9888         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9889         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9890
9891         let chanmon_cfgs = create_chanmon_cfgs(2);
9892         let mut config = test_default_channel_config();
9893         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9894                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9895                 // to get roughly the same initial value as the default setting when this test was
9896                 // originally written.
9897                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9898         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9901         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9902
9903         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9904         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9905         open_channel.common_fields.max_htlc_value_in_flight_msat = 50_000_000;
9906         open_channel.common_fields.max_accepted_htlcs = 60;
9907         if on_holder_tx {
9908                 open_channel.common_fields.dust_limit_satoshis = 546;
9909         }
9910         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9911         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9912         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9913
9914         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9915
9916         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9917
9918         if on_holder_tx {
9919                 let mut node_0_per_peer_lock;
9920                 let mut node_0_peer_state_lock;
9921                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9922                         ChannelPhase::UnfundedOutboundV1(chan) => {
9923                                 chan.context.holder_dust_limit_satoshis = 546;
9924                         },
9925                         _ => panic!("Unexpected ChannelPhase variant"),
9926                 }
9927         }
9928
9929         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9930         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()));
9931         check_added_monitors!(nodes[1], 1);
9932         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9933
9934         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()));
9935         check_added_monitors!(nodes[0], 1);
9936         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9937
9938         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9939         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9940         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9941
9942         // Fetch a route in advance as we will be unable to once we're unable to send.
9943         let (mut route, payment_hash, _, payment_secret) =
9944                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9945
9946         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9947                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9948                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9949                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9950                 (chan.context().get_dust_buffer_feerate(None) as u64,
9951                 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9952         };
9953         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;
9954         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9955
9956         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 - 1) * 1000;
9957         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9958
9959         let dust_htlc_on_counterparty_tx: u64 = 4;
9960         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9961
9962         if on_holder_tx {
9963                 if dust_outbound_balance {
9964                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9965                         // Outbound dust balance: 4372 sats
9966                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9967                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9968                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9969                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9970                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9971                         }
9972                 } else {
9973                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9974                         // Inbound dust balance: 4372 sats
9975                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9976                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9977                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9978                         }
9979                 }
9980         } else {
9981                 if dust_outbound_balance {
9982                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9983                         // Outbound dust balance: 5000 sats
9984                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9985                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9986                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9987                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9988                         }
9989                 } else {
9990                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9991                         // Inbound dust balance: 5000 sats
9992                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9993                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9994                         }
9995                 }
9996         }
9997
9998         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9999                 route.paths[0].hops.last_mut().unwrap().fee_msat =
10000                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
10001                 // With default dust exposure: 5000 sats
10002                 if on_holder_tx {
10003                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10004                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10005                                 ), true, APIError::ChannelUnavailable { .. }, {});
10006                 } else {
10007                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10008                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10009                                 ), true, APIError::ChannelUnavailable { .. }, {});
10010                 }
10011         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10012                 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 });
10013                 nodes[1].node.send_payment_with_route(&route, payment_hash,
10014                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10015                 check_added_monitors!(nodes[1], 1);
10016                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10017                 assert_eq!(events.len(), 1);
10018                 let payment_event = SendEvent::from_event(events.remove(0));
10019                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10020                 // With default dust exposure: 5000 sats
10021                 if on_holder_tx {
10022                         // Outbound dust balance: 6399 sats
10023                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10024                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10025                         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);
10026                 } else {
10027                         // Outbound dust balance: 5200 sats
10028                         nodes[0].logger.assert_log("lightning::ln::channel",
10029                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
10030                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
10031                                         max_dust_htlc_exposure_msat), 1);
10032                 }
10033         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10034                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
10035                 // For the multiplier dust exposure limit, since it scales with feerate,
10036                 // we need to add a lot of HTLCs that will become dust at the new feerate
10037                 // to cross the threshold.
10038                 for _ in 0..20 {
10039                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
10040                         nodes[0].node.send_payment_with_route(&route, payment_hash,
10041                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10042                 }
10043                 {
10044                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10045                         *feerate_lock = *feerate_lock * 10;
10046                 }
10047                 nodes[0].node.timer_tick_occurred();
10048                 check_added_monitors!(nodes[0], 1);
10049                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
10050         }
10051
10052         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10053         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10054         added_monitors.clear();
10055 }
10056
10057 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
10058         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10059         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10060         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10061         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10062         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10063         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10064         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10065         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10066         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10067         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10068         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10069         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10070 }
10071
10072 #[test]
10073 fn test_max_dust_htlc_exposure() {
10074         do_test_max_dust_htlc_exposure_by_threshold_type(false);
10075         do_test_max_dust_htlc_exposure_by_threshold_type(true);
10076 }
10077
10078 #[test]
10079 fn test_non_final_funding_tx() {
10080         let chanmon_cfgs = create_chanmon_cfgs(2);
10081         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10082         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10083         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10084
10085         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10086         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10087         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10088         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10089         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10090
10091         let best_height = nodes[0].node.best_block.read().unwrap().height;
10092
10093         let chan_id = *nodes[0].network_chan_count.borrow();
10094         let events = nodes[0].node.get_and_clear_pending_events();
10095         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
10096         assert_eq!(events.len(), 1);
10097         let mut tx = match events[0] {
10098                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10099                         // Timelock the transaction _beyond_ the best client height + 1.
10100                         Transaction { version: chan_id as i32, lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
10101                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10102                         }]}
10103                 },
10104                 _ => panic!("Unexpected event"),
10105         };
10106         // Transaction should fail as it's evaluated as non-final for propagation.
10107         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10108                 Err(APIError::APIMisuseError { err }) => {
10109                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10110                 },
10111                 _ => panic!()
10112         }
10113         let events = nodes[0].node.get_and_clear_pending_events();
10114         assert_eq!(events.len(), 1);
10115         match events[0] {
10116                 Event::ChannelClosed { channel_id, .. } => {
10117                         assert_eq!(channel_id, temp_channel_id);
10118                 },
10119                 _ => panic!("Unexpected event"),
10120         }
10121 }
10122
10123 #[test]
10124 fn test_non_final_funding_tx_within_headroom() {
10125         let chanmon_cfgs = create_chanmon_cfgs(2);
10126         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10128         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10129
10130         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10131         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10132         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10133         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10134         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10135
10136         let best_height = nodes[0].node.best_block.read().unwrap().height;
10137
10138         let chan_id = *nodes[0].network_chan_count.borrow();
10139         let events = nodes[0].node.get_and_clear_pending_events();
10140         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10141         assert_eq!(events.len(), 1);
10142         let mut tx = match events[0] {
10143                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10144                         // Timelock the transaction within a +1 headroom from the best block.
10145                         Transaction { version: chan_id as i32, lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10146                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10147                         }]}
10148                 },
10149                 _ => panic!("Unexpected event"),
10150         };
10151
10152         // Transaction should be accepted if it's in a +1 headroom from best block.
10153         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10154         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10155 }
10156
10157 #[test]
10158 fn accept_busted_but_better_fee() {
10159         // If a peer sends us a fee update that is too low, but higher than our previous channel
10160         // feerate, we should accept it. In the future we may want to consider closing the channel
10161         // later, but for now we only accept the update.
10162         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10165         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10166
10167         create_chan_between_nodes(&nodes[0], &nodes[1]);
10168
10169         // Set nodes[1] to expect 5,000 sat/kW.
10170         {
10171                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10172                 *feerate_lock = 5000;
10173         }
10174
10175         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10176         {
10177                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10178                 *feerate_lock = 1000;
10179         }
10180         nodes[0].node.timer_tick_occurred();
10181         check_added_monitors!(nodes[0], 1);
10182
10183         let events = nodes[0].node.get_and_clear_pending_msg_events();
10184         assert_eq!(events.len(), 1);
10185         match events[0] {
10186                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10187                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10188                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10189                 },
10190                 _ => panic!("Unexpected event"),
10191         };
10192
10193         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10194         // it.
10195         {
10196                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10197                 *feerate_lock = 2000;
10198         }
10199         nodes[0].node.timer_tick_occurred();
10200         check_added_monitors!(nodes[0], 1);
10201
10202         let events = nodes[0].node.get_and_clear_pending_msg_events();
10203         assert_eq!(events.len(), 1);
10204         match events[0] {
10205                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10206                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10207                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10208                 },
10209                 _ => panic!("Unexpected event"),
10210         };
10211
10212         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10213         // channel.
10214         {
10215                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10216                 *feerate_lock = 1000;
10217         }
10218         nodes[0].node.timer_tick_occurred();
10219         check_added_monitors!(nodes[0], 1);
10220
10221         let events = nodes[0].node.get_and_clear_pending_msg_events();
10222         assert_eq!(events.len(), 1);
10223         match events[0] {
10224                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10225                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10226                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10227                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10228                                 [nodes[0].node.get_our_node_id()], 100000);
10229                         check_closed_broadcast!(nodes[1], true);
10230                         check_added_monitors!(nodes[1], 1);
10231                 },
10232                 _ => panic!("Unexpected event"),
10233         };
10234 }
10235
10236 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10237         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10238         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10239         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10240         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10241         let min_final_cltv_expiry_delta = 120;
10242         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10243                 min_final_cltv_expiry_delta - 2 };
10244         let recv_value = 100_000;
10245
10246         create_chan_between_nodes(&nodes[0], &nodes[1]);
10247
10248         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10249         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10250                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10251                         Some(recv_value), Some(min_final_cltv_expiry_delta));
10252                 (payment_hash, payment_preimage, payment_secret)
10253         } else {
10254                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10255                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10256         };
10257         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10258         nodes[0].node.send_payment_with_route(&route, payment_hash,
10259                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10260         check_added_monitors!(nodes[0], 1);
10261         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10262         assert_eq!(events.len(), 1);
10263         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10264         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10265         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10266         expect_pending_htlcs_forwardable!(nodes[1]);
10267
10268         if valid_delta {
10269                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10270                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10271
10272                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10273         } else {
10274                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10275
10276                 check_added_monitors!(nodes[1], 1);
10277
10278                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10279                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10280                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10281
10282                 expect_payment_failed!(nodes[0], payment_hash, true);
10283         }
10284 }
10285
10286 #[test]
10287 fn test_payment_with_custom_min_cltv_expiry_delta() {
10288         do_payment_with_custom_min_final_cltv_expiry(false, false);
10289         do_payment_with_custom_min_final_cltv_expiry(false, true);
10290         do_payment_with_custom_min_final_cltv_expiry(true, false);
10291         do_payment_with_custom_min_final_cltv_expiry(true, true);
10292 }
10293
10294 #[test]
10295 fn test_disconnects_peer_awaiting_response_ticks() {
10296         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10297         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10298         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10301         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10302
10303         // Asserts a disconnect event is queued to the user.
10304         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10305                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10306                         if let MessageSendEvent::HandleError { action, .. } = event {
10307                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10308                                         Some(())
10309                                 } else {
10310                                         None
10311                                 }
10312                         } else {
10313                                 None
10314                         }
10315                 );
10316                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10317         };
10318
10319         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10320         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10321         let check_disconnect = |node: &Node| {
10322                 // No disconnect without any timer ticks.
10323                 check_disconnect_event(node, false);
10324
10325                 // No disconnect with 1 timer tick less than required.
10326                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10327                         node.node.timer_tick_occurred();
10328                         check_disconnect_event(node, false);
10329                 }
10330
10331                 // Disconnect after reaching the required ticks.
10332                 node.node.timer_tick_occurred();
10333                 check_disconnect_event(node, true);
10334
10335                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10336                 node.node.timer_tick_occurred();
10337                 check_disconnect_event(node, true);
10338         };
10339
10340         create_chan_between_nodes(&nodes[0], &nodes[1]);
10341
10342         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10343         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10344         nodes[0].node.timer_tick_occurred();
10345         check_added_monitors!(&nodes[0], 1);
10346         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10347         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10348         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10349         check_added_monitors!(&nodes[1], 1);
10350
10351         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10352         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10353         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10354         check_added_monitors!(&nodes[0], 1);
10355         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10356         check_added_monitors(&nodes[0], 1);
10357
10358         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10359         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10360         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10361         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10362         check_disconnect(&nodes[1]);
10363
10364         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10365         //
10366         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10367         // final `RevokeAndACK` to Bob to complete it.
10368         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10369         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10370         let bob_init = msgs::Init {
10371                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10372         };
10373         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10374         let alice_init = msgs::Init {
10375                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10376         };
10377         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10378
10379         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10380         // received Bob's yet, so she should disconnect him after reaching
10381         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10382         let alice_channel_reestablish = get_event_msg!(
10383                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10384         );
10385         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10386         check_disconnect(&nodes[0]);
10387
10388         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10389         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10390                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10391                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10392                         Some(msg.clone())
10393                 } else {
10394                         None
10395                 }
10396         ).unwrap();
10397         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10398
10399         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10400         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10401                 nodes[0].node.timer_tick_occurred();
10402                 check_disconnect_event(&nodes[0], false);
10403         }
10404
10405         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10406         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10407         check_disconnect(&nodes[1]);
10408
10409         // Finally, have Bob process the last message.
10410         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10411         check_added_monitors(&nodes[1], 1);
10412
10413         // At this point, neither node should attempt to disconnect each other, since they aren't
10414         // waiting on any messages.
10415         for node in &nodes {
10416                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10417                         node.node.timer_tick_occurred();
10418                         check_disconnect_event(node, false);
10419                 }
10420         }
10421 }
10422
10423 #[test]
10424 fn test_remove_expired_outbound_unfunded_channels() {
10425         let chanmon_cfgs = create_chanmon_cfgs(2);
10426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10428         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10429
10430         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10431         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10432         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10433         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10434         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10435
10436         let events = nodes[0].node.get_and_clear_pending_events();
10437         assert_eq!(events.len(), 1);
10438         match events[0] {
10439                 Event::FundingGenerationReady { .. } => (),
10440                 _ => panic!("Unexpected event"),
10441         };
10442
10443         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10444         let check_outbound_channel_existence = |should_exist: bool| {
10445                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10446                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10447                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10448         };
10449
10450         // Channel should exist without any timer ticks.
10451         check_outbound_channel_existence(true);
10452
10453         // Channel should exist with 1 timer tick less than required.
10454         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10455                 nodes[0].node.timer_tick_occurred();
10456                 check_outbound_channel_existence(true)
10457         }
10458
10459         // Remove channel after reaching the required ticks.
10460         nodes[0].node.timer_tick_occurred();
10461         check_outbound_channel_existence(false);
10462
10463         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10464         assert_eq!(msg_events.len(), 1);
10465         match msg_events[0] {
10466                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10467                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10468                 },
10469                 _ => panic!("Unexpected event"),
10470         }
10471         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10472 }
10473
10474 #[test]
10475 fn test_remove_expired_inbound_unfunded_channels() {
10476         let chanmon_cfgs = create_chanmon_cfgs(2);
10477         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10478         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10479         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10480
10481         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10482         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10483         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10484         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10485         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10486
10487         let events = nodes[0].node.get_and_clear_pending_events();
10488         assert_eq!(events.len(), 1);
10489         match events[0] {
10490                 Event::FundingGenerationReady { .. } => (),
10491                 _ => panic!("Unexpected event"),
10492         };
10493
10494         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10495         let check_inbound_channel_existence = |should_exist: bool| {
10496                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10497                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10498                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10499         };
10500
10501         // Channel should exist without any timer ticks.
10502         check_inbound_channel_existence(true);
10503
10504         // Channel should exist with 1 timer tick less than required.
10505         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10506                 nodes[1].node.timer_tick_occurred();
10507                 check_inbound_channel_existence(true)
10508         }
10509
10510         // Remove channel after reaching the required ticks.
10511         nodes[1].node.timer_tick_occurred();
10512         check_inbound_channel_existence(false);
10513
10514         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10515         assert_eq!(msg_events.len(), 1);
10516         match msg_events[0] {
10517                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10518                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10519                 },
10520                 _ => panic!("Unexpected event"),
10521         }
10522         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10523 }
10524
10525 #[test]
10526 fn test_channel_close_when_not_timely_accepted() {
10527         // Create network of two nodes
10528         let chanmon_cfgs = create_chanmon_cfgs(2);
10529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10532
10533         // Simulate peer-disconnects mid-handshake
10534         // The channel is initiated from the node 0 side,
10535         // but the nodes disconnect before node 1 could send accept channel
10536         let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10537         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10538         assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10539
10540         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10541         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10542
10543         // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10544         assert_eq!(nodes[0].node.list_channels().len(), 1);
10545
10546         // Since channel was inbound from node[1] perspective, it should have been dropped immediately.
10547         assert_eq!(nodes[1].node.list_channels().len(), 0);
10548
10549         // In the meantime, some time passes.
10550         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
10551                 nodes[0].node.timer_tick_occurred();
10552         }
10553
10554         // Since we disconnected from peer and did not connect back within time,
10555         // we should have forced-closed the channel by now.
10556         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
10557         assert_eq!(nodes[0].node.list_channels().len(), 0);
10558
10559         {
10560                 // Since accept channel message was never received
10561                 // The channel should be forced close by now from node 0 side
10562                 // and the peer removed from per_peer_state
10563                 let node_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10564                 assert_eq!(node_0_per_peer_state.len(), 0);
10565         }
10566 }
10567
10568 #[test]
10569 fn test_rebroadcast_open_channel_when_reconnect_mid_handshake() {
10570         // Create network of two nodes
10571         let chanmon_cfgs = create_chanmon_cfgs(2);
10572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10574         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10575
10576         // Simulate peer-disconnects mid-handshake
10577         // The channel is initiated from the node 0 side,
10578         // but the nodes disconnect before node 1 could send accept channel
10579         let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10580         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10581         assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10582
10583         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10584         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10585
10586         // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10587         assert_eq!(nodes[0].node.list_channels().len(), 1);
10588
10589         // Since channel was inbound from node[1] perspective, it should have been immediately dropped.
10590         assert_eq!(nodes[1].node.list_channels().len(), 0);
10591
10592         // The peers now reconnect
10593         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
10594                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10595         }, true).unwrap();
10596         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10597                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10598         }, false).unwrap();
10599
10600         // Make sure the SendOpenChannel message is added to node_0 pending message events
10601         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10602         assert_eq!(msg_events.len(), 1);
10603         match &msg_events[0] {
10604                 MessageSendEvent::SendOpenChannel { msg, .. } => assert_eq!(msg, &open_channel_msg),
10605                 _ => panic!("Unexpected message."),
10606         }
10607 }
10608
10609 fn do_test_multi_post_event_actions(do_reload: bool) {
10610         // Tests handling multiple post-Event actions at once.
10611         // There is specific code in ChannelManager to handle channels where multiple post-Event
10612         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10613         //
10614         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10615         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10616         // - one from an RAA and one from an inbound commitment_signed.
10617         let chanmon_cfgs = create_chanmon_cfgs(3);
10618         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10619         let (persister, chain_monitor);
10620         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10621         let nodes_0_deserialized;
10622         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10623
10624         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10625         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10626
10627         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10628         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10629
10630         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10631         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10632
10633         nodes[1].node.claim_funds(our_payment_preimage);
10634         check_added_monitors!(nodes[1], 1);
10635         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10636
10637         nodes[2].node.claim_funds(payment_preimage_2);
10638         check_added_monitors!(nodes[2], 1);
10639         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10640
10641         for dest in &[1, 2] {
10642                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10643                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10644                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10645                 check_added_monitors(&nodes[0], 0);
10646         }
10647
10648         let (route, payment_hash_3, _, payment_secret_3) =
10649                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10650         let payment_id = PaymentId(payment_hash_3.0);
10651         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10652                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10653         check_added_monitors(&nodes[1], 1);
10654
10655         let send_event = SendEvent::from_node(&nodes[1]);
10656         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10657         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10658         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10659
10660         if do_reload {
10661                 let nodes_0_serialized = nodes[0].node.encode();
10662                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10663                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10664                 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);
10665
10666                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10667                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10668
10669                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10670                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10671         }
10672
10673         let events = nodes[0].node.get_and_clear_pending_events();
10674         assert_eq!(events.len(), 4);
10675         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10676                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10677         } else { panic!(); }
10678         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10679                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10680         } else { panic!(); }
10681         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10682         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10683
10684         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10685         // completion, we'll respond to nodes[1] with an RAA + CS.
10686         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10687         check_added_monitors(&nodes[0], 3);
10688 }
10689
10690 #[test]
10691 fn test_multi_post_event_actions() {
10692         do_test_multi_post_event_actions(true);
10693         do_test_multi_post_event_actions(false);
10694 }
10695
10696 #[test]
10697 fn test_batch_channel_open() {
10698         let chanmon_cfgs = create_chanmon_cfgs(3);
10699         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10700         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10701         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10702
10703         // Initiate channel opening and create the batch channel funding transaction.
10704         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10705                 (&nodes[1], 100_000, 0, 42, None),
10706                 (&nodes[2], 200_000, 0, 43, None),
10707         ]);
10708
10709         // Go through the funding_created and funding_signed flow with node 1.
10710         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10711         check_added_monitors(&nodes[1], 1);
10712         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10713
10714         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10715         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10716         check_added_monitors(&nodes[0], 1);
10717
10718         // The transaction should not have been broadcast before all channels are ready.
10719         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10720
10721         // Go through the funding_created and funding_signed flow with node 2.
10722         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10723         check_added_monitors(&nodes[2], 1);
10724         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10725
10726         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10727         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10728         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10729         check_added_monitors(&nodes[0], 1);
10730
10731         // The transaction should not have been broadcast before persisting all monitors has been
10732         // completed.
10733         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10734         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10735
10736         // Complete the persistence of the monitor.
10737         nodes[0].chain_monitor.complete_sole_pending_chan_update(
10738                 &ChannelId::v1_from_funding_outpoint(OutPoint { txid: tx.txid(), index: 1 })
10739         );
10740         let events = nodes[0].node.get_and_clear_pending_events();
10741
10742         // The transaction should only have been broadcast now.
10743         let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10744         assert_eq!(broadcasted_txs.len(), 1);
10745         assert_eq!(broadcasted_txs[0], tx);
10746
10747         assert_eq!(events.len(), 2);
10748         assert!(events.iter().any(|e| matches!(
10749                 *e,
10750                 crate::events::Event::ChannelPending {
10751                         ref counterparty_node_id,
10752                         ..
10753                 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10754         )));
10755         assert!(events.iter().any(|e| matches!(
10756                 *e,
10757                 crate::events::Event::ChannelPending {
10758                         ref counterparty_node_id,
10759                         ..
10760                 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10761         )));
10762 }
10763
10764 #[test]
10765 fn test_close_in_funding_batch() {
10766         // This test ensures that if one of the channels
10767         // in the batch closes, the complete batch will close.
10768         let chanmon_cfgs = create_chanmon_cfgs(3);
10769         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10770         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10771         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10772
10773         // Initiate channel opening and create the batch channel funding transaction.
10774         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10775                 (&nodes[1], 100_000, 0, 42, None),
10776                 (&nodes[2], 200_000, 0, 43, None),
10777         ]);
10778
10779         // Go through the funding_created and funding_signed flow with node 1.
10780         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10781         check_added_monitors(&nodes[1], 1);
10782         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10783
10784         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10785         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10786         check_added_monitors(&nodes[0], 1);
10787
10788         // The transaction should not have been broadcast before all channels are ready.
10789         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10790
10791         // Force-close the channel for which we've completed the initial monitor.
10792         let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10793         let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10794         let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10795         let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10796
10797         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10798
10799         // The monitor should become closed.
10800         check_added_monitors(&nodes[0], 1);
10801         {
10802                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10803                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10804                 assert_eq!(monitor_updates_1.len(), 1);
10805                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10806         }
10807
10808         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10809         match msg_events[0] {
10810                 MessageSendEvent::HandleError { .. } => (),
10811                 _ => panic!("Unexpected message."),
10812         }
10813
10814         // We broadcast the commitment transaction as part of the force-close.
10815         {
10816                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10817                 assert_eq!(broadcasted_txs.len(), 1);
10818                 assert!(broadcasted_txs[0].txid() != tx.txid());
10819                 assert_eq!(broadcasted_txs[0].input.len(), 1);
10820                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10821         }
10822
10823         // All channels in the batch should close immediately.
10824         check_closed_events(&nodes[0], &[
10825                 ExpectedCloseEvent {
10826                         channel_id: Some(channel_id_1),
10827                         discard_funding: true,
10828                         channel_funding_txo: Some(funding_txo_1),
10829                         user_channel_id: Some(42),
10830                         ..Default::default()
10831                 },
10832                 ExpectedCloseEvent {
10833                         channel_id: Some(channel_id_2),
10834                         discard_funding: true,
10835                         channel_funding_txo: Some(funding_txo_2),
10836                         user_channel_id: Some(43),
10837                         ..Default::default()
10838                 },
10839         ]);
10840
10841         // Ensure the channels don't exist anymore.
10842         assert!(nodes[0].node.list_channels().is_empty());
10843 }
10844
10845 #[test]
10846 fn test_batch_funding_close_after_funding_signed() {
10847         let chanmon_cfgs = create_chanmon_cfgs(3);
10848         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10849         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10850         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10851
10852         // Initiate channel opening and create the batch channel funding transaction.
10853         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10854                 (&nodes[1], 100_000, 0, 42, None),
10855                 (&nodes[2], 200_000, 0, 43, None),
10856         ]);
10857
10858         // Go through the funding_created and funding_signed flow with node 1.
10859         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10860         check_added_monitors(&nodes[1], 1);
10861         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10862
10863         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10864         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10865         check_added_monitors(&nodes[0], 1);
10866
10867         // Go through the funding_created and funding_signed flow with node 2.
10868         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10869         check_added_monitors(&nodes[2], 1);
10870         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10871
10872         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10873         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10874         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10875         check_added_monitors(&nodes[0], 1);
10876
10877         // The transaction should not have been broadcast before all channels are ready.
10878         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10879
10880         // Force-close the channel for which we've completed the initial monitor.
10881         let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10882         let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10883         let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10884         let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10885         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10886         check_added_monitors(&nodes[0], 2);
10887         {
10888                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10889                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10890                 assert_eq!(monitor_updates_1.len(), 1);
10891                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10892                 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10893                 assert_eq!(monitor_updates_2.len(), 1);
10894                 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10895         }
10896         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10897         match msg_events[0] {
10898                 MessageSendEvent::HandleError { .. } => (),
10899                 _ => panic!("Unexpected message."),
10900         }
10901
10902         // We broadcast the commitment transaction as part of the force-close.
10903         {
10904                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10905                 assert_eq!(broadcasted_txs.len(), 1);
10906                 assert!(broadcasted_txs[0].txid() != tx.txid());
10907                 assert_eq!(broadcasted_txs[0].input.len(), 1);
10908                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10909         }
10910
10911         // All channels in the batch should close immediately.
10912         check_closed_events(&nodes[0], &[
10913                 ExpectedCloseEvent {
10914                         channel_id: Some(channel_id_1),
10915                         discard_funding: true,
10916                         channel_funding_txo: Some(funding_txo_1),
10917                         user_channel_id: Some(42),
10918                         ..Default::default()
10919                 },
10920                 ExpectedCloseEvent {
10921                         channel_id: Some(channel_id_2),
10922                         discard_funding: true,
10923                         channel_funding_txo: Some(funding_txo_2),
10924                         user_channel_id: Some(43),
10925                         ..Default::default()
10926                 },
10927         ]);
10928
10929         // Ensure the channels don't exist anymore.
10930         assert!(nodes[0].node.list_channels().is_empty());
10931 }
10932
10933 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10934         // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10935         // funding and commitment transaction confirm in the same block.
10936         let chanmon_cfgs = create_chanmon_cfgs(2);
10937         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10938         let mut min_depth_1_block_cfg = test_default_channel_config();
10939         min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10940         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10941         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10942
10943         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10944         let chan_id = ChannelId::v1_from_funding_outpoint(chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 });
10945
10946         assert_eq!(nodes[0].node.list_channels().len(), 1);
10947         assert_eq!(nodes[1].node.list_channels().len(), 1);
10948
10949         let (closing_node, other_node) = if confirm_remote_commitment {
10950                 (&nodes[1], &nodes[0])
10951         } else {
10952                 (&nodes[0], &nodes[1])
10953         };
10954
10955         closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10956         let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10957         assert_eq!(msg_events.len(), 1);
10958         match msg_events.pop().unwrap() {
10959                 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10960                 _ => panic!("Unexpected event"),
10961         }
10962         check_added_monitors(closing_node, 1);
10963         check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10964
10965         let commitment_tx = {
10966                 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10967                 assert_eq!(txn.len(), 1);
10968                 let commitment_tx = txn.pop().unwrap();
10969                 check_spends!(commitment_tx, funding_tx);
10970                 commitment_tx
10971         };
10972
10973         mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10974         mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10975
10976         check_closed_broadcast(other_node, 1, true);
10977         check_added_monitors(other_node, 1);
10978         check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10979
10980         assert!(nodes[0].node.list_channels().is_empty());
10981         assert!(nodes[1].node.list_channels().is_empty());
10982 }
10983
10984 #[test]
10985 fn test_funding_and_commitment_tx_confirm_same_block() {
10986         do_test_funding_and_commitment_tx_confirm_same_block(false);
10987         do_test_funding_and_commitment_tx_confirm_same_block(true);
10988 }
10989
10990 #[test]
10991 fn test_accept_inbound_channel_errors_queued() {
10992         // For manually accepted inbound channels, tests that a close error is correctly handled
10993         // and the channel fails for the initiator.
10994         let mut config0 = test_default_channel_config();
10995         let mut config1 = config0.clone();
10996         config1.channel_handshake_limits.their_to_self_delay = 1000;
10997         config1.manually_accept_inbound_channels = true;
10998         config0.channel_handshake_config.our_to_self_delay = 2000;
10999
11000         let chanmon_cfgs = create_chanmon_cfgs(2);
11001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config0), Some(config1)]);
11003         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11004
11005         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11006         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11007
11008         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11009         let events = nodes[1].node.get_and_clear_pending_events();
11010         match events[0] {
11011                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11012                         match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23) {
11013                                 Err(APIError::ChannelUnavailable { err: _ }) => (),
11014                                 _ => panic!(),
11015                         }
11016                 }
11017                 _ => panic!("Unexpected event"),
11018         }
11019         assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11020                 open_channel_msg.common_fields.temporary_channel_id);
11021 }