Upgrade rust-bitcoin to 0.31
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, OutputSpender, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::types::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::locktime::absolute::LockTime;
42 use bitcoin::blockdata::script::{Builder, ScriptBuf};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::network::Network;
46 use bitcoin::{Amount, Sequence, Transaction, TxIn, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::transaction::Version;
49
50 use bitcoin::secp256k1::Secp256k1;
51 use bitcoin::secp256k1::{PublicKey,SecretKey};
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::iter::repeat;
57 use bitcoin::hashes::Hash;
58 use crate::sync::{Arc, Mutex, RwLock};
59
60 use crate::ln::functional_test_utils::*;
61 use crate::ln::chan_utils::CommitmentTransaction;
62
63 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
64
65 #[test]
66 fn test_channel_resumption_fail_post_funding() {
67         // If we fail to exchange funding with a peer prior to it disconnecting we'll resume the
68         // channel open on reconnect, however if we do exchange funding we do not currently support
69         // replaying it and here test that the channel closes.
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 0, 42, None, None).unwrap();
76         let open_chan = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
77         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan);
78         let accept_chan = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
79         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan);
80
81         let (temp_chan_id, tx, funding_output) =
82                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
83         let new_chan_id = ChannelId::v1_from_funding_outpoint(funding_output);
84         nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
85
86         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
87         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(new_chan_id, true, ClosureReason::DisconnectedPeer)]);
88
89         // After ddf75afd16 we'd panic on reconnection if we exchanged funding info, so test that
90         // explicitly here.
91         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
92                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
93         }, true).unwrap();
94         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events(), Vec::new());
95 }
96
97 #[test]
98 fn test_insane_channel_opens() {
99         // Stand up a network of 2 nodes
100         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
101         let mut cfg = UserConfig::default();
102         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
103         let chanmon_cfgs = create_chanmon_cfgs(2);
104         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
105         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
106         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
107
108         // Instantiate channel parameters where we push the maximum msats given our
109         // funding satoshis
110         let channel_value_sat = 31337; // same as funding satoshis
111         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
112         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
113
114         // Have node0 initiate a channel to node1 with aforementioned parameters
115         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
116
117         // Extract the channel open message from node0 to node1
118         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
119
120         // Test helper that asserts we get the correct error string given a mutator
121         // that supposedly makes the channel open message insane
122         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
123                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
124                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
125                 assert_eq!(msg_events.len(), 1);
126                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
127                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
128                         match action {
129                                 &ErrorAction::SendErrorMessage { .. } => {
130                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
131                                 },
132                                 _ => panic!("unexpected event!"),
133                         }
134                 } else { assert!(false); }
135         };
136
137         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
138
139         // Test all mutations that would make the channel open message insane
140         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 });
141         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 });
142
143         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.common_fields.funding_satoshis + 1; msg });
144
145         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 });
146
147         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.common_fields.dust_limit_satoshis = msg.common_fields.funding_satoshis + 1 ; msg });
148
149         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 });
150
151         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 });
152
153         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.common_fields.max_accepted_htlcs = 0; msg });
154
155         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 });
156 }
157
158 #[test]
159 fn test_funding_exceeds_no_wumbo_limit() {
160         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
161         // them.
162         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
163         let chanmon_cfgs = create_chanmon_cfgs(2);
164         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
165         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
166         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
167         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
168
169         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
170                 Err(APIError::APIMisuseError { err }) => {
171                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
172                 },
173                 _ => panic!()
174         }
175 }
176
177 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
178         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
179         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
180         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
181         // in normal testing, we test it explicitly here.
182         let chanmon_cfgs = create_chanmon_cfgs(2);
183         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
184         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
185         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
186         let default_config = UserConfig::default();
187
188         // Have node0 initiate a channel to node1 with aforementioned parameters
189         let mut push_amt = 100_000_000;
190         let feerate_per_kw = 253;
191         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
192         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
193         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
194
195         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();
196         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
197         if !send_from_initiator {
198                 open_channel_message.channel_reserve_satoshis = 0;
199                 open_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
200         }
201         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
202
203         // Extract the channel accept message from node1 to node0
204         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
205         if send_from_initiator {
206                 accept_channel_message.channel_reserve_satoshis = 0;
207                 accept_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
208         }
209         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
210         {
211                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
212                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
213                 let mut sender_node_per_peer_lock;
214                 let mut sender_node_peer_state_lock;
215
216                 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
217                 match channel_phase {
218                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
219                                 let chan_context = channel_phase.context_mut();
220                                 chan_context.holder_selected_channel_reserve_satoshis = 0;
221                                 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
222                         },
223                         _ => assert!(false),
224                 }
225         }
226
227         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
228         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
229         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
230
231         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
232         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
233         if send_from_initiator {
234                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
235                         // Note that for outbound channels we have to consider the commitment tx fee and the
236                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
237                         // well as an additional HTLC.
238                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
239         } else {
240                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
241         }
242 }
243
244 #[test]
245 fn test_counterparty_no_reserve() {
246         do_test_counterparty_no_reserve(true);
247         do_test_counterparty_no_reserve(false);
248 }
249
250 #[test]
251 fn test_async_inbound_update_fee() {
252         let chanmon_cfgs = create_chanmon_cfgs(2);
253         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
254         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
255         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
256         create_announced_chan_between_nodes(&nodes, 0, 1);
257
258         // balancing
259         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
260
261         // A                                        B
262         // update_fee                            ->
263         // send (1) commitment_signed            -.
264         //                                       <- update_add_htlc/commitment_signed
265         // send (2) RAA (awaiting remote revoke) -.
266         // (1) commitment_signed is delivered    ->
267         //                                       .- send (3) RAA (awaiting remote revoke)
268         // (2) RAA is delivered                  ->
269         //                                       .- send (4) commitment_signed
270         //                                       <- (3) RAA is delivered
271         // send (5) commitment_signed            -.
272         //                                       <- (4) commitment_signed is delivered
273         // send (6) RAA                          -.
274         // (5) commitment_signed is delivered    ->
275         //                                       <- RAA
276         // (6) RAA is delivered                  ->
277
278         // First nodes[0] generates an update_fee
279         {
280                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
281                 *feerate_lock += 20;
282         }
283         nodes[0].node.timer_tick_occurred();
284         check_added_monitors!(nodes[0], 1);
285
286         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
287         assert_eq!(events_0.len(), 1);
288         let (update_msg, commitment_signed) = match events_0[0] { // (1)
289                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
290                         (update_fee.as_ref(), commitment_signed)
291                 },
292                 _ => panic!("Unexpected event"),
293         };
294
295         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
296
297         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
298         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
299         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
300                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
301         check_added_monitors!(nodes[1], 1);
302
303         let payment_event = {
304                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
305                 assert_eq!(events_1.len(), 1);
306                 SendEvent::from_event(events_1.remove(0))
307         };
308         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
309         assert_eq!(payment_event.msgs.len(), 1);
310
311         // ...now when the messages get delivered everyone should be happy
312         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
313         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
314         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
315         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
316         check_added_monitors!(nodes[0], 1);
317
318         // deliver(1), generate (3):
319         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
320         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
321         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
322         check_added_monitors!(nodes[1], 1);
323
324         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
325         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
326         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
327         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
328         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
329         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
330         assert!(bs_update.update_fee.is_none()); // (4)
331         check_added_monitors!(nodes[1], 1);
332
333         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
334         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
335         assert!(as_update.update_add_htlcs.is_empty()); // (5)
336         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
337         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
338         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
339         assert!(as_update.update_fee.is_none()); // (5)
340         check_added_monitors!(nodes[0], 1);
341
342         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
343         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
344         // only (6) so get_event_msg's assert(len == 1) passes
345         check_added_monitors!(nodes[0], 1);
346
347         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
348         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
349         check_added_monitors!(nodes[1], 1);
350
351         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
352         check_added_monitors!(nodes[0], 1);
353
354         let events_2 = nodes[0].node.get_and_clear_pending_events();
355         assert_eq!(events_2.len(), 1);
356         match events_2[0] {
357                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
358                 _ => panic!("Unexpected event"),
359         }
360
361         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
362         check_added_monitors!(nodes[1], 1);
363 }
364
365 #[test]
366 fn test_update_fee_unordered_raa() {
367         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
368         // crash in an earlier version of the update_fee patch)
369         let chanmon_cfgs = create_chanmon_cfgs(2);
370         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
371         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
372         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
373         create_announced_chan_between_nodes(&nodes, 0, 1);
374
375         // balancing
376         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
377
378         // First nodes[0] generates an update_fee
379         {
380                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
381                 *feerate_lock += 20;
382         }
383         nodes[0].node.timer_tick_occurred();
384         check_added_monitors!(nodes[0], 1);
385
386         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
387         assert_eq!(events_0.len(), 1);
388         let update_msg = match events_0[0] { // (1)
389                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
390                         update_fee.as_ref()
391                 },
392                 _ => panic!("Unexpected event"),
393         };
394
395         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
396
397         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
398         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
399         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
400                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
401         check_added_monitors!(nodes[1], 1);
402
403         let payment_event = {
404                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
405                 assert_eq!(events_1.len(), 1);
406                 SendEvent::from_event(events_1.remove(0))
407         };
408         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
409         assert_eq!(payment_event.msgs.len(), 1);
410
411         // ...now when the messages get delivered everyone should be happy
412         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
413         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
414         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
415         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
416         check_added_monitors!(nodes[0], 1);
417
418         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
419         check_added_monitors!(nodes[1], 1);
420
421         // We can't continue, sadly, because our (1) now has a bogus signature
422 }
423
424 #[test]
425 fn test_multi_flight_update_fee() {
426         let chanmon_cfgs = create_chanmon_cfgs(2);
427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
429         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
430         create_announced_chan_between_nodes(&nodes, 0, 1);
431
432         // A                                        B
433         // update_fee/commitment_signed          ->
434         //                                       .- send (1) RAA and (2) commitment_signed
435         // update_fee (never committed)          ->
436         // (3) update_fee                        ->
437         // We have to manually generate the above update_fee, it is allowed by the protocol but we
438         // don't track which updates correspond to which revoke_and_ack responses so we're in
439         // AwaitingRAA mode and will not generate the update_fee yet.
440         //                                       <- (1) RAA delivered
441         // (3) is generated and send (4) CS      -.
442         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
443         // know the per_commitment_point to use for it.
444         //                                       <- (2) commitment_signed delivered
445         // revoke_and_ack                        ->
446         //                                          B should send no response here
447         // (4) commitment_signed delivered       ->
448         //                                       <- RAA/commitment_signed delivered
449         // revoke_and_ack                        ->
450
451         // First nodes[0] generates an update_fee
452         let initial_feerate;
453         {
454                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
455                 initial_feerate = *feerate_lock;
456                 *feerate_lock = initial_feerate + 20;
457         }
458         nodes[0].node.timer_tick_occurred();
459         check_added_monitors!(nodes[0], 1);
460
461         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
462         assert_eq!(events_0.len(), 1);
463         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
464                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
465                         (update_fee.as_ref().unwrap(), commitment_signed)
466                 },
467                 _ => panic!("Unexpected event"),
468         };
469
470         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
471         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
472         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
473         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
474         check_added_monitors!(nodes[1], 1);
475
476         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
477         // transaction:
478         {
479                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
480                 *feerate_lock = initial_feerate + 40;
481         }
482         nodes[0].node.timer_tick_occurred();
483         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
484         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
485
486         // Create the (3) update_fee message that nodes[0] will generate before it does...
487         let mut update_msg_2 = msgs::UpdateFee {
488                 channel_id: update_msg_1.channel_id.clone(),
489                 feerate_per_kw: (initial_feerate + 30) as u32,
490         };
491
492         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
493
494         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
495         // Deliver (3)
496         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
497
498         // Deliver (1), generating (3) and (4)
499         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
500         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
501         check_added_monitors!(nodes[0], 1);
502         assert!(as_second_update.update_add_htlcs.is_empty());
503         assert!(as_second_update.update_fulfill_htlcs.is_empty());
504         assert!(as_second_update.update_fail_htlcs.is_empty());
505         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
506         // Check that the update_fee newly generated matches what we delivered:
507         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
508         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
509
510         // Deliver (2) commitment_signed
511         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
512         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
513         check_added_monitors!(nodes[0], 1);
514         // No commitment_signed so get_event_msg's assert(len == 1) passes
515
516         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
517         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
518         check_added_monitors!(nodes[1], 1);
519
520         // Delever (4)
521         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
522         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
523         check_added_monitors!(nodes[1], 1);
524
525         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
526         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
527         check_added_monitors!(nodes[0], 1);
528
529         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
530         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
531         // No commitment_signed so get_event_msg's assert(len == 1) passes
532         check_added_monitors!(nodes[0], 1);
533
534         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
535         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
536         check_added_monitors!(nodes[1], 1);
537 }
538
539 fn do_test_sanity_on_in_flight_opens(steps: u8) {
540         // Previously, we had issues deserializing channels when we hadn't connected the first block
541         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
542         // serialization round-trips and simply do steps towards opening a channel and then drop the
543         // Node objects.
544
545         let chanmon_cfgs = create_chanmon_cfgs(2);
546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
548         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
549
550         if steps & 0b1000_0000 != 0{
551                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
552                 connect_block(&nodes[0], &block);
553                 connect_block(&nodes[1], &block);
554         }
555
556         if steps & 0x0f == 0 { return; }
557         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
558         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
559
560         if steps & 0x0f == 1 { return; }
561         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
562         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
563
564         if steps & 0x0f == 2 { return; }
565         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
566
567         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
568
569         if steps & 0x0f == 3 { return; }
570         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
571         check_added_monitors!(nodes[0], 0);
572         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
573
574         if steps & 0x0f == 4 { return; }
575         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
576         {
577                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
578                 assert_eq!(added_monitors.len(), 1);
579                 assert_eq!(added_monitors[0].0, funding_output);
580                 added_monitors.clear();
581         }
582         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
583
584         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
585
586         if steps & 0x0f == 5 { return; }
587         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
588         {
589                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
590                 assert_eq!(added_monitors.len(), 1);
591                 assert_eq!(added_monitors[0].0, funding_output);
592                 added_monitors.clear();
593         }
594
595         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
596         let events_4 = nodes[0].node.get_and_clear_pending_events();
597         assert_eq!(events_4.len(), 0);
598
599         if steps & 0x0f == 6 { return; }
600         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
601
602         if steps & 0x0f == 7 { return; }
603         confirm_transaction_at(&nodes[0], &tx, 2);
604         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
605         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
606         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
607 }
608
609 #[test]
610 fn test_sanity_on_in_flight_opens() {
611         do_test_sanity_on_in_flight_opens(0);
612         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
613         do_test_sanity_on_in_flight_opens(1);
614         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
615         do_test_sanity_on_in_flight_opens(2);
616         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
617         do_test_sanity_on_in_flight_opens(3);
618         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
619         do_test_sanity_on_in_flight_opens(4);
620         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
621         do_test_sanity_on_in_flight_opens(5);
622         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
623         do_test_sanity_on_in_flight_opens(6);
624         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
625         do_test_sanity_on_in_flight_opens(7);
626         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
627         do_test_sanity_on_in_flight_opens(8);
628         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
629 }
630
631 #[test]
632 fn test_update_fee_vanilla() {
633         let chanmon_cfgs = create_chanmon_cfgs(2);
634         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
635         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
636         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
637         create_announced_chan_between_nodes(&nodes, 0, 1);
638
639         {
640                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
641                 *feerate_lock += 25;
642         }
643         nodes[0].node.timer_tick_occurred();
644         check_added_monitors!(nodes[0], 1);
645
646         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
647         assert_eq!(events_0.len(), 1);
648         let (update_msg, commitment_signed) = match events_0[0] {
649                         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 } } => {
650                         (update_fee.as_ref(), commitment_signed)
651                 },
652                 _ => panic!("Unexpected event"),
653         };
654         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
655
656         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
657         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
658         check_added_monitors!(nodes[1], 1);
659
660         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
661         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
662         check_added_monitors!(nodes[0], 1);
663
664         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
665         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
666         // No commitment_signed so get_event_msg's assert(len == 1) passes
667         check_added_monitors!(nodes[0], 1);
668
669         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
670         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
671         check_added_monitors!(nodes[1], 1);
672 }
673
674 #[test]
675 fn test_update_fee_that_funder_cannot_afford() {
676         let chanmon_cfgs = create_chanmon_cfgs(2);
677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
679         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
680         let channel_value = 5000;
681         let push_sats = 700;
682         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
683         let channel_id = chan.2;
684         let secp_ctx = Secp256k1::new();
685         let default_config = UserConfig::default();
686         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
687
688         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
689
690         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
691         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
692         // calculate two different feerates here - the expected local limit as well as the expected
693         // remote limit.
694         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;
695         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
696         {
697                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
698                 *feerate_lock = feerate;
699         }
700         nodes[0].node.timer_tick_occurred();
701         check_added_monitors!(nodes[0], 1);
702         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
703
704         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
705
706         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
707
708         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
709         {
710                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
711
712                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
713                 assert_eq!(commitment_tx.output.len(), 2);
714                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
715                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value.to_sat());
716                 actual_fee = channel_value - actual_fee;
717                 assert_eq!(total_fee, actual_fee);
718         }
719
720         {
721                 // Increment the feerate by a small constant, accounting for rounding errors
722                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
723                 *feerate_lock += 4;
724         }
725         nodes[0].node.timer_tick_occurred();
726         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
727         check_added_monitors!(nodes[0], 0);
728
729         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
730
731         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
732         // needed to sign the new commitment tx and (2) sign the new commitment tx.
733         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
734                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
735                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
736                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
737                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
738                 ).flatten().unwrap();
739                 let chan_signer = local_chan.get_signer();
740                 let pubkeys = chan_signer.as_ref().pubkeys();
741                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
742                  pubkeys.funding_pubkey)
743         };
744         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
745                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
746                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
747                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
748                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
749                 ).flatten().unwrap();
750                 let chan_signer = remote_chan.get_signer();
751                 let pubkeys = chan_signer.as_ref().pubkeys();
752                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
753                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
754                  pubkeys.funding_pubkey)
755         };
756
757         // Assemble the set of keys we can use for signatures for our commitment_signed message.
758         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
759                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
760
761         let res = {
762                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
763                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
764                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
765                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
766                 ).flatten().unwrap();
767                 let local_chan_signer = local_chan.get_signer();
768                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
769                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
770                         INITIAL_COMMITMENT_NUMBER - 1,
771                         push_sats,
772                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
773                         local_funding, remote_funding,
774                         commit_tx_keys.clone(),
775                         non_buffer_feerate + 4,
776                         &mut htlcs,
777                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
778                 );
779                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
780         };
781
782         let commit_signed_msg = msgs::CommitmentSigned {
783                 channel_id: chan.2,
784                 signature: res.0,
785                 htlc_signatures: res.1,
786                 #[cfg(taproot)]
787                 partial_signature_with_nonce: None,
788         };
789
790         let update_fee = msgs::UpdateFee {
791                 channel_id: chan.2,
792                 feerate_per_kw: non_buffer_feerate + 4,
793         };
794
795         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
796
797         //While producing the commitment_signed response after handling a received update_fee request the
798         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
799         //Should produce and error.
800         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
801         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee", 3);
802         check_added_monitors!(nodes[1], 1);
803         check_closed_broadcast!(nodes[1], true);
804         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
805                 [nodes[0].node.get_our_node_id()], channel_value);
806 }
807
808 #[test]
809 fn test_update_fee_with_fundee_update_add_htlc() {
810         let chanmon_cfgs = create_chanmon_cfgs(2);
811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
813         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
814         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
815
816         // balancing
817         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
818
819         {
820                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
821                 *feerate_lock += 20;
822         }
823         nodes[0].node.timer_tick_occurred();
824         check_added_monitors!(nodes[0], 1);
825
826         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
827         assert_eq!(events_0.len(), 1);
828         let (update_msg, commitment_signed) = match events_0[0] {
829                         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 } } => {
830                         (update_fee.as_ref(), commitment_signed)
831                 },
832                 _ => panic!("Unexpected event"),
833         };
834         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
835         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
836         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
837         check_added_monitors!(nodes[1], 1);
838
839         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
840
841         // nothing happens since node[1] is in AwaitingRemoteRevoke
842         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
843                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
844         {
845                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
846                 assert_eq!(added_monitors.len(), 0);
847                 added_monitors.clear();
848         }
849         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
850         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
851         // node[1] has nothing to do
852
853         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
854         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
855         check_added_monitors!(nodes[0], 1);
856
857         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
858         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
859         // No commitment_signed so get_event_msg's assert(len == 1) passes
860         check_added_monitors!(nodes[0], 1);
861         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
862         check_added_monitors!(nodes[1], 1);
863         // AwaitingRemoteRevoke ends here
864
865         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
866         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
867         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
868         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
869         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
870         assert_eq!(commitment_update.update_fee.is_none(), true);
871
872         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
873         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
874         check_added_monitors!(nodes[0], 1);
875         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
876
877         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
878         check_added_monitors!(nodes[1], 1);
879         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
880
881         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
882         check_added_monitors!(nodes[1], 1);
883         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
884         // No commitment_signed so get_event_msg's assert(len == 1) passes
885
886         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
887         check_added_monitors!(nodes[0], 1);
888         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
889
890         expect_pending_htlcs_forwardable!(nodes[0]);
891
892         let events = nodes[0].node.get_and_clear_pending_events();
893         assert_eq!(events.len(), 1);
894         match events[0] {
895                 Event::PaymentClaimable { .. } => { },
896                 _ => panic!("Unexpected event"),
897         };
898
899         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
900
901         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
902         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
903         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
904         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
905         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
906 }
907
908 #[test]
909 fn test_update_fee() {
910         let chanmon_cfgs = create_chanmon_cfgs(2);
911         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
912         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
913         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
914         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
915         let channel_id = chan.2;
916
917         // A                                        B
918         // (1) update_fee/commitment_signed      ->
919         //                                       <- (2) revoke_and_ack
920         //                                       .- send (3) commitment_signed
921         // (4) update_fee/commitment_signed      ->
922         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
923         //                                       <- (3) commitment_signed delivered
924         // send (6) revoke_and_ack               -.
925         //                                       <- (5) deliver revoke_and_ack
926         // (6) deliver revoke_and_ack            ->
927         //                                       .- send (7) commitment_signed in response to (4)
928         //                                       <- (7) deliver commitment_signed
929         // revoke_and_ack                        ->
930
931         // Create and deliver (1)...
932         let feerate;
933         {
934                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
935                 feerate = *feerate_lock;
936                 *feerate_lock = feerate + 20;
937         }
938         nodes[0].node.timer_tick_occurred();
939         check_added_monitors!(nodes[0], 1);
940
941         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
942         assert_eq!(events_0.len(), 1);
943         let (update_msg, commitment_signed) = match events_0[0] {
944                         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 } } => {
945                         (update_fee.as_ref(), commitment_signed)
946                 },
947                 _ => panic!("Unexpected event"),
948         };
949         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
950
951         // Generate (2) and (3):
952         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
953         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
954         check_added_monitors!(nodes[1], 1);
955
956         // Deliver (2):
957         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
958         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
959         check_added_monitors!(nodes[0], 1);
960
961         // Create and deliver (4)...
962         {
963                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
964                 *feerate_lock = feerate + 30;
965         }
966         nodes[0].node.timer_tick_occurred();
967         check_added_monitors!(nodes[0], 1);
968         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
969         assert_eq!(events_0.len(), 1);
970         let (update_msg, commitment_signed) = match events_0[0] {
971                         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 } } => {
972                         (update_fee.as_ref(), commitment_signed)
973                 },
974                 _ => panic!("Unexpected event"),
975         };
976
977         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
978         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
979         check_added_monitors!(nodes[1], 1);
980         // ... creating (5)
981         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
982         // No commitment_signed so get_event_msg's assert(len == 1) passes
983
984         // Handle (3), creating (6):
985         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
986         check_added_monitors!(nodes[0], 1);
987         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
988         // No commitment_signed so get_event_msg's assert(len == 1) passes
989
990         // Deliver (5):
991         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
992         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
993         check_added_monitors!(nodes[0], 1);
994
995         // Deliver (6), creating (7):
996         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
997         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
998         assert!(commitment_update.update_add_htlcs.is_empty());
999         assert!(commitment_update.update_fulfill_htlcs.is_empty());
1000         assert!(commitment_update.update_fail_htlcs.is_empty());
1001         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1002         assert!(commitment_update.update_fee.is_none());
1003         check_added_monitors!(nodes[1], 1);
1004
1005         // Deliver (7)
1006         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
1007         check_added_monitors!(nodes[0], 1);
1008         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1009         // No commitment_signed so get_event_msg's assert(len == 1) passes
1010
1011         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
1012         check_added_monitors!(nodes[1], 1);
1013         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1014
1015         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
1016         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
1017         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
1018         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1019         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1020 }
1021
1022 #[test]
1023 fn fake_network_test() {
1024         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1025         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1026         let chanmon_cfgs = create_chanmon_cfgs(4);
1027         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1028         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1029         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1030
1031         // Create some initial channels
1032         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1033         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1034         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1035
1036         // Rebalance the network a bit by relaying one payment through all the channels...
1037         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1038         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1039         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1040         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1041
1042         // Send some more payments
1043         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1044         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1045         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1046
1047         // Test failure packets
1048         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1049         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1050
1051         // Add a new channel that skips 3
1052         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1053
1054         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1055         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1056         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1057         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1058         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1059         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1060         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1061
1062         // Do some rebalance loop payments, simultaneously
1063         let mut hops = Vec::with_capacity(3);
1064         hops.push(RouteHop {
1065                 pubkey: nodes[2].node.get_our_node_id(),
1066                 node_features: NodeFeatures::empty(),
1067                 short_channel_id: chan_2.0.contents.short_channel_id,
1068                 channel_features: ChannelFeatures::empty(),
1069                 fee_msat: 0,
1070                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1071                 maybe_announced_channel: true,
1072         });
1073         hops.push(RouteHop {
1074                 pubkey: nodes[3].node.get_our_node_id(),
1075                 node_features: NodeFeatures::empty(),
1076                 short_channel_id: chan_3.0.contents.short_channel_id,
1077                 channel_features: ChannelFeatures::empty(),
1078                 fee_msat: 0,
1079                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1080                 maybe_announced_channel: true,
1081         });
1082         hops.push(RouteHop {
1083                 pubkey: nodes[1].node.get_our_node_id(),
1084                 node_features: nodes[1].node.node_features(),
1085                 short_channel_id: chan_4.0.contents.short_channel_id,
1086                 channel_features: nodes[1].node.channel_features(),
1087                 fee_msat: 1000000,
1088                 cltv_expiry_delta: TEST_FINAL_CLTV,
1089                 maybe_announced_channel: true,
1090         });
1091         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;
1092         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;
1093         let payment_preimage_1 = send_along_route(&nodes[1],
1094                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1095                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1096
1097         let mut hops = Vec::with_capacity(3);
1098         hops.push(RouteHop {
1099                 pubkey: nodes[3].node.get_our_node_id(),
1100                 node_features: NodeFeatures::empty(),
1101                 short_channel_id: chan_4.0.contents.short_channel_id,
1102                 channel_features: ChannelFeatures::empty(),
1103                 fee_msat: 0,
1104                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1105                 maybe_announced_channel: true,
1106         });
1107         hops.push(RouteHop {
1108                 pubkey: nodes[2].node.get_our_node_id(),
1109                 node_features: NodeFeatures::empty(),
1110                 short_channel_id: chan_3.0.contents.short_channel_id,
1111                 channel_features: ChannelFeatures::empty(),
1112                 fee_msat: 0,
1113                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1114                 maybe_announced_channel: true,
1115         });
1116         hops.push(RouteHop {
1117                 pubkey: nodes[1].node.get_our_node_id(),
1118                 node_features: nodes[1].node.node_features(),
1119                 short_channel_id: chan_2.0.contents.short_channel_id,
1120                 channel_features: nodes[1].node.channel_features(),
1121                 fee_msat: 1000000,
1122                 cltv_expiry_delta: TEST_FINAL_CLTV,
1123                 maybe_announced_channel: true,
1124         });
1125         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;
1126         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;
1127         let payment_hash_2 = send_along_route(&nodes[1],
1128                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1129                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1130
1131         // Claim the rebalances...
1132         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1133         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1134
1135         // Close down the channels...
1136         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1137         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1138         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1139         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1140         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1141         check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1142         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1143         check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1144         check_closed_event!(nodes[3], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1145         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1146         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1147         check_closed_event!(nodes[3], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1148 }
1149
1150 #[test]
1151 fn holding_cell_htlc_counting() {
1152         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1153         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1154         // commitment dance rounds.
1155         let chanmon_cfgs = create_chanmon_cfgs(3);
1156         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1157         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1158         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1159         create_announced_chan_between_nodes(&nodes, 0, 1);
1160         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1161
1162         // Fetch a route in advance as we will be unable to once we're unable to send.
1163         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1164
1165         let mut payments = Vec::new();
1166         for _ in 0..50 {
1167                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1168                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1169                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1170                 payments.push((payment_preimage, payment_hash));
1171         }
1172         check_added_monitors!(nodes[1], 1);
1173
1174         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1175         assert_eq!(events.len(), 1);
1176         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1177         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1178
1179         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1180         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1181         // another HTLC.
1182         {
1183                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1184                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1185                         ), true, APIError::ChannelUnavailable { .. }, {});
1186                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1187         }
1188
1189         // This should also be true if we try to forward a payment.
1190         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1191         {
1192                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1193                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1194                 check_added_monitors!(nodes[0], 1);
1195         }
1196
1197         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1198         assert_eq!(events.len(), 1);
1199         let payment_event = SendEvent::from_event(events.pop().unwrap());
1200         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1201
1202         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1203         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1204         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1205         // fails), the second will process the resulting failure and fail the HTLC backward.
1206         expect_pending_htlcs_forwardable!(nodes[1]);
1207         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 }]);
1208         check_added_monitors!(nodes[1], 1);
1209
1210         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1211         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1212         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1213
1214         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1215
1216         // Now forward all the pending HTLCs and claim them back
1217         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1218         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1219         check_added_monitors!(nodes[2], 1);
1220
1221         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1222         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1223         check_added_monitors!(nodes[1], 1);
1224         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1225
1226         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1227         check_added_monitors!(nodes[1], 1);
1228         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1229
1230         for ref update in as_updates.update_add_htlcs.iter() {
1231                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1232         }
1233         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1234         check_added_monitors!(nodes[2], 1);
1235         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1236         check_added_monitors!(nodes[2], 1);
1237         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1238
1239         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1240         check_added_monitors!(nodes[1], 1);
1241         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1242         check_added_monitors!(nodes[1], 1);
1243         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1244
1245         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1246         check_added_monitors!(nodes[2], 1);
1247
1248         expect_pending_htlcs_forwardable!(nodes[2]);
1249
1250         let events = nodes[2].node.get_and_clear_pending_events();
1251         assert_eq!(events.len(), payments.len());
1252         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1253                 match event {
1254                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1255                                 assert_eq!(*payment_hash, *hash);
1256                         },
1257                         _ => panic!("Unexpected event"),
1258                 };
1259         }
1260
1261         for (preimage, _) in payments.drain(..) {
1262                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1263         }
1264
1265         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1266 }
1267
1268 #[test]
1269 fn duplicate_htlc_test() {
1270         // Test that we accept duplicate payment_hash HTLCs across the network and that
1271         // claiming/failing them are all separate and don't affect each other
1272         let chanmon_cfgs = create_chanmon_cfgs(6);
1273         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1274         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1275         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1276
1277         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1278         create_announced_chan_between_nodes(&nodes, 0, 3);
1279         create_announced_chan_between_nodes(&nodes, 1, 3);
1280         create_announced_chan_between_nodes(&nodes, 2, 3);
1281         create_announced_chan_between_nodes(&nodes, 3, 4);
1282         create_announced_chan_between_nodes(&nodes, 3, 5);
1283
1284         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1285
1286         *nodes[0].network_payment_count.borrow_mut() -= 1;
1287         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1288
1289         *nodes[0].network_payment_count.borrow_mut() -= 1;
1290         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1291
1292         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1293         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1294         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1295 }
1296
1297 #[test]
1298 fn test_duplicate_htlc_different_direction_onchain() {
1299         // Test that ChannelMonitor doesn't generate 2 preimage txn
1300         // when we have 2 HTLCs with same preimage that go across a node
1301         // in opposite directions, even with the same payment secret.
1302         let chanmon_cfgs = create_chanmon_cfgs(2);
1303         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1304         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1305         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1306
1307         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1308
1309         // balancing
1310         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1311
1312         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1313
1314         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1315         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1316         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1317
1318         // Provide preimage to node 0 by claiming payment
1319         nodes[0].node.claim_funds(payment_preimage);
1320         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1321         check_added_monitors!(nodes[0], 1);
1322
1323         // Broadcast node 1 commitment txn
1324         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1325
1326         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1327         let mut has_both_htlcs = 0; // check htlcs match ones committed
1328         for outp in remote_txn[0].output.iter() {
1329                 if outp.value.to_sat() == 800_000 / 1000 {
1330                         has_both_htlcs += 1;
1331                 } else if outp.value.to_sat() == 900_000 / 1000 {
1332                         has_both_htlcs += 1;
1333                 }
1334         }
1335         assert_eq!(has_both_htlcs, 2);
1336
1337         mine_transaction(&nodes[0], &remote_txn[0]);
1338         check_added_monitors!(nodes[0], 1);
1339         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1340         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1341
1342         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1343         assert_eq!(claim_txn.len(), 3);
1344
1345         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1346         check_spends!(claim_txn[1], remote_txn[0]);
1347         check_spends!(claim_txn[2], remote_txn[0]);
1348         let preimage_tx = &claim_txn[0];
1349         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1350                 (&claim_txn[1], &claim_txn[2])
1351         } else {
1352                 (&claim_txn[2], &claim_txn[1])
1353         };
1354
1355         assert_eq!(preimage_tx.input.len(), 1);
1356         assert_eq!(preimage_bump_tx.input.len(), 1);
1357
1358         assert_eq!(preimage_tx.input.len(), 1);
1359         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1360         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value.to_sat(), 800);
1361
1362         assert_eq!(timeout_tx.input.len(), 1);
1363         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1364         check_spends!(timeout_tx, remote_txn[0]);
1365         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value.to_sat(), 900);
1366
1367         let events = nodes[0].node.get_and_clear_pending_msg_events();
1368         assert_eq!(events.len(), 3);
1369         for e in events {
1370                 match e {
1371                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1372                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1373                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1374                                 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1375                         },
1376                         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, .. } } => {
1377                                 assert!(update_add_htlcs.is_empty());
1378                                 assert!(update_fail_htlcs.is_empty());
1379                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1380                                 assert!(update_fail_malformed_htlcs.is_empty());
1381                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1382                         },
1383                         _ => panic!("Unexpected event"),
1384                 }
1385         }
1386 }
1387
1388 #[test]
1389 fn test_basic_channel_reserve() {
1390         let chanmon_cfgs = create_chanmon_cfgs(2);
1391         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1392         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1393         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1394         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1395
1396         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1397         let channel_reserve = chan_stat.channel_reserve_msat;
1398
1399         // The 2* and +1 are for the fee spike reserve.
1400         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));
1401         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1402         let (mut route, our_payment_hash, _, our_payment_secret) =
1403                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1404         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1405         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1406                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1407         match err {
1408                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1409                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1410                         else { panic!("Unexpected error variant"); }
1411                 },
1412                 _ => panic!("Unexpected error variant"),
1413         }
1414         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1415
1416         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1417 }
1418
1419 #[test]
1420 fn test_fee_spike_violation_fails_htlc() {
1421         let chanmon_cfgs = create_chanmon_cfgs(2);
1422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1424         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1425         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1426
1427         let (mut route, payment_hash, _, payment_secret) =
1428                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1429         route.paths[0].hops[0].fee_msat += 1;
1430         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1431         let secp_ctx = Secp256k1::new();
1432         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1433
1434         let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;
1435
1436         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1437         let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1438         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1439                 3460001, &recipient_onion_fields, cur_height, &None).unwrap();
1440         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1441         let msg = msgs::UpdateAddHTLC {
1442                 channel_id: chan.2,
1443                 htlc_id: 0,
1444                 amount_msat: htlc_msat,
1445                 payment_hash: payment_hash,
1446                 cltv_expiry: htlc_cltv,
1447                 onion_routing_packet: onion_packet,
1448                 skimmed_fee_msat: None,
1449                 blinding_point: None,
1450         };
1451
1452         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1453
1454         // Now manually create the commitment_signed message corresponding to the update_add
1455         // nodes[0] just sent. In the code for construction of this message, "local" refers
1456         // to the sender of the message, and "remote" refers to the receiver.
1457
1458         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1459
1460         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1461
1462         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1463         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1464         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1465                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1466                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1467                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1468                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1469                 ).flatten().unwrap();
1470                 let chan_signer = local_chan.get_signer();
1471                 // Make the signer believe we validated another commitment, so we can release the secret
1472                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1473
1474                 let pubkeys = chan_signer.as_ref().pubkeys();
1475                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1476                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1477                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1478                  chan_signer.as_ref().pubkeys().funding_pubkey)
1479         };
1480         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1481                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1482                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1483                 let remote_chan = 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 chan_signer = remote_chan.get_signer();
1487                 let pubkeys = chan_signer.as_ref().pubkeys();
1488                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1489                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1490                  chan_signer.as_ref().pubkeys().funding_pubkey)
1491         };
1492
1493         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1494         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1495                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1496
1497         // Build the remote commitment transaction so we can sign it, and then later use the
1498         // signature for the commitment_signed message.
1499         let local_chan_balance = 1313;
1500
1501         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1502                 offered: false,
1503                 amount_msat: 3460001,
1504                 cltv_expiry: htlc_cltv,
1505                 payment_hash,
1506                 transaction_output_index: Some(1),
1507         };
1508
1509         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1510
1511         let res = {
1512                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1513                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1514                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1515                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1516                 ).flatten().unwrap();
1517                 let local_chan_signer = local_chan.get_signer();
1518                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1519                         commitment_number,
1520                         95000,
1521                         local_chan_balance,
1522                         local_funding, remote_funding,
1523                         commit_tx_keys.clone(),
1524                         feerate_per_kw,
1525                         &mut vec![(accepted_htlc_info, ())],
1526                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1527                 );
1528                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
1529         };
1530
1531         let commit_signed_msg = msgs::CommitmentSigned {
1532                 channel_id: chan.2,
1533                 signature: res.0,
1534                 htlc_signatures: res.1,
1535                 #[cfg(taproot)]
1536                 partial_signature_with_nonce: None,
1537         };
1538
1539         // Send the commitment_signed message to the nodes[1].
1540         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1541         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1542
1543         // Send the RAA to nodes[1].
1544         let raa_msg = msgs::RevokeAndACK {
1545                 channel_id: chan.2,
1546                 per_commitment_secret: local_secret,
1547                 next_per_commitment_point: next_local_point,
1548                 #[cfg(taproot)]
1549                 next_local_nonce: None,
1550         };
1551         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1552
1553         let events = nodes[1].node.get_and_clear_pending_msg_events();
1554         assert_eq!(events.len(), 1);
1555         // Make sure the HTLC failed in the way we expect.
1556         match events[0] {
1557                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1558                         assert_eq!(update_fail_htlcs.len(), 1);
1559                         update_fail_htlcs[0].clone()
1560                 },
1561                 _ => panic!("Unexpected event"),
1562         };
1563         nodes[1].logger.assert_log("lightning::ln::channel",
1564                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1565
1566         check_added_monitors!(nodes[1], 2);
1567 }
1568
1569 #[test]
1570 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1571         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1572         // Set the fee rate for the channel very high, to the point where the fundee
1573         // sending any above-dust amount would result in a channel reserve violation.
1574         // In this test we check that we would be prevented from sending an HTLC in
1575         // this situation.
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         let mut push_amt = 100_000_000;
1584         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1585
1586         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1587
1588         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1589
1590         // Fetch a route in advance as we will be unable to once we're unable to send.
1591         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1592         // Sending exactly enough to hit the reserve amount should be accepted
1593         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1594                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1595         }
1596
1597         // However one more HTLC should be significantly over the reserve amount and fail.
1598         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1599                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1600                 ), true, APIError::ChannelUnavailable { .. }, {});
1601         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1602 }
1603
1604 #[test]
1605 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1606         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1607         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1608         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1609         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1610         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1611         let default_config = UserConfig::default();
1612         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1613
1614         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1615         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1616         // transaction fee with 0 HTLCs (183 sats)).
1617         let mut push_amt = 100_000_000;
1618         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1619         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1620         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1621
1622         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1625         }
1626
1627         let (mut route, payment_hash, _, payment_secret) =
1628                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1629         route.paths[0].hops[0].fee_msat = 700_000;
1630         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1631         let secp_ctx = Secp256k1::new();
1632         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1633         let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;
1634         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1635         let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1636         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1637                 700_000, &recipient_onion_fields, cur_height, &None).unwrap();
1638         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1639         let msg = msgs::UpdateAddHTLC {
1640                 channel_id: chan.2,
1641                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1642                 amount_msat: htlc_msat,
1643                 payment_hash: payment_hash,
1644                 cltv_expiry: htlc_cltv,
1645                 onion_routing_packet: onion_packet,
1646                 skimmed_fee_msat: None,
1647                 blinding_point: None,
1648         };
1649
1650         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1651         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1652         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value", 3);
1653         assert_eq!(nodes[0].node.list_channels().len(), 0);
1654         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1655         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1656         check_added_monitors!(nodes[0], 1);
1657         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() },
1658                 [nodes[1].node.get_our_node_id()], 100000);
1659 }
1660
1661 #[test]
1662 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1663         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1664         // calculating our commitment transaction fee (this was previously broken).
1665         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1666         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1667
1668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1670         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1671         let default_config = UserConfig::default();
1672         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1673
1674         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1675         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1676         // transaction fee with 0 HTLCs (183 sats)).
1677         let mut push_amt = 100_000_000;
1678         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1679         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1680         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1681
1682         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1683                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1684         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1685         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1686         // commitment transaction fee.
1687         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1688
1689         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1690         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1691                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1692         }
1693
1694         // One more than the dust amt should fail, however.
1695         let (mut route, our_payment_hash, _, our_payment_secret) =
1696                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1697         route.paths[0].hops[0].fee_msat += 1;
1698         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1699                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1700                 ), true, APIError::ChannelUnavailable { .. }, {});
1701 }
1702
1703 #[test]
1704 fn test_chan_init_feerate_unaffordability() {
1705         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1706         // channel reserve and feerate requirements.
1707         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1708         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1709         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1710         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1711         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1712         let default_config = UserConfig::default();
1713         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1714
1715         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1716         // HTLC.
1717         let mut push_amt = 100_000_000;
1718         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1719         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1720                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1721
1722         // During open, we don't have a "counterparty channel reserve" to check against, so that
1723         // requirement only comes into play on the open_channel handling side.
1724         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1725         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1726         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1727         open_channel_msg.push_msat += 1;
1728         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1729
1730         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1731         assert_eq!(msg_events.len(), 1);
1732         match msg_events[0] {
1733                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1734                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1735                 },
1736                 _ => panic!("Unexpected event"),
1737         }
1738 }
1739
1740 #[test]
1741 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1742         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1743         // calculating our counterparty's commitment transaction fee (this was previously broken).
1744         let chanmon_cfgs = create_chanmon_cfgs(2);
1745         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1746         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1747         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1748         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1749
1750         let payment_amt = 46000; // Dust amount
1751         // In the previous code, these first four payments would succeed.
1752         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1753         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1754         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1755         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1756
1757         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1758         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1759         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1760         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1761         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1762         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1763
1764         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1765         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1766         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1767         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1768 }
1769
1770 #[test]
1771 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1772         let chanmon_cfgs = create_chanmon_cfgs(3);
1773         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1774         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1775         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1776         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1777         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1778
1779         let feemsat = 239;
1780         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1781         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1782         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1783         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1784
1785         // Add a 2* and +1 for the fee spike reserve.
1786         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1787         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;
1788         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1789
1790         // Add a pending HTLC.
1791         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1792         let payment_event_1 = {
1793                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1794                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1795                 check_added_monitors!(nodes[0], 1);
1796
1797                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1798                 assert_eq!(events.len(), 1);
1799                 SendEvent::from_event(events.remove(0))
1800         };
1801         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1802
1803         // Attempt to trigger a channel reserve violation --> payment failure.
1804         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1805         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;
1806         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1807         let mut route_2 = route_1.clone();
1808         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1809
1810         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1811         let secp_ctx = Secp256k1::new();
1812         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1813         let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
1814         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1815         let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
1816         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1817                 &route_2.paths[0], recv_value_2, &recipient_onion_fields, cur_height, &None).unwrap();
1818         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1819         let msg = msgs::UpdateAddHTLC {
1820                 channel_id: chan.2,
1821                 htlc_id: 1,
1822                 amount_msat: htlc_msat + 1,
1823                 payment_hash: our_payment_hash_1,
1824                 cltv_expiry: htlc_cltv,
1825                 onion_routing_packet: onion_packet,
1826                 skimmed_fee_msat: None,
1827                 blinding_point: None,
1828         };
1829
1830         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1831         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1832         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value", 3);
1833         assert_eq!(nodes[1].node.list_channels().len(), 1);
1834         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1835         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1836         check_added_monitors!(nodes[1], 1);
1837         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1838                 [nodes[0].node.get_our_node_id()], 100000);
1839 }
1840
1841 #[test]
1842 fn test_inbound_outbound_capacity_is_not_zero() {
1843         let chanmon_cfgs = create_chanmon_cfgs(2);
1844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1846         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1847         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1848         let channels0 = node_chanmgrs[0].list_channels();
1849         let channels1 = node_chanmgrs[1].list_channels();
1850         let default_config = UserConfig::default();
1851         assert_eq!(channels0.len(), 1);
1852         assert_eq!(channels1.len(), 1);
1853
1854         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1855         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1856         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1857
1858         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1859         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1860 }
1861
1862 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1863         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1864 }
1865
1866 #[test]
1867 fn test_channel_reserve_holding_cell_htlcs() {
1868         let chanmon_cfgs = create_chanmon_cfgs(3);
1869         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1870         // When this test was written, the default base fee floated based on the HTLC count.
1871         // It is now fixed, so we simply set the fee to the expected value here.
1872         let mut config = test_default_channel_config();
1873         config.channel_config.forwarding_fee_base_msat = 239;
1874         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1875         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1876         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1877         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1878
1879         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1880         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1881
1882         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1883         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1884
1885         macro_rules! expect_forward {
1886                 ($node: expr) => {{
1887                         let mut events = $node.node.get_and_clear_pending_msg_events();
1888                         assert_eq!(events.len(), 1);
1889                         check_added_monitors!($node, 1);
1890                         let payment_event = SendEvent::from_event(events.remove(0));
1891                         payment_event
1892                 }}
1893         }
1894
1895         let feemsat = 239; // set above
1896         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1897         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1898         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1899
1900         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1901
1902         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1903         {
1904                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1905                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1906                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1907                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1908                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1909
1910                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1911                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1912                         ), true, APIError::ChannelUnavailable { .. }, {});
1913                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914         }
1915
1916         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1917         // nodes[0]'s wealth
1918         loop {
1919                 let amt_msat = recv_value_0 + total_fee_msat;
1920                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1921                 // Also, ensure that each payment has enough to be over the dust limit to
1922                 // ensure it'll be included in each commit tx fee calculation.
1923                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1924                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1925                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1926                         break;
1927                 }
1928
1929                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1930                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1931                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1932                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1933                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1934
1935                 let (stat01_, stat11_, stat12_, stat22_) = (
1936                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1937                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1938                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1939                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1940                 );
1941
1942                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1943                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1944                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1945                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1946                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1947         }
1948
1949         // adding pending output.
1950         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1951         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1952         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1953         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1954         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1955         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1956         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1957         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1958         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1959         // policy.
1960         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1961         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1962         let amt_msat_1 = recv_value_1 + total_fee_msat;
1963
1964         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);
1965         let payment_event_1 = {
1966                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1967                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1968                 check_added_monitors!(nodes[0], 1);
1969
1970                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1971                 assert_eq!(events.len(), 1);
1972                 SendEvent::from_event(events.remove(0))
1973         };
1974         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1975
1976         // channel reserve test with htlc pending output > 0
1977         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1978         {
1979                 let mut route = route_1.clone();
1980                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1981                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1982                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1983                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1984                         ), true, APIError::ChannelUnavailable { .. }, {});
1985                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1986         }
1987
1988         // split the rest to test holding cell
1989         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1990         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1991         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1992         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1993         {
1994                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1995                 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);
1996         }
1997
1998         // now see if they go through on both sides
1999         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);
2000         // but this will stuck in the holding cell
2001         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
2002                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
2003         check_added_monitors!(nodes[0], 0);
2004         let events = nodes[0].node.get_and_clear_pending_events();
2005         assert_eq!(events.len(), 0);
2006
2007         // test with outbound holding cell amount > 0
2008         {
2009                 let (mut route, our_payment_hash, _, our_payment_secret) =
2010                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
2011                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
2012                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
2013                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
2014                         ), true, APIError::ChannelUnavailable { .. }, {});
2015                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2016         }
2017
2018         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);
2019         // this will also stuck in the holding cell
2020         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
2021                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
2022         check_added_monitors!(nodes[0], 0);
2023         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2024         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2025
2026         // flush the pending htlc
2027         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2028         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2029         check_added_monitors!(nodes[1], 1);
2030
2031         // the pending htlc should be promoted to committed
2032         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2033         check_added_monitors!(nodes[0], 1);
2034         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2035
2036         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2037         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2038         // No commitment_signed so get_event_msg's assert(len == 1) passes
2039         check_added_monitors!(nodes[0], 1);
2040
2041         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2042         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2043         check_added_monitors!(nodes[1], 1);
2044
2045         expect_pending_htlcs_forwardable!(nodes[1]);
2046
2047         let ref payment_event_11 = expect_forward!(nodes[1]);
2048         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2049         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2050
2051         expect_pending_htlcs_forwardable!(nodes[2]);
2052         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2053
2054         // flush the htlcs in the holding cell
2055         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2056         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2057         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2058         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2059         expect_pending_htlcs_forwardable!(nodes[1]);
2060
2061         let ref payment_event_3 = expect_forward!(nodes[1]);
2062         assert_eq!(payment_event_3.msgs.len(), 2);
2063         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2064         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2065
2066         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2067         expect_pending_htlcs_forwardable!(nodes[2]);
2068
2069         let events = nodes[2].node.get_and_clear_pending_events();
2070         assert_eq!(events.len(), 2);
2071         match events[0] {
2072                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2073                         assert_eq!(our_payment_hash_21, *payment_hash);
2074                         assert_eq!(recv_value_21, amount_msat);
2075                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2076                         assert_eq!(via_channel_id, Some(chan_2.2));
2077                         match &purpose {
2078                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
2079                                         assert!(payment_preimage.is_none());
2080                                         assert_eq!(our_payment_secret_21, *payment_secret);
2081                                 },
2082                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
2083                         }
2084                 },
2085                 _ => panic!("Unexpected event"),
2086         }
2087         match events[1] {
2088                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2089                         assert_eq!(our_payment_hash_22, *payment_hash);
2090                         assert_eq!(recv_value_22, amount_msat);
2091                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2092                         assert_eq!(via_channel_id, Some(chan_2.2));
2093                         match &purpose {
2094                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
2095                                         assert!(payment_preimage.is_none());
2096                                         assert_eq!(our_payment_secret_22, *payment_secret);
2097                                 },
2098                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
2099                         }
2100                 },
2101                 _ => panic!("Unexpected event"),
2102         }
2103
2104         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2105         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2106         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2107
2108         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2109         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2110         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2111
2112         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2113         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);
2114         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2115         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2116         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2117
2118         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2119         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2120 }
2121
2122 #[test]
2123 fn channel_reserve_in_flight_removes() {
2124         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2125         // can send to its counterparty, but due to update ordering, the other side may not yet have
2126         // considered those HTLCs fully removed.
2127         // This tests that we don't count HTLCs which will not be included in the next remote
2128         // commitment transaction towards the reserve value (as it implies no commitment transaction
2129         // will be generated which violates the remote reserve value).
2130         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2131         // To test this we:
2132         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2133         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2134         //    you only consider the value of the first HTLC, it may not),
2135         //  * start routing a third HTLC from A to B,
2136         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2137         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2138         //  * deliver the first fulfill from B
2139         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2140         //    claim,
2141         //  * deliver A's response CS and RAA.
2142         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2143         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2144         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2145         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2146         let chanmon_cfgs = create_chanmon_cfgs(2);
2147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2149         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2150         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2151
2152         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2153         // Route the first two HTLCs.
2154         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2155         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2156         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2157
2158         // Start routing the third HTLC (this is just used to get everyone in the right state).
2159         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2160         let send_1 = {
2161                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2162                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2163                 check_added_monitors!(nodes[0], 1);
2164                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2165                 assert_eq!(events.len(), 1);
2166                 SendEvent::from_event(events.remove(0))
2167         };
2168
2169         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2170         // initial fulfill/CS.
2171         nodes[1].node.claim_funds(payment_preimage_1);
2172         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2173         check_added_monitors!(nodes[1], 1);
2174         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2175
2176         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2177         // remove the second HTLC when we send the HTLC back from B to A.
2178         nodes[1].node.claim_funds(payment_preimage_2);
2179         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2180         check_added_monitors!(nodes[1], 1);
2181         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2182
2183         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2184         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2185         check_added_monitors!(nodes[0], 1);
2186         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2187         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2188
2189         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2190         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2191         check_added_monitors!(nodes[1], 1);
2192         // B is already AwaitingRAA, so cant generate a CS here
2193         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2194
2195         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2196         check_added_monitors!(nodes[1], 1);
2197         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2198
2199         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2200         check_added_monitors!(nodes[0], 1);
2201         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2202
2203         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2204         check_added_monitors!(nodes[1], 1);
2205         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2206
2207         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2208         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2209         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2210         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2211         // on-chain as necessary).
2212         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2213         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2214         check_added_monitors!(nodes[0], 1);
2215         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2216         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2217
2218         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2219         check_added_monitors!(nodes[1], 1);
2220         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2221
2222         expect_pending_htlcs_forwardable!(nodes[1]);
2223         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2224
2225         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2226         // resolve the second HTLC from A's point of view.
2227         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2228         check_added_monitors!(nodes[0], 1);
2229         expect_payment_path_successful!(nodes[0]);
2230         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2231
2232         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2233         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2234         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2235         let send_2 = {
2236                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2237                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2238                 check_added_monitors!(nodes[1], 1);
2239                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2240                 assert_eq!(events.len(), 1);
2241                 SendEvent::from_event(events.remove(0))
2242         };
2243
2244         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2245         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2246         check_added_monitors!(nodes[0], 1);
2247         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2248
2249         // Now just resolve all the outstanding messages/HTLCs for completeness...
2250
2251         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2252         check_added_monitors!(nodes[1], 1);
2253         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2254
2255         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2256         check_added_monitors!(nodes[1], 1);
2257
2258         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2259         check_added_monitors!(nodes[0], 1);
2260         expect_payment_path_successful!(nodes[0]);
2261         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2262
2263         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2264         check_added_monitors!(nodes[1], 1);
2265         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2266
2267         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2268         check_added_monitors!(nodes[0], 1);
2269
2270         expect_pending_htlcs_forwardable!(nodes[0]);
2271         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2272
2273         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2274         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2275 }
2276
2277 #[test]
2278 fn channel_monitor_network_test() {
2279         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2280         // tests that ChannelMonitor is able to recover from various states.
2281         let chanmon_cfgs = create_chanmon_cfgs(5);
2282         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2283         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2284         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2285
2286         // Create some initial channels
2287         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2288         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2289         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2290         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2291
2292         // Make sure all nodes are at the same starting height
2293         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2294         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2295         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2296         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2297         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2298
2299         // Rebalance the network a bit by relaying one payment through all the channels...
2300         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2301         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2302         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2303         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2304
2305         // Simple case with no pending HTLCs:
2306         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2307         check_added_monitors!(nodes[1], 1);
2308         check_closed_broadcast!(nodes[1], true);
2309         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2310         {
2311                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2312                 assert_eq!(node_txn.len(), 1);
2313                 mine_transaction(&nodes[1], &node_txn[0]);
2314                 if nodes[1].connect_style.borrow().updates_best_block_first() {
2315                         let _ = nodes[1].tx_broadcaster.txn_broadcast();
2316                 }
2317
2318                 mine_transaction(&nodes[0], &node_txn[0]);
2319                 check_added_monitors!(nodes[0], 1);
2320                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2321         }
2322         check_closed_broadcast!(nodes[0], true);
2323         assert_eq!(nodes[0].node.list_channels().len(), 0);
2324         assert_eq!(nodes[1].node.list_channels().len(), 1);
2325         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2326
2327         // One pending HTLC is discarded by the force-close:
2328         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2329
2330         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2331         // broadcasted until we reach the timelock time).
2332         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2333         check_closed_broadcast!(nodes[1], true);
2334         check_added_monitors!(nodes[1], 1);
2335         {
2336                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2337                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2338                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2339                 mine_transaction(&nodes[2], &node_txn[0]);
2340                 check_added_monitors!(nodes[2], 1);
2341                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2342         }
2343         check_closed_broadcast!(nodes[2], true);
2344         assert_eq!(nodes[1].node.list_channels().len(), 0);
2345         assert_eq!(nodes[2].node.list_channels().len(), 1);
2346         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2347         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2348
2349         macro_rules! claim_funds {
2350                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2351                         {
2352                                 $node.node.claim_funds($preimage);
2353                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2354                                 check_added_monitors!($node, 1);
2355
2356                                 let events = $node.node.get_and_clear_pending_msg_events();
2357                                 assert_eq!(events.len(), 1);
2358                                 match events[0] {
2359                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2360                                                 assert!(update_add_htlcs.is_empty());
2361                                                 assert!(update_fail_htlcs.is_empty());
2362                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2363                                         },
2364                                         _ => panic!("Unexpected event"),
2365                                 };
2366                         }
2367                 }
2368         }
2369
2370         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2371         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2372         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2373         check_added_monitors!(nodes[2], 1);
2374         check_closed_broadcast!(nodes[2], true);
2375         let node2_commitment_txid;
2376         {
2377                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2378                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2379                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2380                 node2_commitment_txid = node_txn[0].txid();
2381
2382                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2383                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2384                 mine_transaction(&nodes[3], &node_txn[0]);
2385                 check_added_monitors!(nodes[3], 1);
2386                 check_preimage_claim(&nodes[3], &node_txn);
2387         }
2388         check_closed_broadcast!(nodes[3], true);
2389         assert_eq!(nodes[2].node.list_channels().len(), 0);
2390         assert_eq!(nodes[3].node.list_channels().len(), 1);
2391         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2392         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2393
2394         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2395         // confusing us in the following tests.
2396         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2397
2398         // One pending HTLC to time out:
2399         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2400         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2401         // buffer space).
2402
2403         let (close_chan_update_1, close_chan_update_2) = {
2404                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2405                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2406                 assert_eq!(events.len(), 2);
2407                 let close_chan_update_1 = match events[1] {
2408                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2409                                 msg.clone()
2410                         },
2411                         _ => panic!("Unexpected event"),
2412                 };
2413                 match events[0] {
2414                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2415                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2416                         },
2417                         _ => panic!("Unexpected event"),
2418                 }
2419                 check_added_monitors!(nodes[3], 1);
2420
2421                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2422                 {
2423                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2424                         node_txn.retain(|tx| {
2425                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2426                                         false
2427                                 } else { true }
2428                         });
2429                 }
2430
2431                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2432
2433                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2434                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2435
2436                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2437                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2438                 assert_eq!(events.len(), 2);
2439                 let close_chan_update_2 = match events[1] {
2440                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2441                                 msg.clone()
2442                         },
2443                         _ => panic!("Unexpected event"),
2444                 };
2445                 match events[0] {
2446                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2447                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2448                         },
2449                         _ => panic!("Unexpected event"),
2450                 }
2451                 check_added_monitors!(nodes[4], 1);
2452                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2453                 check_closed_event!(nodes[4], 1, ClosureReason::HTLCsTimedOut, [nodes[3].node.get_our_node_id()], 100000);
2454
2455                 mine_transaction(&nodes[4], &node_txn[0]);
2456                 check_preimage_claim(&nodes[4], &node_txn);
2457                 (close_chan_update_1, close_chan_update_2)
2458         };
2459         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2460         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2461         assert_eq!(nodes[3].node.list_channels().len(), 0);
2462         assert_eq!(nodes[4].node.list_channels().len(), 0);
2463
2464         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2465                 Ok(ChannelMonitorUpdateStatus::Completed));
2466         check_closed_event!(nodes[3], 1, ClosureReason::HTLCsTimedOut, [nodes[4].node.get_our_node_id()], 100000);
2467 }
2468
2469 #[test]
2470 fn test_justice_tx_htlc_timeout() {
2471         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2472         let mut alice_config = test_default_channel_config();
2473         alice_config.channel_handshake_config.announced_channel = true;
2474         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2475         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2476         let mut bob_config = test_default_channel_config();
2477         bob_config.channel_handshake_config.announced_channel = true;
2478         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2479         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2480         let user_cfgs = [Some(alice_config), Some(bob_config)];
2481         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2482         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2483         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2484         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2485         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2486         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2487         // Create some new channels:
2488         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2489
2490         // A pending HTLC which will be revoked:
2491         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2492         // Get the will-be-revoked local txn from nodes[0]
2493         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2494         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2495         assert_eq!(revoked_local_txn[0].input.len(), 1);
2496         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2497         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2498         assert_eq!(revoked_local_txn[1].input.len(), 1);
2499         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2500         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2501         // Revoke the old state
2502         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2503
2504         {
2505                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2506                 {
2507                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2508                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2509                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2510                         check_spends!(node_txn[0], revoked_local_txn[0]);
2511                         node_txn.swap_remove(0);
2512                 }
2513                 check_added_monitors!(nodes[1], 1);
2514                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2515                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2516
2517                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2518                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2519                 // Verify broadcast of revoked HTLC-timeout
2520                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2521                 check_added_monitors!(nodes[0], 1);
2522                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2523                 // Broadcast revoked HTLC-timeout on node 1
2524                 mine_transaction(&nodes[1], &node_txn[1]);
2525                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2526         }
2527         get_announce_close_broadcast_events(&nodes, 0, 1);
2528         assert_eq!(nodes[0].node.list_channels().len(), 0);
2529         assert_eq!(nodes[1].node.list_channels().len(), 0);
2530 }
2531
2532 #[test]
2533 fn test_justice_tx_htlc_success() {
2534         // Test justice txn built on revoked HTLC-Success tx, against both sides
2535         let mut alice_config = test_default_channel_config();
2536         alice_config.channel_handshake_config.announced_channel = true;
2537         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2538         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2539         let mut bob_config = test_default_channel_config();
2540         bob_config.channel_handshake_config.announced_channel = true;
2541         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2542         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2543         let user_cfgs = [Some(alice_config), Some(bob_config)];
2544         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2545         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2546         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2549         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2550         // Create some new channels:
2551         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2552
2553         // A pending HTLC which will be revoked:
2554         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2555         // Get the will-be-revoked local txn from B
2556         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2557         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2558         assert_eq!(revoked_local_txn[0].input.len(), 1);
2559         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2560         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2561         // Revoke the old state
2562         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2563         {
2564                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2565                 {
2566                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2567                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2568                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2569
2570                         check_spends!(node_txn[0], revoked_local_txn[0]);
2571                         node_txn.swap_remove(0);
2572                 }
2573                 check_added_monitors!(nodes[0], 1);
2574                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2575
2576                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2577                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2578                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2579                 check_added_monitors!(nodes[1], 1);
2580                 mine_transaction(&nodes[0], &node_txn[1]);
2581                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2582                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2583         }
2584         get_announce_close_broadcast_events(&nodes, 0, 1);
2585         assert_eq!(nodes[0].node.list_channels().len(), 0);
2586         assert_eq!(nodes[1].node.list_channels().len(), 0);
2587 }
2588
2589 #[test]
2590 fn revoked_output_claim() {
2591         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2592         // transaction is broadcast by its counterparty
2593         let chanmon_cfgs = create_chanmon_cfgs(2);
2594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2596         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2597         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2598         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2599         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2600         assert_eq!(revoked_local_txn.len(), 1);
2601         // Only output is the full channel value back to nodes[0]:
2602         assert_eq!(revoked_local_txn[0].output.len(), 1);
2603         // Send a payment through, updating everyone's latest commitment txn
2604         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2605
2606         // Inform nodes[1] that nodes[0] broadcast a stale tx
2607         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2608         check_added_monitors!(nodes[1], 1);
2609         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2610         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2611         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2612
2613         check_spends!(node_txn[0], revoked_local_txn[0]);
2614
2615         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2616         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2617         get_announce_close_broadcast_events(&nodes, 0, 1);
2618         check_added_monitors!(nodes[0], 1);
2619         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2620 }
2621
2622 #[test]
2623 fn test_forming_justice_tx_from_monitor_updates() {
2624         do_test_forming_justice_tx_from_monitor_updates(true);
2625         do_test_forming_justice_tx_from_monitor_updates(false);
2626 }
2627
2628 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2629         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2630         // is properly formed and can be broadcasted/confirmed successfully in the event
2631         // that a revoked commitment transaction is broadcasted
2632         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2633         let chanmon_cfgs = create_chanmon_cfgs(2);
2634         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2635         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2636         let persisters = vec![WatchtowerPersister::new(destination_script0),
2637                 WatchtowerPersister::new(destination_script1)];
2638         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2640         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2641         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2642         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2643
2644         if !broadcast_initial_commitment {
2645                 // Send a payment to move the channel forward
2646                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2647         }
2648
2649         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2650         // We'll keep this commitment transaction to broadcast once it's revoked.
2651         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2652         assert_eq!(revoked_local_txn.len(), 1);
2653         let revoked_commitment_tx = &revoked_local_txn[0];
2654
2655         // Send another payment, now revoking the previous commitment tx
2656         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2657
2658         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2659         check_spends!(justice_tx, revoked_commitment_tx);
2660
2661         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2662         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2663
2664         check_added_monitors!(nodes[1], 1);
2665         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2666                 &[nodes[0].node.get_our_node_id()], 100_000);
2667         get_announce_close_broadcast_events(&nodes, 1, 0);
2668
2669         check_added_monitors!(nodes[0], 1);
2670         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2671                 &[nodes[1].node.get_our_node_id()], 100_000);
2672
2673         // Check that the justice tx has sent the revoked output value to nodes[1]
2674         let monitor = get_monitor!(nodes[1], channel_id);
2675         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2676                 match balance {
2677                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2678                         _ => panic!("Unexpected balance type"),
2679                 }
2680         });
2681         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2682         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value.to_sat() };
2683         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value.to_sat();
2684         assert_eq!(total_claimable_balance, expected_claimable_balance);
2685 }
2686
2687
2688 #[test]
2689 fn claim_htlc_outputs_shared_tx() {
2690         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2691         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2692         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2693         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2694         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2695         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2696
2697         // Create some new channel:
2698         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2699
2700         // Rebalance the network to generate htlc in the two directions
2701         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2702         // 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
2703         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2704         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2705
2706         // Get the will-be-revoked local txn from node[0]
2707         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2708         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2709         assert_eq!(revoked_local_txn[0].input.len(), 1);
2710         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2711         assert_eq!(revoked_local_txn[1].input.len(), 1);
2712         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2713         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2714         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2715
2716         //Revoke the old state
2717         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2718
2719         {
2720                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2721                 check_added_monitors!(nodes[0], 1);
2722                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2723                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2724                 check_added_monitors!(nodes[1], 1);
2725                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2726                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2727                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2728
2729                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2730                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2731
2732                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2733                 check_spends!(node_txn[0], revoked_local_txn[0]);
2734
2735                 let mut witness_lens = BTreeSet::new();
2736                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2737                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2738                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2739                 assert_eq!(witness_lens.len(), 3);
2740                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2741                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2742                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2743
2744                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2745                 // ANTI_REORG_DELAY confirmations.
2746                 mine_transaction(&nodes[1], &node_txn[0]);
2747                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2748                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2749         }
2750         get_announce_close_broadcast_events(&nodes, 0, 1);
2751         assert_eq!(nodes[0].node.list_channels().len(), 0);
2752         assert_eq!(nodes[1].node.list_channels().len(), 0);
2753 }
2754
2755 #[test]
2756 fn claim_htlc_outputs_single_tx() {
2757         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2758         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2759         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2762         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2763
2764         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2765
2766         // Rebalance the network to generate htlc in the two directions
2767         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2768         // 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
2769         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2770         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2771         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2772
2773         // Get the will-be-revoked local txn from node[0]
2774         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2775
2776         //Revoke the old state
2777         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2778
2779         {
2780                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2781                 check_added_monitors!(nodes[0], 1);
2782                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2783                 check_added_monitors!(nodes[1], 1);
2784                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2785                 let mut events = nodes[0].node.get_and_clear_pending_events();
2786                 expect_pending_htlcs_forwardable_conditions(events[0..2].to_vec(), &[HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
2787                 match events.last().unwrap() {
2788                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2789                         _ => panic!("Unexpected event"),
2790                 }
2791
2792                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2793                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2794
2795                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2796
2797                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2798                 assert_eq!(node_txn[0].input.len(), 1);
2799                 check_spends!(node_txn[0], chan_1.3);
2800                 assert_eq!(node_txn[1].input.len(), 1);
2801                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2802                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2803                 check_spends!(node_txn[1], node_txn[0]);
2804
2805                 // Filter out any non justice transactions.
2806                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2807                 assert!(node_txn.len() > 3);
2808
2809                 assert_eq!(node_txn[0].input.len(), 1);
2810                 assert_eq!(node_txn[1].input.len(), 1);
2811                 assert_eq!(node_txn[2].input.len(), 1);
2812
2813                 check_spends!(node_txn[0], revoked_local_txn[0]);
2814                 check_spends!(node_txn[1], revoked_local_txn[0]);
2815                 check_spends!(node_txn[2], revoked_local_txn[0]);
2816
2817                 let mut witness_lens = BTreeSet::new();
2818                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2819                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2820                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2821                 assert_eq!(witness_lens.len(), 3);
2822                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2823                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2824                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2825
2826                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2827                 // ANTI_REORG_DELAY confirmations.
2828                 mine_transaction(&nodes[1], &node_txn[0]);
2829                 mine_transaction(&nodes[1], &node_txn[1]);
2830                 mine_transaction(&nodes[1], &node_txn[2]);
2831                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2832                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2833         }
2834         get_announce_close_broadcast_events(&nodes, 0, 1);
2835         assert_eq!(nodes[0].node.list_channels().len(), 0);
2836         assert_eq!(nodes[1].node.list_channels().len(), 0);
2837 }
2838
2839 #[test]
2840 fn test_htlc_on_chain_success() {
2841         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2842         // the preimage backward accordingly. So here we test that ChannelManager is
2843         // broadcasting the right event to other nodes in payment path.
2844         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2845         // A --------------------> B ----------------------> C (preimage)
2846         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2847         // commitment transaction was broadcast.
2848         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2849         // towards B.
2850         // B should be able to claim via preimage if A then broadcasts its local tx.
2851         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2852         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2853         // PaymentSent event).
2854
2855         let chanmon_cfgs = create_chanmon_cfgs(3);
2856         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2857         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2858         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2859
2860         // Create some initial channels
2861         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2862         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2863
2864         // Ensure all nodes are at the same height
2865         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2866         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2867         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2868         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2869
2870         // Rebalance the network a bit by relaying one payment through all the channels...
2871         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2872         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2873
2874         let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2875         let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2876
2877         // Broadcast legit commitment tx from C on B's chain
2878         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2879         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2880         assert_eq!(commitment_tx.len(), 1);
2881         check_spends!(commitment_tx[0], chan_2.3);
2882         nodes[2].node.claim_funds(our_payment_preimage);
2883         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2884         nodes[2].node.claim_funds(our_payment_preimage_2);
2885         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2886         check_added_monitors!(nodes[2], 2);
2887         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2888         assert!(updates.update_add_htlcs.is_empty());
2889         assert!(updates.update_fail_htlcs.is_empty());
2890         assert!(updates.update_fail_malformed_htlcs.is_empty());
2891         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2892
2893         mine_transaction(&nodes[2], &commitment_tx[0]);
2894         check_closed_broadcast!(nodes[2], true);
2895         check_added_monitors!(nodes[2], 1);
2896         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2897         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2898         assert_eq!(node_txn.len(), 2);
2899         check_spends!(node_txn[0], commitment_tx[0]);
2900         check_spends!(node_txn[1], commitment_tx[0]);
2901         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2902         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2903         assert!(node_txn[0].output[0].script_pubkey.is_p2wsh()); // revokeable output
2904         assert!(node_txn[1].output[0].script_pubkey.is_p2wsh()); // revokeable output
2905         assert_eq!(node_txn[0].lock_time, LockTime::ZERO);
2906         assert_eq!(node_txn[1].lock_time, LockTime::ZERO);
2907
2908         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2909         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()]));
2910         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2911         {
2912                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2913                 assert_eq!(added_monitors.len(), 1);
2914                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2915                 added_monitors.clear();
2916         }
2917         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2918         assert_eq!(forwarded_events.len(), 3);
2919         match forwarded_events[0] {
2920                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2921                 _ => panic!("Unexpected event"),
2922         }
2923         let chan_id = Some(chan_1.2);
2924         match forwarded_events[1] {
2925                 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2926                         next_channel_id, outbound_amount_forwarded_msat, ..
2927                 } => {
2928                         assert_eq!(total_fee_earned_msat, Some(1000));
2929                         assert_eq!(prev_channel_id, chan_id);
2930                         assert_eq!(claim_from_onchain_tx, true);
2931                         assert_eq!(next_channel_id, Some(chan_2.2));
2932                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2933                 },
2934                 _ => panic!()
2935         }
2936         match forwarded_events[2] {
2937                 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2938                         next_channel_id, outbound_amount_forwarded_msat, ..
2939                 } => {
2940                         assert_eq!(total_fee_earned_msat, Some(1000));
2941                         assert_eq!(prev_channel_id, chan_id);
2942                         assert_eq!(claim_from_onchain_tx, true);
2943                         assert_eq!(next_channel_id, Some(chan_2.2));
2944                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2945                 },
2946                 _ => panic!()
2947         }
2948         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2949         {
2950                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2951                 assert_eq!(added_monitors.len(), 2);
2952                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2953                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2954                 added_monitors.clear();
2955         }
2956         assert_eq!(events.len(), 3);
2957
2958         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2959         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2960
2961         match nodes_2_event {
2962                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2963                 _ => panic!("Unexpected event"),
2964         }
2965
2966         match nodes_0_event {
2967                 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, .. } } => {
2968                         assert!(update_add_htlcs.is_empty());
2969                         assert!(update_fail_htlcs.is_empty());
2970                         assert_eq!(update_fulfill_htlcs.len(), 1);
2971                         assert!(update_fail_malformed_htlcs.is_empty());
2972                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2973                 },
2974                 _ => panic!("Unexpected event"),
2975         };
2976
2977         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2978         match events[0] {
2979                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2980                 _ => panic!("Unexpected event"),
2981         }
2982
2983         macro_rules! check_tx_local_broadcast {
2984                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2985                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2986                         assert_eq!(node_txn.len(), 2);
2987                         // Node[1]: 2 * HTLC-timeout tx
2988                         // Node[0]: 2 * HTLC-timeout tx
2989                         check_spends!(node_txn[0], $commitment_tx);
2990                         check_spends!(node_txn[1], $commitment_tx);
2991                         assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2992                         assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2993                         if $htlc_offered {
2994                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2995                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2996                                 assert!(node_txn[0].output[0].script_pubkey.is_p2wsh()); // revokeable output
2997                                 assert!(node_txn[1].output[0].script_pubkey.is_p2wsh()); // revokeable output
2998                         } else {
2999                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3000                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3001                                 assert!(node_txn[0].output[0].script_pubkey.is_p2wpkh()); // direct payment
3002                                 assert!(node_txn[1].output[0].script_pubkey.is_p2wpkh()); // direct payment
3003                         }
3004                         node_txn.clear();
3005                 } }
3006         }
3007         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
3008         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
3009
3010         // Broadcast legit commitment tx from A on B's chain
3011         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
3012         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
3013         check_spends!(node_a_commitment_tx[0], chan_1.3);
3014         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
3015         check_closed_broadcast!(nodes[1], true);
3016         check_added_monitors!(nodes[1], 1);
3017         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3018         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3019         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
3020         let commitment_spend =
3021                 if node_txn.len() == 1 {
3022                         &node_txn[0]
3023                 } else {
3024                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
3025                         // FullBlockViaListen
3026                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
3027                                 check_spends!(node_txn[1], commitment_tx[0]);
3028                                 check_spends!(node_txn[2], commitment_tx[0]);
3029                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
3030                                 &node_txn[0]
3031                         } else {
3032                                 check_spends!(node_txn[0], commitment_tx[0]);
3033                                 check_spends!(node_txn[1], commitment_tx[0]);
3034                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
3035                                 &node_txn[2]
3036                         }
3037                 };
3038
3039         check_spends!(commitment_spend, node_a_commitment_tx[0]);
3040         assert_eq!(commitment_spend.input.len(), 2);
3041         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3042         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3043         assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3044         assert!(commitment_spend.output[0].script_pubkey.is_p2wpkh()); // direct payment
3045         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3046         // we already checked the same situation with A.
3047
3048         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3049         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3050         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3051         check_closed_broadcast!(nodes[0], true);
3052         check_added_monitors!(nodes[0], 1);
3053         let events = nodes[0].node.get_and_clear_pending_events();
3054         assert_eq!(events.len(), 5);
3055         let mut first_claimed = false;
3056         for event in events {
3057                 match event {
3058                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3059                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3060                                         assert!(!first_claimed);
3061                                         first_claimed = true;
3062                                 } else {
3063                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3064                                         assert_eq!(payment_hash, payment_hash_2);
3065                                 }
3066                         },
3067                         Event::PaymentPathSuccessful { .. } => {},
3068                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3069                         _ => panic!("Unexpected event"),
3070                 }
3071         }
3072         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3073 }
3074
3075 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3076         // Test that in case of a unilateral close onchain, we detect the state of output and
3077         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3078         // broadcasting the right event to other nodes in payment path.
3079         // A ------------------> B ----------------------> C (timeout)
3080         //    B's commitment tx                 C's commitment tx
3081         //            \                                  \
3082         //         B's HTLC timeout tx               B's timeout tx
3083
3084         let chanmon_cfgs = create_chanmon_cfgs(3);
3085         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3086         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3087         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3088         *nodes[0].connect_style.borrow_mut() = connect_style;
3089         *nodes[1].connect_style.borrow_mut() = connect_style;
3090         *nodes[2].connect_style.borrow_mut() = connect_style;
3091
3092         // Create some intial channels
3093         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3094         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3095
3096         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3097         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3098         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3099
3100         let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3101
3102         // Broadcast legit commitment tx from C on B's chain
3103         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3104         check_spends!(commitment_tx[0], chan_2.3);
3105         nodes[2].node.fail_htlc_backwards(&payment_hash);
3106         check_added_monitors!(nodes[2], 0);
3107         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3108         check_added_monitors!(nodes[2], 1);
3109
3110         let events = nodes[2].node.get_and_clear_pending_msg_events();
3111         assert_eq!(events.len(), 1);
3112         match events[0] {
3113                 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, .. } } => {
3114                         assert!(update_add_htlcs.is_empty());
3115                         assert!(!update_fail_htlcs.is_empty());
3116                         assert!(update_fulfill_htlcs.is_empty());
3117                         assert!(update_fail_malformed_htlcs.is_empty());
3118                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3119                 },
3120                 _ => panic!("Unexpected event"),
3121         };
3122         mine_transaction(&nodes[2], &commitment_tx[0]);
3123         check_closed_broadcast!(nodes[2], true);
3124         check_added_monitors!(nodes[2], 1);
3125         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3126         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3127         assert_eq!(node_txn.len(), 0);
3128
3129         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3130         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3131         mine_transaction(&nodes[1], &commitment_tx[0]);
3132         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3133                 , [nodes[2].node.get_our_node_id()], 100000);
3134         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3135         let timeout_tx = {
3136                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3137                 if nodes[1].connect_style.borrow().skips_blocks() {
3138                         assert_eq!(txn.len(), 1);
3139                 } else {
3140                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3141                 }
3142                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3143                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3144                 txn.remove(0)
3145         };
3146
3147         mine_transaction(&nodes[1], &timeout_tx);
3148         check_added_monitors!(nodes[1], 1);
3149         check_closed_broadcast!(nodes[1], true);
3150
3151         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3152
3153         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 }]);
3154         check_added_monitors!(nodes[1], 1);
3155         let events = nodes[1].node.get_and_clear_pending_msg_events();
3156         assert_eq!(events.len(), 1);
3157         match events[0] {
3158                 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, .. } } => {
3159                         assert!(update_add_htlcs.is_empty());
3160                         assert!(!update_fail_htlcs.is_empty());
3161                         assert!(update_fulfill_htlcs.is_empty());
3162                         assert!(update_fail_malformed_htlcs.is_empty());
3163                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3164                 },
3165                 _ => panic!("Unexpected event"),
3166         };
3167
3168         // Broadcast legit commitment tx from B on A's chain
3169         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3170         check_spends!(commitment_tx[0], chan_1.3);
3171
3172         mine_transaction(&nodes[0], &commitment_tx[0]);
3173         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3174
3175         check_closed_broadcast!(nodes[0], true);
3176         check_added_monitors!(nodes[0], 1);
3177         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3178         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3179         assert_eq!(node_txn.len(), 1);
3180         check_spends!(node_txn[0], commitment_tx[0]);
3181         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3182 }
3183
3184 #[test]
3185 fn test_htlc_on_chain_timeout() {
3186         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3187         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3188         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3189 }
3190
3191 #[test]
3192 fn test_simple_commitment_revoked_fail_backward() {
3193         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3194         // and fail backward accordingly.
3195
3196         let chanmon_cfgs = create_chanmon_cfgs(3);
3197         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3198         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3199         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3200
3201         // Create some initial channels
3202         create_announced_chan_between_nodes(&nodes, 0, 1);
3203         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3204
3205         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3206         // Get the will-be-revoked local txn from nodes[2]
3207         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3208         // Revoke the old state
3209         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3210
3211         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3212
3213         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3214         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3215         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3216         check_added_monitors!(nodes[1], 1);
3217         check_closed_broadcast!(nodes[1], true);
3218
3219         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 }]);
3220         check_added_monitors!(nodes[1], 1);
3221         let events = nodes[1].node.get_and_clear_pending_msg_events();
3222         assert_eq!(events.len(), 1);
3223         match events[0] {
3224                 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, .. } } => {
3225                         assert!(update_add_htlcs.is_empty());
3226                         assert_eq!(update_fail_htlcs.len(), 1);
3227                         assert!(update_fulfill_htlcs.is_empty());
3228                         assert!(update_fail_malformed_htlcs.is_empty());
3229                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3230
3231                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3232                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3233                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3234                 },
3235                 _ => panic!("Unexpected event"),
3236         }
3237 }
3238
3239 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3240         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3241         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3242         // commitment transaction anymore.
3243         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3244         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3245         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3246         // technically disallowed and we should probably handle it reasonably.
3247         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3248         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3249         // transactions:
3250         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3251         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3252         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3253         //   and once they revoke the previous commitment transaction (allowing us to send a new
3254         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3255         let chanmon_cfgs = create_chanmon_cfgs(3);
3256         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3257         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3258         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3259
3260         // Create some initial channels
3261         create_announced_chan_between_nodes(&nodes, 0, 1);
3262         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3263
3264         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3265         // Get the will-be-revoked local txn from nodes[2]
3266         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3267         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3268         // Revoke the old state
3269         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3270
3271         let value = if use_dust {
3272                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3273                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3274                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3275                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3276         } else { 3000000 };
3277
3278         let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3279         let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3280         let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3281
3282         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3283         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3284         check_added_monitors!(nodes[2], 1);
3285         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3286         assert!(updates.update_add_htlcs.is_empty());
3287         assert!(updates.update_fulfill_htlcs.is_empty());
3288         assert!(updates.update_fail_malformed_htlcs.is_empty());
3289         assert_eq!(updates.update_fail_htlcs.len(), 1);
3290         assert!(updates.update_fee.is_none());
3291         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3292         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3293         // Drop the last RAA from 3 -> 2
3294
3295         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3296         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3297         check_added_monitors!(nodes[2], 1);
3298         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3299         assert!(updates.update_add_htlcs.is_empty());
3300         assert!(updates.update_fulfill_htlcs.is_empty());
3301         assert!(updates.update_fail_malformed_htlcs.is_empty());
3302         assert_eq!(updates.update_fail_htlcs.len(), 1);
3303         assert!(updates.update_fee.is_none());
3304         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3305         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3306         check_added_monitors!(nodes[1], 1);
3307         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3308         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3309         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3310         check_added_monitors!(nodes[2], 1);
3311
3312         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3313         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3314         check_added_monitors!(nodes[2], 1);
3315         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3316         assert!(updates.update_add_htlcs.is_empty());
3317         assert!(updates.update_fulfill_htlcs.is_empty());
3318         assert!(updates.update_fail_malformed_htlcs.is_empty());
3319         assert_eq!(updates.update_fail_htlcs.len(), 1);
3320         assert!(updates.update_fee.is_none());
3321         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3322         // At this point first_payment_hash has dropped out of the latest two commitment
3323         // transactions that nodes[1] is tracking...
3324         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3325         check_added_monitors!(nodes[1], 1);
3326         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3327         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3328         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3329         check_added_monitors!(nodes[2], 1);
3330
3331         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3332         // on nodes[2]'s RAA.
3333         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3334         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3335                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3336         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3337         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3338         check_added_monitors!(nodes[1], 0);
3339
3340         if deliver_bs_raa {
3341                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3342                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3343                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3344                 check_added_monitors!(nodes[1], 1);
3345                 let events = nodes[1].node.get_and_clear_pending_events();
3346                 assert_eq!(events.len(), 2);
3347                 match events[0] {
3348                         Event::HTLCHandlingFailed { .. } => { },
3349                         _ => panic!("Unexpected event"),
3350                 }
3351                 match events[1] {
3352                         Event::PendingHTLCsForwardable { .. } => { },
3353                         _ => panic!("Unexpected event"),
3354                 };
3355                 // Deliberately don't process the pending fail-back so they all fail back at once after
3356                 // block connection just like the !deliver_bs_raa case
3357         }
3358
3359         let mut failed_htlcs = new_hash_set();
3360         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3361
3362         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3363         check_added_monitors!(nodes[1], 1);
3364         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3365
3366         let events = nodes[1].node.get_and_clear_pending_events();
3367         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3368         assert!(events.iter().any(|ev| matches!(
3369                 ev,
3370                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. }
3371         )));
3372         assert!(events.iter().any(|ev| matches!(
3373                 ev,
3374                 Event::PaymentPathFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3375         )));
3376         assert!(events.iter().any(|ev| matches!(
3377                 ev,
3378                 Event::PaymentFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3379         )));
3380
3381         nodes[1].node.process_pending_htlc_forwards();
3382         check_added_monitors!(nodes[1], 1);
3383
3384         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3385         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3386
3387         if deliver_bs_raa {
3388                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3389                 match nodes_2_event {
3390                         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, .. } } => {
3391                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3392                                 assert_eq!(update_add_htlcs.len(), 1);
3393                                 assert!(update_fulfill_htlcs.is_empty());
3394                                 assert!(update_fail_htlcs.is_empty());
3395                                 assert!(update_fail_malformed_htlcs.is_empty());
3396                         },
3397                         _ => panic!("Unexpected event"),
3398                 }
3399         }
3400
3401         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3402         match nodes_2_event {
3403                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3404                         assert_eq!(channel_id, chan_2.2);
3405                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3406                 },
3407                 _ => panic!("Unexpected event"),
3408         }
3409
3410         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3411         match nodes_0_event {
3412                 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, .. } } => {
3413                         assert!(update_add_htlcs.is_empty());
3414                         assert_eq!(update_fail_htlcs.len(), 3);
3415                         assert!(update_fulfill_htlcs.is_empty());
3416                         assert!(update_fail_malformed_htlcs.is_empty());
3417                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3418
3419                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3420                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3421                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3422
3423                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3424
3425                         let events = nodes[0].node.get_and_clear_pending_events();
3426                         assert_eq!(events.len(), 6);
3427                         match events[0] {
3428                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3429                                         assert!(failed_htlcs.insert(payment_hash.0));
3430                                         // If we delivered B's RAA we got an unknown preimage error, not something
3431                                         // that we should update our routing table for.
3432                                         if !deliver_bs_raa {
3433                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3434                                         }
3435                                 },
3436                                 _ => panic!("Unexpected event"),
3437                         }
3438                         match events[1] {
3439                                 Event::PaymentFailed { ref payment_hash, .. } => {
3440                                         assert_eq!(*payment_hash, first_payment_hash);
3441                                 },
3442                                 _ => panic!("Unexpected event"),
3443                         }
3444                         match events[2] {
3445                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3446                                         assert!(failed_htlcs.insert(payment_hash.0));
3447                                 },
3448                                 _ => panic!("Unexpected event"),
3449                         }
3450                         match events[3] {
3451                                 Event::PaymentFailed { ref payment_hash, .. } => {
3452                                         assert_eq!(*payment_hash, second_payment_hash);
3453                                 },
3454                                 _ => panic!("Unexpected event"),
3455                         }
3456                         match events[4] {
3457                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3458                                         assert!(failed_htlcs.insert(payment_hash.0));
3459                                 },
3460                                 _ => panic!("Unexpected event"),
3461                         }
3462                         match events[5] {
3463                                 Event::PaymentFailed { ref payment_hash, .. } => {
3464                                         assert_eq!(*payment_hash, third_payment_hash);
3465                                 },
3466                                 _ => panic!("Unexpected event"),
3467                         }
3468                 },
3469                 _ => panic!("Unexpected event"),
3470         }
3471
3472         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3473         match events[0] {
3474                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3475                 _ => panic!("Unexpected event"),
3476         }
3477
3478         assert!(failed_htlcs.contains(&first_payment_hash.0));
3479         assert!(failed_htlcs.contains(&second_payment_hash.0));
3480         assert!(failed_htlcs.contains(&third_payment_hash.0));
3481 }
3482
3483 #[test]
3484 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3485         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3486         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3487         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3488         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3489 }
3490
3491 #[test]
3492 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3493         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3494         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3495         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3496         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3497 }
3498
3499 #[test]
3500 fn fail_backward_pending_htlc_upon_channel_failure() {
3501         let chanmon_cfgs = create_chanmon_cfgs(2);
3502         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3503         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3504         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3505         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3506
3507         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3508         {
3509                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3510                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3511                         PaymentId(payment_hash.0)).unwrap();
3512                 check_added_monitors!(nodes[0], 1);
3513
3514                 let payment_event = {
3515                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3516                         assert_eq!(events.len(), 1);
3517                         SendEvent::from_event(events.remove(0))
3518                 };
3519                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3520                 assert_eq!(payment_event.msgs.len(), 1);
3521         }
3522
3523         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3524         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3525         {
3526                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3527                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3528                 check_added_monitors!(nodes[0], 0);
3529
3530                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3531         }
3532
3533         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3534         {
3535                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3536
3537                 let secp_ctx = Secp256k1::new();
3538                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3539                 let current_height = nodes[1].node.best_block.read().unwrap().height + 1;
3540                 let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
3541                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3542                         &route.paths[0], 50_000, &recipient_onion_fields, current_height, &None).unwrap();
3543                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3544                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3545
3546                 // Send a 0-msat update_add_htlc to fail the channel.
3547                 let update_add_htlc = msgs::UpdateAddHTLC {
3548                         channel_id: chan.2,
3549                         htlc_id: 0,
3550                         amount_msat: 0,
3551                         payment_hash,
3552                         cltv_expiry,
3553                         onion_routing_packet,
3554                         skimmed_fee_msat: None,
3555                         blinding_point: None,
3556                 };
3557                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3558         }
3559         let events = nodes[0].node.get_and_clear_pending_events();
3560         assert_eq!(events.len(), 3);
3561         // Check that Alice fails backward the pending HTLC from the second payment.
3562         match events[0] {
3563                 Event::PaymentPathFailed { payment_hash, .. } => {
3564                         assert_eq!(payment_hash, failed_payment_hash);
3565                 },
3566                 _ => panic!("Unexpected event"),
3567         }
3568         match events[1] {
3569                 Event::PaymentFailed { payment_hash, .. } => {
3570                         assert_eq!(payment_hash, failed_payment_hash);
3571                 },
3572                 _ => panic!("Unexpected event"),
3573         }
3574         match events[2] {
3575                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3576                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3577                 },
3578                 _ => panic!("Unexpected event {:?}", events[1]),
3579         }
3580         check_closed_broadcast!(nodes[0], true);
3581         check_added_monitors!(nodes[0], 1);
3582 }
3583
3584 #[test]
3585 fn test_htlc_ignore_latest_remote_commitment() {
3586         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3587         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3588         let chanmon_cfgs = create_chanmon_cfgs(2);
3589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3592         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3593                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3594                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3595                 // connect_style.
3596                 return;
3597         }
3598         let funding_tx = create_announced_chan_between_nodes(&nodes, 0, 1).3;
3599
3600         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3601         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3602         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3603         check_closed_broadcast!(nodes[0], true);
3604         check_added_monitors!(nodes[0], 1);
3605         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3606
3607         let node_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
3608         assert_eq!(node_txn.len(), 2);
3609         check_spends!(node_txn[0], funding_tx);
3610         check_spends!(node_txn[1], node_txn[0]);
3611
3612         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone()]);
3613         connect_block(&nodes[1], &block);
3614         check_closed_broadcast!(nodes[1], true);
3615         check_added_monitors!(nodes[1], 1);
3616         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3617
3618         // Duplicate the connect_block call since this may happen due to other listeners
3619         // registering new transactions
3620         connect_block(&nodes[1], &block);
3621 }
3622
3623 #[test]
3624 fn test_force_close_fail_back() {
3625         // Check which HTLCs are failed-backwards on channel force-closure
3626         let chanmon_cfgs = create_chanmon_cfgs(3);
3627         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3628         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3629         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3630         create_announced_chan_between_nodes(&nodes, 0, 1);
3631         create_announced_chan_between_nodes(&nodes, 1, 2);
3632
3633         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3634
3635         let mut payment_event = {
3636                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3637                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3638                 check_added_monitors!(nodes[0], 1);
3639
3640                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3641                 assert_eq!(events.len(), 1);
3642                 SendEvent::from_event(events.remove(0))
3643         };
3644
3645         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3646         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3647
3648         expect_pending_htlcs_forwardable!(nodes[1]);
3649
3650         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3651         assert_eq!(events_2.len(), 1);
3652         payment_event = SendEvent::from_event(events_2.remove(0));
3653         assert_eq!(payment_event.msgs.len(), 1);
3654
3655         check_added_monitors!(nodes[1], 1);
3656         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3657         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3658         check_added_monitors!(nodes[2], 1);
3659         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3660
3661         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3662         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3663         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3664
3665         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3666         check_closed_broadcast!(nodes[2], true);
3667         check_added_monitors!(nodes[2], 1);
3668         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3669         let commitment_tx = {
3670                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3671                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3672                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3673                 // back to nodes[1] upon timeout otherwise.
3674                 assert_eq!(node_txn.len(), 1);
3675                 node_txn.remove(0)
3676         };
3677
3678         mine_transaction(&nodes[1], &commitment_tx);
3679
3680         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3681         check_closed_broadcast!(nodes[1], true);
3682         check_added_monitors!(nodes[1], 1);
3683         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3684
3685         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3686         {
3687                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3688                         .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);
3689         }
3690         mine_transaction(&nodes[2], &commitment_tx);
3691         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcast();
3692         assert_eq!(node_txn.len(), if nodes[2].connect_style.borrow().updates_best_block_first() { 2 } else { 1 });
3693         let htlc_tx = node_txn.pop().unwrap();
3694         assert_eq!(htlc_tx.input.len(), 1);
3695         assert_eq!(htlc_tx.input[0].previous_output.txid, commitment_tx.txid());
3696         assert_eq!(htlc_tx.lock_time, LockTime::ZERO); // Must be an HTLC-Success
3697         assert_eq!(htlc_tx.input[0].witness.len(), 5); // Must be an HTLC-Success
3698
3699         check_spends!(htlc_tx, commitment_tx);
3700 }
3701
3702 #[test]
3703 fn test_dup_events_on_peer_disconnect() {
3704         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3705         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3706         // as we used to generate the event immediately upon receipt of the payment preimage in the
3707         // update_fulfill_htlc message.
3708
3709         let chanmon_cfgs = create_chanmon_cfgs(2);
3710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3713         create_announced_chan_between_nodes(&nodes, 0, 1);
3714
3715         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3716
3717         nodes[1].node.claim_funds(payment_preimage);
3718         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3719         check_added_monitors!(nodes[1], 1);
3720         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3721         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3722         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3723
3724         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3725         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3726
3727         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3728         reconnect_args.pending_htlc_claims.0 = 1;
3729         reconnect_nodes(reconnect_args);
3730         expect_payment_path_successful!(nodes[0]);
3731 }
3732
3733 #[test]
3734 fn test_peer_disconnected_before_funding_broadcasted() {
3735         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3736         // before the funding transaction has been broadcasted, and doesn't reconnect back within time.
3737         let chanmon_cfgs = create_chanmon_cfgs(2);
3738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3741
3742         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3743         // broadcasted, even though it's created by `nodes[0]`.
3744         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();
3745         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3746         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3747         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3748         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3749
3750         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3751         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3752
3753         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3754
3755         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3756         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3757
3758         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3759         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3760         // broadcasted.
3761         {
3762                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3763         }
3764
3765         // The peers disconnect before the funding is broadcasted.
3766         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3767         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3768
3769         // The time for peers to reconnect expires.
3770         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
3771                 nodes[0].node.timer_tick_occurred();
3772         }
3773
3774         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` and a
3775         // `DiscardFunding` event when the peers are disconnected and do not reconnect before the
3776         // funding transaction is broadcasted.
3777         check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3778                 , [nodes[1].node.get_our_node_id()], 1000000);
3779         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3780                 , [nodes[0].node.get_our_node_id()], 1000000);
3781 }
3782
3783 #[test]
3784 fn test_simple_peer_disconnect() {
3785         // Test that we can reconnect when there are no lost messages
3786         let chanmon_cfgs = create_chanmon_cfgs(3);
3787         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3788         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3789         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3790         create_announced_chan_between_nodes(&nodes, 0, 1);
3791         create_announced_chan_between_nodes(&nodes, 1, 2);
3792
3793         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3794         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3795         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3796         reconnect_args.send_channel_ready = (true, true);
3797         reconnect_nodes(reconnect_args);
3798
3799         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3800         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3801         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3802         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3803
3804         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3805         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3806         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3807
3808         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3809         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3810         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3811         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3812
3813         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3814         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3815
3816         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3817         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3818
3819         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3820         reconnect_args.pending_cell_htlc_fails.0 = 1;
3821         reconnect_args.pending_cell_htlc_claims.0 = 1;
3822         reconnect_nodes(reconnect_args);
3823         {
3824                 let events = nodes[0].node.get_and_clear_pending_events();
3825                 assert_eq!(events.len(), 4);
3826                 match events[0] {
3827                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3828                                 assert_eq!(payment_preimage, payment_preimage_3);
3829                                 assert_eq!(payment_hash, payment_hash_3);
3830                         },
3831                         _ => panic!("Unexpected event"),
3832                 }
3833                 match events[1] {
3834                         Event::PaymentPathSuccessful { .. } => {},
3835                         _ => panic!("Unexpected event"),
3836                 }
3837                 match events[2] {
3838                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3839                                 assert_eq!(payment_hash, payment_hash_5);
3840                                 assert!(payment_failed_permanently);
3841                         },
3842                         _ => panic!("Unexpected event"),
3843                 }
3844                 match events[3] {
3845                         Event::PaymentFailed { payment_hash, .. } => {
3846                                 assert_eq!(payment_hash, payment_hash_5);
3847                         },
3848                         _ => panic!("Unexpected event"),
3849                 }
3850         }
3851         check_added_monitors(&nodes[0], 1);
3852
3853         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3854         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3855 }
3856
3857 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3858         // Test that we can reconnect when in-flight HTLC updates get dropped
3859         let chanmon_cfgs = create_chanmon_cfgs(2);
3860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3862         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3863
3864         let mut as_channel_ready = None;
3865         let channel_id = if messages_delivered == 0 {
3866                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3867                 as_channel_ready = Some(channel_ready);
3868                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3869                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3870                 // it before the channel_reestablish message.
3871                 chan_id
3872         } else {
3873                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3874         };
3875
3876         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3877
3878         let payment_event = {
3879                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3880                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3881                 check_added_monitors!(nodes[0], 1);
3882
3883                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3884                 assert_eq!(events.len(), 1);
3885                 SendEvent::from_event(events.remove(0))
3886         };
3887         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3888
3889         if messages_delivered < 2 {
3890                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3891         } else {
3892                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3893                 if messages_delivered >= 3 {
3894                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3895                         check_added_monitors!(nodes[1], 1);
3896                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3897
3898                         if messages_delivered >= 4 {
3899                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3900                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3901                                 check_added_monitors!(nodes[0], 1);
3902
3903                                 if messages_delivered >= 5 {
3904                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3905                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3906                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3907                                         check_added_monitors!(nodes[0], 1);
3908
3909                                         if messages_delivered >= 6 {
3910                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3911                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3912                                                 check_added_monitors!(nodes[1], 1);
3913                                         }
3914                                 }
3915                         }
3916                 }
3917         }
3918
3919         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3920         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3921         if messages_delivered < 3 {
3922                 if simulate_broken_lnd {
3923                         // lnd has a long-standing bug where they send a channel_ready prior to a
3924                         // channel_reestablish if you reconnect prior to channel_ready time.
3925                         //
3926                         // Here we simulate that behavior, delivering a channel_ready immediately on
3927                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3928                         // in `reconnect_nodes` but we currently don't fail based on that.
3929                         //
3930                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3931                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3932                 }
3933                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3934                 // received on either side, both sides will need to resend them.
3935                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3936                 reconnect_args.send_channel_ready = (true, true);
3937                 reconnect_args.pending_htlc_adds.1 = 1;
3938                 reconnect_nodes(reconnect_args);
3939         } else if messages_delivered == 3 {
3940                 // nodes[0] still wants its RAA + commitment_signed
3941                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3942                 reconnect_args.pending_responding_commitment_signed.0 = true;
3943                 reconnect_args.pending_raa.0 = true;
3944                 reconnect_nodes(reconnect_args);
3945         } else if messages_delivered == 4 {
3946                 // nodes[0] still wants its commitment_signed
3947                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3948                 reconnect_args.pending_responding_commitment_signed.0 = true;
3949                 reconnect_nodes(reconnect_args);
3950         } else if messages_delivered == 5 {
3951                 // nodes[1] still wants its final RAA
3952                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3953                 reconnect_args.pending_raa.1 = true;
3954                 reconnect_nodes(reconnect_args);
3955         } else if messages_delivered == 6 {
3956                 // Everything was delivered...
3957                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3958         }
3959
3960         let events_1 = nodes[1].node.get_and_clear_pending_events();
3961         if messages_delivered == 0 {
3962                 assert_eq!(events_1.len(), 2);
3963                 match events_1[0] {
3964                         Event::ChannelReady { .. } => { },
3965                         _ => panic!("Unexpected event"),
3966                 };
3967                 match events_1[1] {
3968                         Event::PendingHTLCsForwardable { .. } => { },
3969                         _ => panic!("Unexpected event"),
3970                 };
3971         } else {
3972                 assert_eq!(events_1.len(), 1);
3973                 match events_1[0] {
3974                         Event::PendingHTLCsForwardable { .. } => { },
3975                         _ => panic!("Unexpected event"),
3976                 };
3977         }
3978
3979         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3980         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3981         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3982
3983         nodes[1].node.process_pending_htlc_forwards();
3984
3985         let events_2 = nodes[1].node.get_and_clear_pending_events();
3986         assert_eq!(events_2.len(), 1);
3987         match events_2[0] {
3988                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3989                         assert_eq!(payment_hash_1, *payment_hash);
3990                         assert_eq!(amount_msat, 1_000_000);
3991                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3992                         assert_eq!(via_channel_id, Some(channel_id));
3993                         match &purpose {
3994                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
3995                                         assert!(payment_preimage.is_none());
3996                                         assert_eq!(payment_secret_1, *payment_secret);
3997                                 },
3998                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
3999                         }
4000                 },
4001                 _ => panic!("Unexpected event"),
4002         }
4003
4004         nodes[1].node.claim_funds(payment_preimage_1);
4005         check_added_monitors!(nodes[1], 1);
4006         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4007
4008         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
4009         assert_eq!(events_3.len(), 1);
4010         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
4011                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4012                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4013                         assert!(updates.update_add_htlcs.is_empty());
4014                         assert!(updates.update_fail_htlcs.is_empty());
4015                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4016                         assert!(updates.update_fail_malformed_htlcs.is_empty());
4017                         assert!(updates.update_fee.is_none());
4018                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
4019                 },
4020                 _ => panic!("Unexpected event"),
4021         };
4022
4023         if messages_delivered >= 1 {
4024                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
4025
4026                 let events_4 = nodes[0].node.get_and_clear_pending_events();
4027                 assert_eq!(events_4.len(), 1);
4028                 match events_4[0] {
4029                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4030                                 assert_eq!(payment_preimage_1, *payment_preimage);
4031                                 assert_eq!(payment_hash_1, *payment_hash);
4032                         },
4033                         _ => panic!("Unexpected event"),
4034                 }
4035
4036                 if messages_delivered >= 2 {
4037                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
4038                         check_added_monitors!(nodes[0], 1);
4039                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4040
4041                         if messages_delivered >= 3 {
4042                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4043                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4044                                 check_added_monitors!(nodes[1], 1);
4045
4046                                 if messages_delivered >= 4 {
4047                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4048                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4049                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4050                                         check_added_monitors!(nodes[1], 1);
4051
4052                                         if messages_delivered >= 5 {
4053                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4054                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4055                                                 check_added_monitors!(nodes[0], 1);
4056                                         }
4057                                 }
4058                         }
4059                 }
4060         }
4061
4062         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4063         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4064         if messages_delivered < 2 {
4065                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4066                 reconnect_args.pending_htlc_claims.0 = 1;
4067                 reconnect_nodes(reconnect_args);
4068                 if messages_delivered < 1 {
4069                         expect_payment_sent!(nodes[0], payment_preimage_1);
4070                 } else {
4071                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4072                 }
4073         } else if messages_delivered == 2 {
4074                 // nodes[0] still wants its RAA + commitment_signed
4075                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4076                 reconnect_args.pending_responding_commitment_signed.1 = true;
4077                 reconnect_args.pending_raa.1 = true;
4078                 reconnect_nodes(reconnect_args);
4079         } else if messages_delivered == 3 {
4080                 // nodes[0] still wants its commitment_signed
4081                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4082                 reconnect_args.pending_responding_commitment_signed.1 = true;
4083                 reconnect_nodes(reconnect_args);
4084         } else if messages_delivered == 4 {
4085                 // nodes[1] still wants its final RAA
4086                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4087                 reconnect_args.pending_raa.0 = true;
4088                 reconnect_nodes(reconnect_args);
4089         } else if messages_delivered == 5 {
4090                 // Everything was delivered...
4091                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4092         }
4093
4094         if messages_delivered == 1 || messages_delivered == 2 {
4095                 expect_payment_path_successful!(nodes[0]);
4096         }
4097         if messages_delivered <= 5 {
4098                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4099                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4100         }
4101         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4102
4103         if messages_delivered > 2 {
4104                 expect_payment_path_successful!(nodes[0]);
4105         }
4106
4107         // Channel should still work fine...
4108         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4109         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4110         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4111 }
4112
4113 #[test]
4114 fn test_drop_messages_peer_disconnect_a() {
4115         do_test_drop_messages_peer_disconnect(0, true);
4116         do_test_drop_messages_peer_disconnect(0, false);
4117         do_test_drop_messages_peer_disconnect(1, false);
4118         do_test_drop_messages_peer_disconnect(2, false);
4119 }
4120
4121 #[test]
4122 fn test_drop_messages_peer_disconnect_b() {
4123         do_test_drop_messages_peer_disconnect(3, false);
4124         do_test_drop_messages_peer_disconnect(4, false);
4125         do_test_drop_messages_peer_disconnect(5, false);
4126         do_test_drop_messages_peer_disconnect(6, false);
4127 }
4128
4129 #[test]
4130 fn test_channel_ready_without_best_block_updated() {
4131         // Previously, if we were offline when a funding transaction was locked in, and then we came
4132         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4133         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4134         // channel_ready immediately instead.
4135         let chanmon_cfgs = create_chanmon_cfgs(2);
4136         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4137         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4138         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4139         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4140
4141         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4142
4143         let conf_height = nodes[0].best_block_info().1 + 1;
4144         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4145         let block_txn = [funding_tx];
4146         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4147         let conf_block_header = nodes[0].get_block_header(conf_height);
4148         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4149
4150         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4151         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4152         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4153 }
4154
4155 #[test]
4156 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4157         let chanmon_cfgs = create_chanmon_cfgs(2);
4158         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4159         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4160         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4161
4162         // Let channel_manager get ahead of chain_monitor by 1 block.
4163         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4164         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4165         let height_1 = nodes[0].best_block_info().1 + 1;
4166         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4167
4168         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4169         nodes[0].node.block_connected(&block_1, height_1);
4170
4171         // Create channel, and it gets added to chain_monitor in funding_created.
4172         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4173
4174         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4175         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4176         // was running ahead of chain_monitor at the time of funding_created.
4177         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4178         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4179         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4180         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4181
4182         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4183         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4184         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4185 }
4186
4187 #[test]
4188 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4189         let chanmon_cfgs = create_chanmon_cfgs(2);
4190         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4191         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4192         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4193
4194         // Let chain_monitor get ahead of channel_manager by 1 block.
4195         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4196         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4197         let height_1 = nodes[0].best_block_info().1 + 1;
4198         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4199
4200         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4201         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4202
4203         // Create channel, and it gets added to chain_monitor in funding_created.
4204         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4205
4206         // channel_manager can't really skip block_1, it should get it eventually.
4207         nodes[0].node.block_connected(&block_1, height_1);
4208
4209         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4210         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4211         // running behind at the time of funding_created.
4212         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4213         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4214         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4215         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4216
4217         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4218         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4219         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4220 }
4221
4222 #[test]
4223 fn test_drop_messages_peer_disconnect_dual_htlc() {
4224         // Test that we can handle reconnecting when both sides of a channel have pending
4225         // commitment_updates when we disconnect.
4226         let chanmon_cfgs = create_chanmon_cfgs(2);
4227         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4228         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4229         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4230         create_announced_chan_between_nodes(&nodes, 0, 1);
4231
4232         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4233
4234         // Now try to send a second payment which will fail to send
4235         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4236         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4237                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4238         check_added_monitors!(nodes[0], 1);
4239
4240         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4241         assert_eq!(events_1.len(), 1);
4242         match events_1[0] {
4243                 MessageSendEvent::UpdateHTLCs { .. } => {},
4244                 _ => panic!("Unexpected event"),
4245         }
4246
4247         nodes[1].node.claim_funds(payment_preimage_1);
4248         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4249         check_added_monitors!(nodes[1], 1);
4250
4251         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4252         assert_eq!(events_2.len(), 1);
4253         match events_2[0] {
4254                 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 } } => {
4255                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4256                         assert!(update_add_htlcs.is_empty());
4257                         assert_eq!(update_fulfill_htlcs.len(), 1);
4258                         assert!(update_fail_htlcs.is_empty());
4259                         assert!(update_fail_malformed_htlcs.is_empty());
4260                         assert!(update_fee.is_none());
4261
4262                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4263                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4264                         assert_eq!(events_3.len(), 1);
4265                         match events_3[0] {
4266                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4267                                         assert_eq!(*payment_preimage, payment_preimage_1);
4268                                         assert_eq!(*payment_hash, payment_hash_1);
4269                                 },
4270                                 _ => panic!("Unexpected event"),
4271                         }
4272
4273                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4274                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4275                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4276                         check_added_monitors!(nodes[0], 1);
4277                 },
4278                 _ => panic!("Unexpected event"),
4279         }
4280
4281         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4282         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4283
4284         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4285                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4286         }, true).unwrap();
4287         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4288         assert_eq!(reestablish_1.len(), 1);
4289         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4290                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4291         }, false).unwrap();
4292         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4293         assert_eq!(reestablish_2.len(), 1);
4294
4295         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4296         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4297         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4298         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4299
4300         assert!(as_resp.0.is_none());
4301         assert!(bs_resp.0.is_none());
4302
4303         assert!(bs_resp.1.is_none());
4304         assert!(bs_resp.2.is_none());
4305
4306         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4307
4308         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4309         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4310         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4311         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4312         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4313         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4314         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4315         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4316         // No commitment_signed so get_event_msg's assert(len == 1) passes
4317         check_added_monitors!(nodes[1], 1);
4318
4319         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4320         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4321         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4322         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4323         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4324         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4325         assert!(bs_second_commitment_signed.update_fee.is_none());
4326         check_added_monitors!(nodes[1], 1);
4327
4328         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4329         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4330         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4331         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4332         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4333         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4334         assert!(as_commitment_signed.update_fee.is_none());
4335         check_added_monitors!(nodes[0], 1);
4336
4337         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4338         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4339         // No commitment_signed so get_event_msg's assert(len == 1) passes
4340         check_added_monitors!(nodes[0], 1);
4341
4342         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4343         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4344         // No commitment_signed so get_event_msg's assert(len == 1) passes
4345         check_added_monitors!(nodes[1], 1);
4346
4347         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4348         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4349         check_added_monitors!(nodes[1], 1);
4350
4351         expect_pending_htlcs_forwardable!(nodes[1]);
4352
4353         let events_5 = nodes[1].node.get_and_clear_pending_events();
4354         assert_eq!(events_5.len(), 1);
4355         match events_5[0] {
4356                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4357                         assert_eq!(payment_hash_2, *payment_hash);
4358                         match &purpose {
4359                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
4360                                         assert!(payment_preimage.is_none());
4361                                         assert_eq!(payment_secret_2, *payment_secret);
4362                                 },
4363                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
4364                         }
4365                 },
4366                 _ => panic!("Unexpected event"),
4367         }
4368
4369         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4370         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4371         check_added_monitors!(nodes[0], 1);
4372
4373         expect_payment_path_successful!(nodes[0]);
4374         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4375 }
4376
4377 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4378         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4379         // to avoid our counterparty failing the channel.
4380         let chanmon_cfgs = create_chanmon_cfgs(2);
4381         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4382         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4383         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4384
4385         create_announced_chan_between_nodes(&nodes, 0, 1);
4386
4387         let our_payment_hash = if send_partial_mpp {
4388                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4389                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4390                 // indicates there are more HTLCs coming.
4391                 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.
4392                 let payment_id = PaymentId([42; 32]);
4393                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4394                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4395                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4396                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4397                         &None, session_privs[0]).unwrap();
4398                 check_added_monitors!(nodes[0], 1);
4399                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4400                 assert_eq!(events.len(), 1);
4401                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4402                 // hop should *not* yet generate any PaymentClaimable event(s).
4403                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4404                 our_payment_hash
4405         } else {
4406                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4407         };
4408
4409         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4410         connect_block(&nodes[0], &block);
4411         connect_block(&nodes[1], &block);
4412         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4413         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4414                 block.header.prev_blockhash = block.block_hash();
4415                 connect_block(&nodes[0], &block);
4416                 connect_block(&nodes[1], &block);
4417         }
4418
4419         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4420
4421         check_added_monitors!(nodes[1], 1);
4422         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4423         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4424         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4425         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4426         assert!(htlc_timeout_updates.update_fee.is_none());
4427
4428         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4429         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4430         // 100_000 msat as u64, followed by the height at which we failed back above
4431         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4432         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4433         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4434 }
4435
4436 #[test]
4437 fn test_htlc_timeout() {
4438         do_test_htlc_timeout(true);
4439         do_test_htlc_timeout(false);
4440 }
4441
4442 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4443         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4444         let chanmon_cfgs = create_chanmon_cfgs(3);
4445         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4446         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4447         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4448         create_announced_chan_between_nodes(&nodes, 0, 1);
4449         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4450
4451         // Make sure all nodes are at the same starting height
4452         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4453         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4454         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4455
4456         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4457         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4458         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4459                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4460         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4461         check_added_monitors!(nodes[1], 1);
4462
4463         // Now attempt to route a second payment, which should be placed in the holding cell
4464         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4465         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4466         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4467                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4468         if forwarded_htlc {
4469                 check_added_monitors!(nodes[0], 1);
4470                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4471                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4472                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4473                 expect_pending_htlcs_forwardable!(nodes[1]);
4474         }
4475         check_added_monitors!(nodes[1], 0);
4476
4477         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4478         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4479         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4480         connect_blocks(&nodes[1], 1);
4481
4482         if forwarded_htlc {
4483                 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 }]);
4484                 check_added_monitors!(nodes[1], 1);
4485                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4486                 assert_eq!(fail_commit.len(), 1);
4487                 match fail_commit[0] {
4488                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4489                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4490                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4491                         },
4492                         _ => unreachable!(),
4493                 }
4494                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4495         } else {
4496                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4497         }
4498 }
4499
4500 #[test]
4501 fn test_holding_cell_htlc_add_timeouts() {
4502         do_test_holding_cell_htlc_add_timeouts(false);
4503         do_test_holding_cell_htlc_add_timeouts(true);
4504 }
4505
4506 macro_rules! check_spendable_outputs {
4507         ($node: expr, $keysinterface: expr) => {
4508                 {
4509                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4510                         let mut txn = Vec::new();
4511                         let mut all_outputs = Vec::new();
4512                         let secp_ctx = Secp256k1::new();
4513                         for event in events.drain(..) {
4514                                 match event {
4515                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4516                                                 for outp in outputs.drain(..) {
4517                                                         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());
4518                                                         all_outputs.push(outp);
4519                                                 }
4520                                         },
4521                                         _ => panic!("Unexpected event"),
4522                                 };
4523                         }
4524                         if all_outputs.len() > 1 {
4525                                 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) {
4526                                         txn.push(tx);
4527                                 }
4528                         }
4529                         txn
4530                 }
4531         }
4532 }
4533
4534 #[test]
4535 fn test_claim_sizeable_push_msat() {
4536         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4537         let chanmon_cfgs = create_chanmon_cfgs(2);
4538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4540         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4541
4542         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4543         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4544         check_closed_broadcast!(nodes[1], true);
4545         check_added_monitors!(nodes[1], 1);
4546         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4547         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4548         assert_eq!(node_txn.len(), 1);
4549         check_spends!(node_txn[0], chan.3);
4550         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
4551
4552         mine_transaction(&nodes[1], &node_txn[0]);
4553         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4554
4555         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4556         assert_eq!(spend_txn.len(), 1);
4557         assert_eq!(spend_txn[0].input.len(), 1);
4558         check_spends!(spend_txn[0], node_txn[0]);
4559         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4560 }
4561
4562 #[test]
4563 fn test_claim_on_remote_sizeable_push_msat() {
4564         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4565         // to_remote output is encumbered by a P2WPKH
4566         let chanmon_cfgs = create_chanmon_cfgs(2);
4567         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4568         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4569         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4570
4571         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4572         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4573         check_closed_broadcast!(nodes[0], true);
4574         check_added_monitors!(nodes[0], 1);
4575         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4576
4577         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4578         assert_eq!(node_txn.len(), 1);
4579         check_spends!(node_txn[0], chan.3);
4580         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
4581
4582         mine_transaction(&nodes[1], &node_txn[0]);
4583         check_closed_broadcast!(nodes[1], true);
4584         check_added_monitors!(nodes[1], 1);
4585         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4586         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4587
4588         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4589         assert_eq!(spend_txn.len(), 1);
4590         check_spends!(spend_txn[0], node_txn[0]);
4591 }
4592
4593 #[test]
4594 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4595         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4596         // to_remote output is encumbered by a P2WPKH
4597
4598         let chanmon_cfgs = create_chanmon_cfgs(2);
4599         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4600         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4601         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4602
4603         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4604         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4605         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4606         assert_eq!(revoked_local_txn[0].input.len(), 1);
4607         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4608
4609         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4610         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4611         check_closed_broadcast!(nodes[1], true);
4612         check_added_monitors!(nodes[1], 1);
4613         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4614
4615         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4616         mine_transaction(&nodes[1], &node_txn[0]);
4617         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4618
4619         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4620         assert_eq!(spend_txn.len(), 3);
4621         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4622         check_spends!(spend_txn[1], node_txn[0]);
4623         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4624 }
4625
4626 #[test]
4627 fn test_static_spendable_outputs_preimage_tx() {
4628         let chanmon_cfgs = create_chanmon_cfgs(2);
4629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4631         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4632
4633         // Create some initial channels
4634         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4635
4636         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4637
4638         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4639         assert_eq!(commitment_tx[0].input.len(), 1);
4640         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4641
4642         // Settle A's commitment tx on B's chain
4643         nodes[1].node.claim_funds(payment_preimage);
4644         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4645         check_added_monitors!(nodes[1], 1);
4646         mine_transaction(&nodes[1], &commitment_tx[0]);
4647         check_added_monitors!(nodes[1], 1);
4648         let events = nodes[1].node.get_and_clear_pending_msg_events();
4649         match events[0] {
4650                 MessageSendEvent::UpdateHTLCs { .. } => {},
4651                 _ => panic!("Unexpected event"),
4652         }
4653         match events[2] {
4654                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4655                 _ => panic!("Unexepected event"),
4656         }
4657
4658         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4659         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4660         assert_eq!(node_txn.len(), 1);
4661         check_spends!(node_txn[0], commitment_tx[0]);
4662         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4663
4664         mine_transaction(&nodes[1], &node_txn[0]);
4665         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4666         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4667
4668         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4669         assert_eq!(spend_txn.len(), 1);
4670         check_spends!(spend_txn[0], node_txn[0]);
4671 }
4672
4673 #[test]
4674 fn test_static_spendable_outputs_timeout_tx() {
4675         let chanmon_cfgs = create_chanmon_cfgs(2);
4676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4678         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4679
4680         // Create some initial channels
4681         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4682
4683         // Rebalance the network a bit by relaying one payment through all the channels ...
4684         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4685
4686         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4687
4688         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4689         assert_eq!(commitment_tx[0].input.len(), 1);
4690         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4691
4692         // Settle A's commitment tx on B' chain
4693         mine_transaction(&nodes[1], &commitment_tx[0]);
4694         check_added_monitors!(nodes[1], 1);
4695         let events = nodes[1].node.get_and_clear_pending_msg_events();
4696         match events[1] {
4697                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4698                 _ => panic!("Unexpected event"),
4699         }
4700         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4701
4702         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4703         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4704         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4705         check_spends!(node_txn[0],  commitment_tx[0].clone());
4706         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4707
4708         mine_transaction(&nodes[1], &node_txn[0]);
4709         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4710         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4711         expect_payment_failed!(nodes[1], our_payment_hash, false);
4712
4713         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4714         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4715         check_spends!(spend_txn[0], commitment_tx[0]);
4716         check_spends!(spend_txn[1], node_txn[0]);
4717         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4718 }
4719
4720 #[test]
4721 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4722         let chanmon_cfgs = create_chanmon_cfgs(2);
4723         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4724         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4725         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4726
4727         // Create some initial channels
4728         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4729
4730         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4731         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4732         assert_eq!(revoked_local_txn[0].input.len(), 1);
4733         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4734
4735         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4736
4737         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4738         check_closed_broadcast!(nodes[1], true);
4739         check_added_monitors!(nodes[1], 1);
4740         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4741
4742         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4743         assert_eq!(node_txn.len(), 1);
4744         assert_eq!(node_txn[0].input.len(), 2);
4745         check_spends!(node_txn[0], revoked_local_txn[0]);
4746
4747         mine_transaction(&nodes[1], &node_txn[0]);
4748         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4749
4750         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4751         assert_eq!(spend_txn.len(), 1);
4752         check_spends!(spend_txn[0], node_txn[0]);
4753 }
4754
4755 #[test]
4756 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4757         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4758         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4759         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4760         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4761         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4762
4763         // Create some initial channels
4764         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4765
4766         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4767         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4768         assert_eq!(revoked_local_txn[0].input.len(), 1);
4769         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4770
4771         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4772
4773         // A will generate HTLC-Timeout from revoked commitment tx
4774         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4775         check_closed_broadcast!(nodes[0], true);
4776         check_added_monitors!(nodes[0], 1);
4777         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4778         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4779
4780         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4781         assert_eq!(revoked_htlc_txn.len(), 1);
4782         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4783         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4784         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4785         assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4786
4787         // B will generate justice tx from A's revoked commitment/HTLC tx
4788         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4789         check_closed_broadcast!(nodes[1], true);
4790         check_added_monitors!(nodes[1], 1);
4791         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4792
4793         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4794         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4795         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4796         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4797         // transactions next...
4798         assert_eq!(node_txn[0].input.len(), 3);
4799         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4800
4801         assert_eq!(node_txn[1].input.len(), 2);
4802         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4803         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4804                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4805         } else {
4806                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4807                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4808         }
4809
4810         mine_transaction(&nodes[1], &node_txn[1]);
4811         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4812
4813         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4814         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4815         assert_eq!(spend_txn.len(), 1);
4816         assert_eq!(spend_txn[0].input.len(), 1);
4817         check_spends!(spend_txn[0], node_txn[1]);
4818 }
4819
4820 #[test]
4821 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4822         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4823         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4824         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4825         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4826         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4827
4828         // Create some initial channels
4829         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4830
4831         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4832         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4833         assert_eq!(revoked_local_txn[0].input.len(), 1);
4834         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4835
4836         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4837         assert_eq!(revoked_local_txn[0].output.len(), 2);
4838
4839         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4840
4841         // B will generate HTLC-Success from revoked commitment tx
4842         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4843         check_closed_broadcast!(nodes[1], true);
4844         check_added_monitors!(nodes[1], 1);
4845         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4846         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4847
4848         assert_eq!(revoked_htlc_txn.len(), 1);
4849         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4850         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4851         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4852
4853         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4854         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4855         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4856
4857         // A will generate justice tx from B's revoked commitment/HTLC tx
4858         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4859         check_closed_broadcast!(nodes[0], true);
4860         check_added_monitors!(nodes[0], 1);
4861         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4862
4863         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4864         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4865
4866         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4867         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4868         // transactions next...
4869         assert_eq!(node_txn[0].input.len(), 2);
4870         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4871         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4872                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4873         } else {
4874                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4875                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4876         }
4877
4878         assert_eq!(node_txn[1].input.len(), 1);
4879         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4880
4881         mine_transaction(&nodes[0], &node_txn[1]);
4882         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4883
4884         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4885         // didn't try to generate any new transactions.
4886
4887         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4888         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4889         assert_eq!(spend_txn.len(), 3);
4890         assert_eq!(spend_txn[0].input.len(), 1);
4891         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4892         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4893         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4894         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4895 }
4896
4897 #[test]
4898 fn test_onchain_to_onchain_claim() {
4899         // Test that in case of channel closure, we detect the state of output and claim HTLC
4900         // on downstream peer's remote commitment tx.
4901         // First, have C claim an HTLC against its own latest commitment transaction.
4902         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4903         // channel.
4904         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4905         // gets broadcast.
4906
4907         let chanmon_cfgs = create_chanmon_cfgs(3);
4908         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4909         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4910         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4911
4912         // Create some initial channels
4913         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4914         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4915
4916         // Ensure all nodes are at the same height
4917         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4918         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4919         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4920         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4921
4922         // Rebalance the network a bit by relaying one payment through all the channels ...
4923         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4924         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4925
4926         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4927         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4928         check_spends!(commitment_tx[0], chan_2.3);
4929         nodes[2].node.claim_funds(payment_preimage);
4930         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4931         check_added_monitors!(nodes[2], 1);
4932         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4933         assert!(updates.update_add_htlcs.is_empty());
4934         assert!(updates.update_fail_htlcs.is_empty());
4935         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4936         assert!(updates.update_fail_malformed_htlcs.is_empty());
4937
4938         mine_transaction(&nodes[2], &commitment_tx[0]);
4939         check_closed_broadcast!(nodes[2], true);
4940         check_added_monitors!(nodes[2], 1);
4941         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4942
4943         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4944         assert_eq!(c_txn.len(), 1);
4945         check_spends!(c_txn[0], commitment_tx[0]);
4946         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4947         assert!(c_txn[0].output[0].script_pubkey.is_p2wsh()); // revokeable output
4948         assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4949
4950         // 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
4951         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4952         check_added_monitors!(nodes[1], 1);
4953         let events = nodes[1].node.get_and_clear_pending_events();
4954         assert_eq!(events.len(), 2);
4955         match events[0] {
4956                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4957                 _ => panic!("Unexpected event"),
4958         }
4959         match events[1] {
4960                 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
4961                         next_channel_id, outbound_amount_forwarded_msat, ..
4962                 } => {
4963                         assert_eq!(total_fee_earned_msat, Some(1000));
4964                         assert_eq!(prev_channel_id, Some(chan_1.2));
4965                         assert_eq!(claim_from_onchain_tx, true);
4966                         assert_eq!(next_channel_id, Some(chan_2.2));
4967                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4968                 },
4969                 _ => panic!("Unexpected event"),
4970         }
4971         check_added_monitors!(nodes[1], 1);
4972         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4973         assert_eq!(msg_events.len(), 3);
4974         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4975         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4976
4977         match nodes_2_event {
4978                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4979                 _ => panic!("Unexpected event"),
4980         }
4981
4982         match nodes_0_event {
4983                 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, .. } } => {
4984                         assert!(update_add_htlcs.is_empty());
4985                         assert!(update_fail_htlcs.is_empty());
4986                         assert_eq!(update_fulfill_htlcs.len(), 1);
4987                         assert!(update_fail_malformed_htlcs.is_empty());
4988                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4989                 },
4990                 _ => panic!("Unexpected event"),
4991         };
4992
4993         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4994         match msg_events[0] {
4995                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4996                 _ => panic!("Unexpected event"),
4997         }
4998
4999         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5000         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5001         mine_transaction(&nodes[1], &commitment_tx[0]);
5002         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5003         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5004         // ChannelMonitor: HTLC-Success tx
5005         assert_eq!(b_txn.len(), 1);
5006         check_spends!(b_txn[0], commitment_tx[0]);
5007         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5008         assert!(b_txn[0].output[0].script_pubkey.is_p2wpkh()); // direct payment
5009         assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
5010
5011         check_closed_broadcast!(nodes[1], true);
5012         check_added_monitors!(nodes[1], 1);
5013 }
5014
5015 #[test]
5016 fn test_duplicate_payment_hash_one_failure_one_success() {
5017         // Topology : A --> B --> C --> D
5018         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5019         // Note that because C will refuse to generate two payment secrets for the same payment hash,
5020         // we forward one of the payments onwards to D.
5021         let chanmon_cfgs = create_chanmon_cfgs(4);
5022         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5023         // When this test was written, the default base fee floated based on the HTLC count.
5024         // It is now fixed, so we simply set the fee to the expected value here.
5025         let mut config = test_default_channel_config();
5026         config.channel_config.forwarding_fee_base_msat = 196;
5027         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5028                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5029         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5030
5031         create_announced_chan_between_nodes(&nodes, 0, 1);
5032         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5033         create_announced_chan_between_nodes(&nodes, 2, 3);
5034
5035         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5036         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5037         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5038         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5039         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5040
5041         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5042
5043         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
5044         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5045         // script push size limit so that the below script length checks match
5046         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5047         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
5048                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
5049         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5050         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5051
5052         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5053         assert_eq!(commitment_txn[0].input.len(), 1);
5054         check_spends!(commitment_txn[0], chan_2.3);
5055
5056         mine_transaction(&nodes[1], &commitment_txn[0]);
5057         check_closed_broadcast!(nodes[1], true);
5058         check_added_monitors!(nodes[1], 1);
5059         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5060         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5061
5062         let htlc_timeout_tx;
5063         { // Extract one of the two HTLC-Timeout transaction
5064                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5065                 // ChannelMonitor: timeout tx * 2-or-3
5066                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5067
5068                 check_spends!(node_txn[0], commitment_txn[0]);
5069                 assert_eq!(node_txn[0].input.len(), 1);
5070                 assert_eq!(node_txn[0].output.len(), 1);
5071
5072                 if node_txn.len() > 2 {
5073                         check_spends!(node_txn[1], commitment_txn[0]);
5074                         assert_eq!(node_txn[1].input.len(), 1);
5075                         assert_eq!(node_txn[1].output.len(), 1);
5076                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5077
5078                         check_spends!(node_txn[2], commitment_txn[0]);
5079                         assert_eq!(node_txn[2].input.len(), 1);
5080                         assert_eq!(node_txn[2].output.len(), 1);
5081                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5082                 } else {
5083                         check_spends!(node_txn[1], commitment_txn[0]);
5084                         assert_eq!(node_txn[1].input.len(), 1);
5085                         assert_eq!(node_txn[1].output.len(), 1);
5086                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5087                 }
5088
5089                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5090                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5091                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5092                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5093                 if node_txn.len() > 2 {
5094                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5095                         htlc_timeout_tx = if node_txn[2].output[0].value.to_sat() < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5096                 } else {
5097                         htlc_timeout_tx = if node_txn[0].output[0].value.to_sat() < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5098                 }
5099         }
5100
5101         nodes[2].node.claim_funds(our_payment_preimage);
5102         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5103
5104         mine_transaction(&nodes[2], &commitment_txn[0]);
5105         check_added_monitors!(nodes[2], 2);
5106         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5107         let events = nodes[2].node.get_and_clear_pending_msg_events();
5108         match events[0] {
5109                 MessageSendEvent::UpdateHTLCs { .. } => {},
5110                 _ => panic!("Unexpected event"),
5111         }
5112         match events[2] {
5113                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5114                 _ => panic!("Unexepected event"),
5115         }
5116         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5117         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5118         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5119         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5120         assert_eq!(htlc_success_txn[0].input.len(), 1);
5121         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5122         assert_eq!(htlc_success_txn[1].input.len(), 1);
5123         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5124         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5125         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5126
5127         mine_transaction(&nodes[1], &htlc_timeout_tx);
5128         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5129         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 }]);
5130         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5131         assert!(htlc_updates.update_add_htlcs.is_empty());
5132         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5133         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5134         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5135         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5136         check_added_monitors!(nodes[1], 1);
5137
5138         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5139         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5140         {
5141                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5142         }
5143         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5144
5145         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5146         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5147         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5148         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5149         assert!(updates.update_add_htlcs.is_empty());
5150         assert!(updates.update_fail_htlcs.is_empty());
5151         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5152         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5153         assert!(updates.update_fail_malformed_htlcs.is_empty());
5154         check_added_monitors!(nodes[1], 1);
5155
5156         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5157         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5158         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5159 }
5160
5161 #[test]
5162 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5163         let chanmon_cfgs = create_chanmon_cfgs(2);
5164         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5165         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5166         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5167
5168         // Create some initial channels
5169         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5170
5171         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5172         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5173         assert_eq!(local_txn.len(), 1);
5174         assert_eq!(local_txn[0].input.len(), 1);
5175         check_spends!(local_txn[0], chan_1.3);
5176
5177         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5178         nodes[1].node.claim_funds(payment_preimage);
5179         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5180         check_added_monitors!(nodes[1], 1);
5181
5182         mine_transaction(&nodes[1], &local_txn[0]);
5183         check_added_monitors!(nodes[1], 1);
5184         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5185         let events = nodes[1].node.get_and_clear_pending_msg_events();
5186         match events[0] {
5187                 MessageSendEvent::UpdateHTLCs { .. } => {},
5188                 _ => panic!("Unexpected event"),
5189         }
5190         match events[2] {
5191                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5192                 _ => panic!("Unexepected event"),
5193         }
5194         let node_tx = {
5195                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5196                 assert_eq!(node_txn.len(), 1);
5197                 assert_eq!(node_txn[0].input.len(), 1);
5198                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5199                 check_spends!(node_txn[0], local_txn[0]);
5200                 node_txn[0].clone()
5201         };
5202
5203         mine_transaction(&nodes[1], &node_tx);
5204         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5205
5206         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5207         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5208         assert_eq!(spend_txn.len(), 1);
5209         assert_eq!(spend_txn[0].input.len(), 1);
5210         check_spends!(spend_txn[0], node_tx);
5211         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5212 }
5213
5214 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5215         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5216         // unrevoked commitment transaction.
5217         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5218         // a remote RAA before they could be failed backwards (and combinations thereof).
5219         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5220         // use the same payment hashes.
5221         // Thus, we use a six-node network:
5222         //
5223         // A \         / E
5224         //    - C - D -
5225         // B /         \ F
5226         // And test where C fails back to A/B when D announces its latest commitment transaction
5227         let chanmon_cfgs = create_chanmon_cfgs(6);
5228         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5229         // When this test was written, the default base fee floated based on the HTLC count.
5230         // It is now fixed, so we simply set the fee to the expected value here.
5231         let mut config = test_default_channel_config();
5232         config.channel_config.forwarding_fee_base_msat = 196;
5233         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5234                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5235         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5236
5237         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5238         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5239         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5240         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5241         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5242
5243         // Rebalance and check output sanity...
5244         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5245         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5246         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5247
5248         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5249                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5250         // 0th HTLC:
5251         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
5252         // 1st HTLC:
5253         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
5254         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5255         // 2nd HTLC:
5256         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
5257         // 3rd HTLC:
5258         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
5259         // 4th HTLC:
5260         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5261         // 5th HTLC:
5262         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5263         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5264         // 6th HTLC:
5265         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());
5266         // 7th HTLC:
5267         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());
5268
5269         // 8th HTLC:
5270         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5271         // 9th HTLC:
5272         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5273         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
5274
5275         // 10th HTLC:
5276         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
5277         // 11th HTLC:
5278         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5279         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());
5280
5281         // Double-check that six of the new HTLC were added
5282         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5283         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5284         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5285         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5286
5287         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5288         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5289         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5290         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5291         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5292         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5293         check_added_monitors!(nodes[4], 0);
5294
5295         let failed_destinations = vec![
5296                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5297                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5298                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5299                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5300         ];
5301         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5302         check_added_monitors!(nodes[4], 1);
5303
5304         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5305         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5306         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5307         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5308         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5309         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5310
5311         // Fail 3rd below-dust and 7th above-dust HTLCs
5312         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5313         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5314         check_added_monitors!(nodes[5], 0);
5315
5316         let failed_destinations_2 = vec![
5317                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5318                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5319         ];
5320         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5321         check_added_monitors!(nodes[5], 1);
5322
5323         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5324         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5325         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5326         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5327
5328         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5329
5330         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5331         let failed_destinations_3 = vec![
5332                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5333                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5334                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5335                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5336                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5337                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5338         ];
5339         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5340         check_added_monitors!(nodes[3], 1);
5341         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5342         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5343         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5344         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5345         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5346         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5347         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5348         if deliver_last_raa {
5349                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5350         } else {
5351                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5352         }
5353
5354         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5355         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5356         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5357         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5358         //
5359         // We now broadcast the latest commitment transaction, which *should* result in failures for
5360         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5361         // the non-broadcast above-dust HTLCs.
5362         //
5363         // Alternatively, we may broadcast the previous commitment transaction, which should only
5364         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5365         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5366
5367         if announce_latest {
5368                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5369         } else {
5370                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5371         }
5372         let events = nodes[2].node.get_and_clear_pending_events();
5373         let close_event = if deliver_last_raa {
5374                 assert_eq!(events.len(), 2 + 6);
5375                 events.last().clone().unwrap()
5376         } else {
5377                 assert_eq!(events.len(), 1);
5378                 events.last().clone().unwrap()
5379         };
5380         match close_event {
5381                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5382                 _ => panic!("Unexpected event"),
5383         }
5384
5385         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5386         check_closed_broadcast!(nodes[2], true);
5387         if deliver_last_raa {
5388                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[1..2], true);
5389
5390                 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();
5391                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5392         } else {
5393                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5394                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5395                 } else {
5396                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5397                 };
5398
5399                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5400         }
5401         check_added_monitors!(nodes[2], 3);
5402
5403         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5404         assert_eq!(cs_msgs.len(), 2);
5405         let mut a_done = false;
5406         for msg in cs_msgs {
5407                 match msg {
5408                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5409                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5410                                 // should be failed-backwards here.
5411                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5412                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5413                                         for htlc in &updates.update_fail_htlcs {
5414                                                 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 });
5415                                         }
5416                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5417                                         assert!(!a_done);
5418                                         a_done = true;
5419                                         &nodes[0]
5420                                 } else {
5421                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5422                                         for htlc in &updates.update_fail_htlcs {
5423                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5424                                         }
5425                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5426                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5427                                         &nodes[1]
5428                                 };
5429                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5430                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5431                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5432                                 if announce_latest {
5433                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5434                                         if *node_id == nodes[0].node.get_our_node_id() {
5435                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5436                                         }
5437                                 }
5438                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5439                         },
5440                         _ => panic!("Unexpected event"),
5441                 }
5442         }
5443
5444         let as_events = nodes[0].node.get_and_clear_pending_events();
5445         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5446         let mut as_faileds = new_hash_set();
5447         let mut as_updates = 0;
5448         for event in as_events.iter() {
5449                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5450                         assert!(as_faileds.insert(*payment_hash));
5451                         if *payment_hash != payment_hash_2 {
5452                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5453                         } else {
5454                                 assert!(!payment_failed_permanently);
5455                         }
5456                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5457                                 as_updates += 1;
5458                         }
5459                 } else if let &Event::PaymentFailed { .. } = event {
5460                 } else { panic!("Unexpected event"); }
5461         }
5462         assert!(as_faileds.contains(&payment_hash_1));
5463         assert!(as_faileds.contains(&payment_hash_2));
5464         if announce_latest {
5465                 assert!(as_faileds.contains(&payment_hash_3));
5466                 assert!(as_faileds.contains(&payment_hash_5));
5467         }
5468         assert!(as_faileds.contains(&payment_hash_6));
5469
5470         let bs_events = nodes[1].node.get_and_clear_pending_events();
5471         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5472         let mut bs_faileds = new_hash_set();
5473         let mut bs_updates = 0;
5474         for event in bs_events.iter() {
5475                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5476                         assert!(bs_faileds.insert(*payment_hash));
5477                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5478                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5479                         } else {
5480                                 assert!(!payment_failed_permanently);
5481                         }
5482                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5483                                 bs_updates += 1;
5484                         }
5485                 } else if let &Event::PaymentFailed { .. } = event {
5486                 } else { panic!("Unexpected event"); }
5487         }
5488         assert!(bs_faileds.contains(&payment_hash_1));
5489         assert!(bs_faileds.contains(&payment_hash_2));
5490         if announce_latest {
5491                 assert!(bs_faileds.contains(&payment_hash_4));
5492         }
5493         assert!(bs_faileds.contains(&payment_hash_5));
5494
5495         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5496         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5497         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5498         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5499         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5500         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5501 }
5502
5503 #[test]
5504 fn test_fail_backwards_latest_remote_announce_a() {
5505         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5506 }
5507
5508 #[test]
5509 fn test_fail_backwards_latest_remote_announce_b() {
5510         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5511 }
5512
5513 #[test]
5514 fn test_fail_backwards_previous_remote_announce() {
5515         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5516         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5517         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5518 }
5519
5520 #[test]
5521 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5522         let chanmon_cfgs = create_chanmon_cfgs(2);
5523         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5524         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5525         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5526
5527         // Create some initial channels
5528         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5529
5530         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5531         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5532         assert_eq!(local_txn[0].input.len(), 1);
5533         check_spends!(local_txn[0], chan_1.3);
5534
5535         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5536         mine_transaction(&nodes[0], &local_txn[0]);
5537         check_closed_broadcast!(nodes[0], true);
5538         check_added_monitors!(nodes[0], 1);
5539         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5540         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5541
5542         let htlc_timeout = {
5543                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5544                 assert_eq!(node_txn.len(), 1);
5545                 assert_eq!(node_txn[0].input.len(), 1);
5546                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5547                 check_spends!(node_txn[0], local_txn[0]);
5548                 node_txn[0].clone()
5549         };
5550
5551         mine_transaction(&nodes[0], &htlc_timeout);
5552         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5553         expect_payment_failed!(nodes[0], our_payment_hash, false);
5554
5555         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5556         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5557         assert_eq!(spend_txn.len(), 3);
5558         check_spends!(spend_txn[0], local_txn[0]);
5559         assert_eq!(spend_txn[1].input.len(), 1);
5560         check_spends!(spend_txn[1], htlc_timeout);
5561         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5562         assert_eq!(spend_txn[2].input.len(), 2);
5563         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5564         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5565                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5566 }
5567
5568 #[test]
5569 fn test_key_derivation_params() {
5570         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5571         // manager rotation to test that `channel_keys_id` returned in
5572         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5573         // then derive a `delayed_payment_key`.
5574
5575         let chanmon_cfgs = create_chanmon_cfgs(3);
5576
5577         // We manually create the node configuration to backup the seed.
5578         let seed = [42; 32];
5579         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5580         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);
5581         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5582         let scorer = RwLock::new(test_utils::TestScorer::new());
5583         let router = test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[0].logger, &scorer);
5584         let message_router = test_utils::TestMessageRouter::new(network_graph.clone(), &keys_manager);
5585         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)) };
5586         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5587         node_cfgs.remove(0);
5588         node_cfgs.insert(0, node);
5589
5590         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5591         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5592
5593         // Create some initial channels
5594         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5595         // for node 0
5596         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5597         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5598         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5599
5600         // Ensure all nodes are at the same height
5601         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5602         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5603         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5604         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5605
5606         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5607         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5608         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5609         assert_eq!(local_txn_1[0].input.len(), 1);
5610         check_spends!(local_txn_1[0], chan_1.3);
5611
5612         // We check funding pubkey are unique
5613         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]));
5614         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]));
5615         if from_0_funding_key_0 == from_1_funding_key_0
5616             || from_0_funding_key_0 == from_1_funding_key_1
5617             || from_0_funding_key_1 == from_1_funding_key_0
5618             || from_0_funding_key_1 == from_1_funding_key_1 {
5619                 panic!("Funding pubkeys aren't unique");
5620         }
5621
5622         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5623         mine_transaction(&nodes[0], &local_txn_1[0]);
5624         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5625         check_closed_broadcast!(nodes[0], true);
5626         check_added_monitors!(nodes[0], 1);
5627         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5628
5629         let htlc_timeout = {
5630                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5631                 assert_eq!(node_txn.len(), 1);
5632                 assert_eq!(node_txn[0].input.len(), 1);
5633                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5634                 check_spends!(node_txn[0], local_txn_1[0]);
5635                 node_txn[0].clone()
5636         };
5637
5638         mine_transaction(&nodes[0], &htlc_timeout);
5639         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5640         expect_payment_failed!(nodes[0], our_payment_hash, false);
5641
5642         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5643         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5644         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5645         assert_eq!(spend_txn.len(), 3);
5646         check_spends!(spend_txn[0], local_txn_1[0]);
5647         assert_eq!(spend_txn[1].input.len(), 1);
5648         check_spends!(spend_txn[1], htlc_timeout);
5649         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5650         assert_eq!(spend_txn[2].input.len(), 2);
5651         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5652         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5653                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5654 }
5655
5656 #[test]
5657 fn test_static_output_closing_tx() {
5658         let chanmon_cfgs = create_chanmon_cfgs(2);
5659         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5660         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5661         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5662
5663         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5664
5665         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5666         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5667
5668         mine_transaction(&nodes[0], &closing_tx);
5669         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5670         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5671
5672         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5673         assert_eq!(spend_txn.len(), 1);
5674         check_spends!(spend_txn[0], closing_tx);
5675
5676         mine_transaction(&nodes[1], &closing_tx);
5677         check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5678         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5679
5680         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5681         assert_eq!(spend_txn.len(), 1);
5682         check_spends!(spend_txn[0], closing_tx);
5683 }
5684
5685 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5686         let chanmon_cfgs = create_chanmon_cfgs(2);
5687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5689         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5690         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5691
5692         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5693
5694         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5695         // present in B's local commitment transaction, but none of A's commitment transactions.
5696         nodes[1].node.claim_funds(payment_preimage);
5697         check_added_monitors!(nodes[1], 1);
5698         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5699
5700         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5701         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5702         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5703
5704         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5705         check_added_monitors!(nodes[0], 1);
5706         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5707         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5708         check_added_monitors!(nodes[1], 1);
5709
5710         let starting_block = nodes[1].best_block_info();
5711         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5712         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5713                 connect_block(&nodes[1], &block);
5714                 block.header.prev_blockhash = block.block_hash();
5715         }
5716         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5717         check_closed_broadcast!(nodes[1], true);
5718         check_added_monitors!(nodes[1], 1);
5719         check_closed_event!(nodes[1], 1, ClosureReason::HTLCsTimedOut, [nodes[0].node.get_our_node_id()], 100000);
5720 }
5721
5722 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5723         let chanmon_cfgs = create_chanmon_cfgs(2);
5724         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5725         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5726         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5727         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5728
5729         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5730         nodes[0].node.send_payment_with_route(&route, payment_hash,
5731                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5732         check_added_monitors!(nodes[0], 1);
5733
5734         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5735
5736         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5737         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5738         // to "time out" the HTLC.
5739
5740         let starting_block = nodes[1].best_block_info();
5741         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5742
5743         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5744                 connect_block(&nodes[0], &block);
5745                 block.header.prev_blockhash = block.block_hash();
5746         }
5747         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5748         check_closed_broadcast!(nodes[0], true);
5749         check_added_monitors!(nodes[0], 1);
5750         check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5751 }
5752
5753 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5754         let chanmon_cfgs = create_chanmon_cfgs(3);
5755         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5756         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5757         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5758         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5759
5760         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5761         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5762         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5763         // actually revoked.
5764         let htlc_value = if use_dust { 50000 } else { 3000000 };
5765         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5766         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5767         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5768         check_added_monitors!(nodes[1], 1);
5769
5770         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5771         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5772         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5773         check_added_monitors!(nodes[0], 1);
5774         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5775         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5776         check_added_monitors!(nodes[1], 1);
5777         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5778         check_added_monitors!(nodes[1], 1);
5779         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5780
5781         if check_revoke_no_close {
5782                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5783                 check_added_monitors!(nodes[0], 1);
5784         }
5785
5786         let starting_block = nodes[1].best_block_info();
5787         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5788         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5789                 connect_block(&nodes[0], &block);
5790                 block.header.prev_blockhash = block.block_hash();
5791         }
5792         if !check_revoke_no_close {
5793                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5794                 check_closed_broadcast!(nodes[0], true);
5795                 check_added_monitors!(nodes[0], 1);
5796                 check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5797         } else {
5798                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5799         }
5800 }
5801
5802 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5803 // There are only a few cases to test here:
5804 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5805 //    broadcastable commitment transactions result in channel closure,
5806 //  * its included in an unrevoked-but-previous remote commitment transaction,
5807 //  * its included in the latest remote or local commitment transactions.
5808 // We test each of the three possible commitment transactions individually and use both dust and
5809 // non-dust HTLCs.
5810 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5811 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5812 // tested for at least one of the cases in other tests.
5813 #[test]
5814 fn htlc_claim_single_commitment_only_a() {
5815         do_htlc_claim_local_commitment_only(true);
5816         do_htlc_claim_local_commitment_only(false);
5817
5818         do_htlc_claim_current_remote_commitment_only(true);
5819         do_htlc_claim_current_remote_commitment_only(false);
5820 }
5821
5822 #[test]
5823 fn htlc_claim_single_commitment_only_b() {
5824         do_htlc_claim_previous_remote_commitment_only(true, false);
5825         do_htlc_claim_previous_remote_commitment_only(false, false);
5826         do_htlc_claim_previous_remote_commitment_only(true, true);
5827         do_htlc_claim_previous_remote_commitment_only(false, true);
5828 }
5829
5830 #[test]
5831 #[should_panic]
5832 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5833         let chanmon_cfgs = create_chanmon_cfgs(2);
5834         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5835         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5836         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5837         // Force duplicate randomness for every get-random call
5838         for node in nodes.iter() {
5839                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5840         }
5841
5842         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5843         let channel_value_satoshis=10000;
5844         let push_msat=10001;
5845         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5846         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5847         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5848         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5849
5850         // Create a second channel with the same random values. This used to panic due to a colliding
5851         // channel_id, but now panics due to a colliding outbound SCID alias.
5852         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5853 }
5854
5855 #[test]
5856 fn bolt2_open_channel_sending_node_checks_part2() {
5857         let chanmon_cfgs = create_chanmon_cfgs(2);
5858         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5859         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5860         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5861
5862         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5863         let channel_value_satoshis=2^24;
5864         let push_msat=10001;
5865         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5866
5867         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5868         let channel_value_satoshis=10000;
5869         // Test when push_msat is equal to 1000 * funding_satoshis.
5870         let push_msat=1000*channel_value_satoshis+1;
5871         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5872
5873         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5874         let channel_value_satoshis=10000;
5875         let push_msat=10001;
5876         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
5877         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5878         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.common_fields.dust_limit_satoshis);
5879
5880         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5881         // 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
5882         assert!(node0_to_1_send_open_channel.common_fields.channel_flags<=1);
5883
5884         // 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.
5885         assert!(BREAKDOWN_TIMEOUT>0);
5886         assert!(node0_to_1_send_open_channel.common_fields.to_self_delay==BREAKDOWN_TIMEOUT);
5887
5888         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5889         let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5890         assert_eq!(node0_to_1_send_open_channel.common_fields.chain_hash, chain_hash);
5891
5892         // 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.
5893         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.funding_pubkey.serialize()).is_ok());
5894         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.revocation_basepoint.serialize()).is_ok());
5895         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.htlc_basepoint.serialize()).is_ok());
5896         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.payment_basepoint.serialize()).is_ok());
5897         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.delayed_payment_basepoint.serialize()).is_ok());
5898 }
5899
5900 #[test]
5901 fn bolt2_open_channel_sane_dust_limit() {
5902         let chanmon_cfgs = create_chanmon_cfgs(2);
5903         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5904         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5905         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5906
5907         let channel_value_satoshis=1000000;
5908         let push_msat=10001;
5909         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5910         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5911         node0_to_1_send_open_channel.common_fields.dust_limit_satoshis = 547;
5912         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5913
5914         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5915         let events = nodes[1].node.get_and_clear_pending_msg_events();
5916         let err_msg = match events[0] {
5917                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5918                         msg.clone()
5919                 },
5920                 _ => panic!("Unexpected event"),
5921         };
5922         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5923 }
5924
5925 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5926 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5927 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5928 // is no longer affordable once it's freed.
5929 #[test]
5930 fn test_fail_holding_cell_htlc_upon_free() {
5931         let chanmon_cfgs = create_chanmon_cfgs(2);
5932         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5933         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5934         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5935         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5936
5937         // First nodes[0] generates an update_fee, setting the channel's
5938         // pending_update_fee.
5939         {
5940                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5941                 *feerate_lock += 20;
5942         }
5943         nodes[0].node.timer_tick_occurred();
5944         check_added_monitors!(nodes[0], 1);
5945
5946         let events = nodes[0].node.get_and_clear_pending_msg_events();
5947         assert_eq!(events.len(), 1);
5948         let (update_msg, commitment_signed) = match events[0] {
5949                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5950                         (update_fee.as_ref(), commitment_signed)
5951                 },
5952                 _ => panic!("Unexpected event"),
5953         };
5954
5955         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5956
5957         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5958         let channel_reserve = chan_stat.channel_reserve_msat;
5959         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5960         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5961
5962         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5963         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5964         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5965
5966         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5967         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5968                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5969         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5970         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5971
5972         // Flush the pending fee update.
5973         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5974         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5975         check_added_monitors!(nodes[1], 1);
5976         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5977         check_added_monitors!(nodes[0], 1);
5978
5979         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5980         // HTLC, but now that the fee has been raised the payment will now fail, causing
5981         // us to surface its failure to the user.
5982         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5983         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5984         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5985
5986         // Check that the payment failed to be sent out.
5987         let events = nodes[0].node.get_and_clear_pending_events();
5988         assert_eq!(events.len(), 2);
5989         match &events[0] {
5990                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5991                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5992                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5993                         assert_eq!(*payment_failed_permanently, false);
5994                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5995                 },
5996                 _ => panic!("Unexpected event"),
5997         }
5998         match &events[1] {
5999                 &Event::PaymentFailed { ref payment_hash, .. } => {
6000                         assert_eq!(our_payment_hash.clone(), *payment_hash);
6001                 },
6002                 _ => panic!("Unexpected event"),
6003         }
6004 }
6005
6006 // Test that if multiple HTLCs are released from the holding cell and one is
6007 // valid but the other is no longer valid upon release, the valid HTLC can be
6008 // successfully completed while the other one fails as expected.
6009 #[test]
6010 fn test_free_and_fail_holding_cell_htlcs() {
6011         let chanmon_cfgs = create_chanmon_cfgs(2);
6012         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6013         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6014         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6015         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6016
6017         // First nodes[0] generates an update_fee, setting the channel's
6018         // pending_update_fee.
6019         {
6020                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6021                 *feerate_lock += 200;
6022         }
6023         nodes[0].node.timer_tick_occurred();
6024         check_added_monitors!(nodes[0], 1);
6025
6026         let events = nodes[0].node.get_and_clear_pending_msg_events();
6027         assert_eq!(events.len(), 1);
6028         let (update_msg, commitment_signed) = match events[0] {
6029                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6030                         (update_fee.as_ref(), commitment_signed)
6031                 },
6032                 _ => panic!("Unexpected event"),
6033         };
6034
6035         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6036
6037         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6038         let channel_reserve = chan_stat.channel_reserve_msat;
6039         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6040         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6041
6042         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6043         let amt_1 = 20000;
6044         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
6045         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6046         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6047
6048         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6049         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
6050                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6051         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6052         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6053         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6054         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6055                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6056         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6057         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6058
6059         // Flush the pending fee update.
6060         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6061         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6062         check_added_monitors!(nodes[1], 1);
6063         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6064         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6065         check_added_monitors!(nodes[0], 2);
6066
6067         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6068         // but now that the fee has been raised the second payment will now fail, causing us
6069         // to surface its failure to the user. The first payment should succeed.
6070         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6071         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6072         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6073
6074         // Check that the second payment failed to be sent out.
6075         let events = nodes[0].node.get_and_clear_pending_events();
6076         assert_eq!(events.len(), 2);
6077         match &events[0] {
6078                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6079                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6080                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6081                         assert_eq!(*payment_failed_permanently, false);
6082                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6083                 },
6084                 _ => panic!("Unexpected event"),
6085         }
6086         match &events[1] {
6087                 &Event::PaymentFailed { ref payment_hash, .. } => {
6088                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6089                 },
6090                 _ => panic!("Unexpected event"),
6091         }
6092
6093         // Complete the first payment and the RAA from the fee update.
6094         let (payment_event, send_raa_event) = {
6095                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6096                 assert_eq!(msgs.len(), 2);
6097                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6098         };
6099         let raa = match send_raa_event {
6100                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6101                 _ => panic!("Unexpected event"),
6102         };
6103         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6104         check_added_monitors!(nodes[1], 1);
6105         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6106         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6107         let events = nodes[1].node.get_and_clear_pending_events();
6108         assert_eq!(events.len(), 1);
6109         match events[0] {
6110                 Event::PendingHTLCsForwardable { .. } => {},
6111                 _ => panic!("Unexpected event"),
6112         }
6113         nodes[1].node.process_pending_htlc_forwards();
6114         let events = nodes[1].node.get_and_clear_pending_events();
6115         assert_eq!(events.len(), 1);
6116         match events[0] {
6117                 Event::PaymentClaimable { .. } => {},
6118                 _ => panic!("Unexpected event"),
6119         }
6120         nodes[1].node.claim_funds(payment_preimage_1);
6121         check_added_monitors!(nodes[1], 1);
6122         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6123
6124         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6125         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6126         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6127         expect_payment_sent!(nodes[0], payment_preimage_1);
6128 }
6129
6130 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6131 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6132 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6133 // once it's freed.
6134 #[test]
6135 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6136         let chanmon_cfgs = create_chanmon_cfgs(3);
6137         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6138         // Avoid having to include routing fees in calculations
6139         let mut config = test_default_channel_config();
6140         config.channel_config.forwarding_fee_base_msat = 0;
6141         config.channel_config.forwarding_fee_proportional_millionths = 0;
6142         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6143         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6144         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6145         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6146
6147         // First nodes[1] generates an update_fee, setting the channel's
6148         // pending_update_fee.
6149         {
6150                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6151                 *feerate_lock += 20;
6152         }
6153         nodes[1].node.timer_tick_occurred();
6154         check_added_monitors!(nodes[1], 1);
6155
6156         let events = nodes[1].node.get_and_clear_pending_msg_events();
6157         assert_eq!(events.len(), 1);
6158         let (update_msg, commitment_signed) = match events[0] {
6159                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6160                         (update_fee.as_ref(), commitment_signed)
6161                 },
6162                 _ => panic!("Unexpected event"),
6163         };
6164
6165         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6166
6167         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6168         let channel_reserve = chan_stat.channel_reserve_msat;
6169         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6170         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6171
6172         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6173         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6174         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6175         let payment_event = {
6176                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6177                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6178                 check_added_monitors!(nodes[0], 1);
6179
6180                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6181                 assert_eq!(events.len(), 1);
6182
6183                 SendEvent::from_event(events.remove(0))
6184         };
6185         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6186         check_added_monitors!(nodes[1], 0);
6187         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6188         expect_pending_htlcs_forwardable!(nodes[1]);
6189
6190         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6191         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6192
6193         // Flush the pending fee update.
6194         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6195         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6196         check_added_monitors!(nodes[2], 1);
6197         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6198         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6199         check_added_monitors!(nodes[1], 2);
6200
6201         // A final RAA message is generated to finalize the fee update.
6202         let events = nodes[1].node.get_and_clear_pending_msg_events();
6203         assert_eq!(events.len(), 1);
6204
6205         let raa_msg = match &events[0] {
6206                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6207                         msg.clone()
6208                 },
6209                 _ => panic!("Unexpected event"),
6210         };
6211
6212         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6213         check_added_monitors!(nodes[2], 1);
6214         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6215
6216         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6217         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6218         assert_eq!(process_htlc_forwards_event.len(), 2);
6219         match &process_htlc_forwards_event[1] {
6220                 &Event::PendingHTLCsForwardable { .. } => {},
6221                 _ => panic!("Unexpected event"),
6222         }
6223
6224         // In response, we call ChannelManager's process_pending_htlc_forwards
6225         nodes[1].node.process_pending_htlc_forwards();
6226         check_added_monitors!(nodes[1], 1);
6227
6228         // This causes the HTLC to be failed backwards.
6229         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6230         assert_eq!(fail_event.len(), 1);
6231         let (fail_msg, commitment_signed) = match &fail_event[0] {
6232                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6233                         assert_eq!(updates.update_add_htlcs.len(), 0);
6234                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6235                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6236                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6237                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6238                 },
6239                 _ => panic!("Unexpected event"),
6240         };
6241
6242         // Pass the failure messages back to nodes[0].
6243         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6244         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6245
6246         // Complete the HTLC failure+removal process.
6247         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6248         check_added_monitors!(nodes[0], 1);
6249         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6250         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6251         check_added_monitors!(nodes[1], 2);
6252         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6253         assert_eq!(final_raa_event.len(), 1);
6254         let raa = match &final_raa_event[0] {
6255                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6256                 _ => panic!("Unexpected event"),
6257         };
6258         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6259         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6260         check_added_monitors!(nodes[0], 1);
6261 }
6262
6263 #[test]
6264 fn test_payment_route_reaching_same_channel_twice() {
6265         //A route should not go through the same channel twice
6266         //It is enforced when constructing a route.
6267         let chanmon_cfgs = create_chanmon_cfgs(2);
6268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6270         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6271         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6272
6273         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6274                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6275         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6276
6277         // Extend the path by itself, essentially simulating route going through same channel twice
6278         let cloned_hops = route.paths[0].hops.clone();
6279         route.paths[0].hops.extend_from_slice(&cloned_hops);
6280
6281         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6282                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6283         ), false, APIError::InvalidRoute { ref err },
6284         assert_eq!(err, &"Path went through the same channel twice"));
6285 }
6286
6287 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6288 // 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.
6289 //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.
6290
6291 #[test]
6292 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6293         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6294         let chanmon_cfgs = create_chanmon_cfgs(2);
6295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6297         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6298         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6299
6300         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6301         route.paths[0].hops[0].fee_msat = 100;
6302
6303         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6304                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6305                 ), true, APIError::ChannelUnavailable { .. }, {});
6306         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6307 }
6308
6309 #[test]
6310 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6311         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6312         let chanmon_cfgs = create_chanmon_cfgs(2);
6313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6315         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6316         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6317
6318         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6319         route.paths[0].hops[0].fee_msat = 0;
6320         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6321                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6322                 true, APIError::ChannelUnavailable { ref err },
6323                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6324
6325         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6326         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6327 }
6328
6329 #[test]
6330 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6331         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6332         let chanmon_cfgs = create_chanmon_cfgs(2);
6333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6335         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6336         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6337
6338         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6339         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6340                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6341         check_added_monitors!(nodes[0], 1);
6342         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6343         updates.update_add_htlcs[0].amount_msat = 0;
6344
6345         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6346         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC", 3);
6347         check_closed_broadcast!(nodes[1], true).unwrap();
6348         check_added_monitors!(nodes[1], 1);
6349         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6350                 [nodes[0].node.get_our_node_id()], 100000);
6351 }
6352
6353 #[test]
6354 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6355         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6356         //It is enforced when constructing a route.
6357         let chanmon_cfgs = create_chanmon_cfgs(2);
6358         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6359         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6360         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6361         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6362
6363         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6364                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6365         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6366         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6367         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6368                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6369                 ), true, APIError::InvalidRoute { ref err },
6370                 assert_eq!(err, &"Channel CLTV overflowed?"));
6371 }
6372
6373 #[test]
6374 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6375         //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.
6376         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6377         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6378         let chanmon_cfgs = create_chanmon_cfgs(2);
6379         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6380         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6381         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6382         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6383         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6384                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6385
6386         // Fetch a route in advance as we will be unable to once we're unable to send.
6387         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6388         for i in 0..max_accepted_htlcs {
6389                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6390                 let payment_event = {
6391                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6392                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6393                         check_added_monitors!(nodes[0], 1);
6394
6395                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6396                         assert_eq!(events.len(), 1);
6397                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6398                                 assert_eq!(htlcs[0].htlc_id, i);
6399                         } else {
6400                                 assert!(false);
6401                         }
6402                         SendEvent::from_event(events.remove(0))
6403                 };
6404                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6405                 check_added_monitors!(nodes[1], 0);
6406                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6407
6408                 expect_pending_htlcs_forwardable!(nodes[1]);
6409                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6410         }
6411         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6412                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6413                 ), true, APIError::ChannelUnavailable { .. }, {});
6414
6415         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6416 }
6417
6418 #[test]
6419 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6420         //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.
6421         let chanmon_cfgs = create_chanmon_cfgs(2);
6422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6424         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6425         let channel_value = 100000;
6426         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6427         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6428
6429         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6430
6431         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6432         // Manually create a route over our max in flight (which our router normally automatically
6433         // limits us to.
6434         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6435         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6436                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6437                 ), true, APIError::ChannelUnavailable { .. }, {});
6438         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6439
6440         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6441 }
6442
6443 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6444 #[test]
6445 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6446         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6447         let chanmon_cfgs = create_chanmon_cfgs(2);
6448         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6449         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6450         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6451         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6452         let htlc_minimum_msat: u64;
6453         {
6454                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6455                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6456                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6457                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6458         }
6459
6460         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6461         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6462                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6463         check_added_monitors!(nodes[0], 1);
6464         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6465         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6466         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6467         assert!(nodes[1].node.list_channels().is_empty());
6468         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6469         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()));
6470         check_added_monitors!(nodes[1], 1);
6471         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6472 }
6473
6474 #[test]
6475 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6476         //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
6477         let chanmon_cfgs = create_chanmon_cfgs(2);
6478         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6479         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6480         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6481         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6482
6483         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6484         let channel_reserve = chan_stat.channel_reserve_msat;
6485         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6486         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6487         // The 2* and +1 are for the fee spike reserve.
6488         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6489
6490         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6491         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6492         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6493                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6494         check_added_monitors!(nodes[0], 1);
6495         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6496
6497         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6498         // at this time channel-initiatee receivers are not required to enforce that senders
6499         // respect the fee_spike_reserve.
6500         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6501         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6502
6503         assert!(nodes[1].node.list_channels().is_empty());
6504         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6505         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6506         check_added_monitors!(nodes[1], 1);
6507         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6508 }
6509
6510 #[test]
6511 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6512         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6513         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6514         let chanmon_cfgs = create_chanmon_cfgs(2);
6515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6517         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6518         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6519
6520         let send_amt = 3999999;
6521         let (mut route, our_payment_hash, _, our_payment_secret) =
6522                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6523         route.paths[0].hops[0].fee_msat = send_amt;
6524         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6525         let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
6526         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6527         let recipient_onion_fields = RecipientOnionFields::secret_only(our_payment_secret);
6528         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6529                 &route.paths[0], send_amt, &recipient_onion_fields, cur_height, &None).unwrap();
6530         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6531
6532         let mut msg = msgs::UpdateAddHTLC {
6533                 channel_id: chan.2,
6534                 htlc_id: 0,
6535                 amount_msat: 1000,
6536                 payment_hash: our_payment_hash,
6537                 cltv_expiry: htlc_cltv,
6538                 onion_routing_packet: onion_packet.clone(),
6539                 skimmed_fee_msat: None,
6540                 blinding_point: None,
6541         };
6542
6543         for i in 0..50 {
6544                 msg.htlc_id = i as u64;
6545                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6546         }
6547         msg.htlc_id = (50) as u64;
6548         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6549
6550         assert!(nodes[1].node.list_channels().is_empty());
6551         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6552         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6553         check_added_monitors!(nodes[1], 1);
6554         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6555 }
6556
6557 #[test]
6558 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6559         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6560         let chanmon_cfgs = create_chanmon_cfgs(2);
6561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6563         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6564         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6565
6566         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6567         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6568                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6569         check_added_monitors!(nodes[0], 1);
6570         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6571         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;
6572         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6573
6574         assert!(nodes[1].node.list_channels().is_empty());
6575         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6576         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6577         check_added_monitors!(nodes[1], 1);
6578         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6579 }
6580
6581 #[test]
6582 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6583         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6584         let chanmon_cfgs = create_chanmon_cfgs(2);
6585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6587         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6588
6589         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6590         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6591         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6592                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6593         check_added_monitors!(nodes[0], 1);
6594         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6595         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6596         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6597
6598         assert!(nodes[1].node.list_channels().is_empty());
6599         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6600         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6601         check_added_monitors!(nodes[1], 1);
6602         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6603 }
6604
6605 #[test]
6606 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6607         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6608         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6609         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6610         let chanmon_cfgs = create_chanmon_cfgs(2);
6611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6613         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6614
6615         create_announced_chan_between_nodes(&nodes, 0, 1);
6616         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6617         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6618                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6619         check_added_monitors!(nodes[0], 1);
6620         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6621         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6622
6623         //Disconnect and Reconnect
6624         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6625         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6626         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6627                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6628         }, true).unwrap();
6629         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6630         assert_eq!(reestablish_1.len(), 1);
6631         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6632                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6633         }, false).unwrap();
6634         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6635         assert_eq!(reestablish_2.len(), 1);
6636         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6637         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6638         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6639         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6640
6641         //Resend HTLC
6642         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6643         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6644         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6645         check_added_monitors!(nodes[1], 1);
6646         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6647
6648         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6649
6650         assert!(nodes[1].node.list_channels().is_empty());
6651         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6652         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6653         check_added_monitors!(nodes[1], 1);
6654         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6655 }
6656
6657 #[test]
6658 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6659         //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.
6660
6661         let chanmon_cfgs = create_chanmon_cfgs(2);
6662         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6663         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6664         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6665         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6666         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6667         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6668                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6669
6670         check_added_monitors!(nodes[0], 1);
6671         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6672         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6673
6674         let update_msg = msgs::UpdateFulfillHTLC{
6675                 channel_id: chan.2,
6676                 htlc_id: 0,
6677                 payment_preimage: our_payment_preimage,
6678         };
6679
6680         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6681
6682         assert!(nodes[0].node.list_channels().is_empty());
6683         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6684         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()));
6685         check_added_monitors!(nodes[0], 1);
6686         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6687 }
6688
6689 #[test]
6690 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6691         //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.
6692
6693         let chanmon_cfgs = create_chanmon_cfgs(2);
6694         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6695         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6696         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6697         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6698
6699         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6700         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6701                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6702         check_added_monitors!(nodes[0], 1);
6703         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6704         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6705
6706         let update_msg = msgs::UpdateFailHTLC{
6707                 channel_id: chan.2,
6708                 htlc_id: 0,
6709                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6710         };
6711
6712         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6713
6714         assert!(nodes[0].node.list_channels().is_empty());
6715         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6716         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()));
6717         check_added_monitors!(nodes[0], 1);
6718         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6719 }
6720
6721 #[test]
6722 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6723         //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.
6724
6725         let chanmon_cfgs = create_chanmon_cfgs(2);
6726         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6727         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6728         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6729         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6730
6731         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6732         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6733                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6734         check_added_monitors!(nodes[0], 1);
6735         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6736         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6737         let update_msg = msgs::UpdateFailMalformedHTLC{
6738                 channel_id: chan.2,
6739                 htlc_id: 0,
6740                 sha256_of_onion: [1; 32],
6741                 failure_code: 0x8000,
6742         };
6743
6744         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6745
6746         assert!(nodes[0].node.list_channels().is_empty());
6747         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6748         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()));
6749         check_added_monitors!(nodes[0], 1);
6750         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6751 }
6752
6753 #[test]
6754 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6755         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6756
6757         let chanmon_cfgs = create_chanmon_cfgs(2);
6758         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6759         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6760         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6761         create_announced_chan_between_nodes(&nodes, 0, 1);
6762
6763         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6764
6765         nodes[1].node.claim_funds(our_payment_preimage);
6766         check_added_monitors!(nodes[1], 1);
6767         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6768
6769         let events = nodes[1].node.get_and_clear_pending_msg_events();
6770         assert_eq!(events.len(), 1);
6771         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6772                 match events[0] {
6773                         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, .. } } => {
6774                                 assert!(update_add_htlcs.is_empty());
6775                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6776                                 assert!(update_fail_htlcs.is_empty());
6777                                 assert!(update_fail_malformed_htlcs.is_empty());
6778                                 assert!(update_fee.is_none());
6779                                 update_fulfill_htlcs[0].clone()
6780                         },
6781                         _ => panic!("Unexpected event"),
6782                 }
6783         };
6784
6785         update_fulfill_msg.htlc_id = 1;
6786
6787         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6788
6789         assert!(nodes[0].node.list_channels().is_empty());
6790         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6791         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6792         check_added_monitors!(nodes[0], 1);
6793         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6794 }
6795
6796 #[test]
6797 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6798         //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.
6799
6800         let chanmon_cfgs = create_chanmon_cfgs(2);
6801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6804         create_announced_chan_between_nodes(&nodes, 0, 1);
6805
6806         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6807
6808         nodes[1].node.claim_funds(our_payment_preimage);
6809         check_added_monitors!(nodes[1], 1);
6810         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6811
6812         let events = nodes[1].node.get_and_clear_pending_msg_events();
6813         assert_eq!(events.len(), 1);
6814         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6815                 match events[0] {
6816                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6817                                 assert!(update_add_htlcs.is_empty());
6818                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6819                                 assert!(update_fail_htlcs.is_empty());
6820                                 assert!(update_fail_malformed_htlcs.is_empty());
6821                                 assert!(update_fee.is_none());
6822                                 update_fulfill_htlcs[0].clone()
6823                         },
6824                         _ => panic!("Unexpected event"),
6825                 }
6826         };
6827
6828         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6829
6830         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6831
6832         assert!(nodes[0].node.list_channels().is_empty());
6833         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6834         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6835         check_added_monitors!(nodes[0], 1);
6836         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6837 }
6838
6839 #[test]
6840 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6841         //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.
6842
6843         let chanmon_cfgs = create_chanmon_cfgs(2);
6844         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6845         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6846         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6847         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6848
6849         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6850         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6851                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6852         check_added_monitors!(nodes[0], 1);
6853
6854         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6855         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6856
6857         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6858         check_added_monitors!(nodes[1], 0);
6859         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6860
6861         let events = nodes[1].node.get_and_clear_pending_msg_events();
6862
6863         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6864                 match events[0] {
6865                         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, .. } } => {
6866                                 assert!(update_add_htlcs.is_empty());
6867                                 assert!(update_fulfill_htlcs.is_empty());
6868                                 assert!(update_fail_htlcs.is_empty());
6869                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6870                                 assert!(update_fee.is_none());
6871                                 update_fail_malformed_htlcs[0].clone()
6872                         },
6873                         _ => panic!("Unexpected event"),
6874                 }
6875         };
6876         update_msg.failure_code &= !0x8000;
6877         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6878
6879         assert!(nodes[0].node.list_channels().is_empty());
6880         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6881         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6882         check_added_monitors!(nodes[0], 1);
6883         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6884 }
6885
6886 #[test]
6887 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6888         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6889         //    * 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.
6890
6891         let chanmon_cfgs = create_chanmon_cfgs(3);
6892         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6893         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6894         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6895         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6896         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6897
6898         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6899
6900         //First hop
6901         let mut payment_event = {
6902                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6903                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6904                 check_added_monitors!(nodes[0], 1);
6905                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6906                 assert_eq!(events.len(), 1);
6907                 SendEvent::from_event(events.remove(0))
6908         };
6909         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6910         check_added_monitors!(nodes[1], 0);
6911         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6912         expect_pending_htlcs_forwardable!(nodes[1]);
6913         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6914         assert_eq!(events_2.len(), 1);
6915         check_added_monitors!(nodes[1], 1);
6916         payment_event = SendEvent::from_event(events_2.remove(0));
6917         assert_eq!(payment_event.msgs.len(), 1);
6918
6919         //Second Hop
6920         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6921         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6922         check_added_monitors!(nodes[2], 0);
6923         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6924
6925         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6926         assert_eq!(events_3.len(), 1);
6927         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6928                 match events_3[0] {
6929                         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 } } => {
6930                                 assert!(update_add_htlcs.is_empty());
6931                                 assert!(update_fulfill_htlcs.is_empty());
6932                                 assert!(update_fail_htlcs.is_empty());
6933                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6934                                 assert!(update_fee.is_none());
6935                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6936                         },
6937                         _ => panic!("Unexpected event"),
6938                 }
6939         };
6940
6941         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6942
6943         check_added_monitors!(nodes[1], 0);
6944         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6945         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 }]);
6946         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6947         assert_eq!(events_4.len(), 1);
6948
6949         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6950         match events_4[0] {
6951                 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, .. } } => {
6952                         assert!(update_add_htlcs.is_empty());
6953                         assert!(update_fulfill_htlcs.is_empty());
6954                         assert_eq!(update_fail_htlcs.len(), 1);
6955                         assert!(update_fail_malformed_htlcs.is_empty());
6956                         assert!(update_fee.is_none());
6957                 },
6958                 _ => panic!("Unexpected event"),
6959         };
6960
6961         check_added_monitors!(nodes[1], 1);
6962 }
6963
6964 #[test]
6965 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6966         let chanmon_cfgs = create_chanmon_cfgs(3);
6967         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6968         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6969         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6970         create_announced_chan_between_nodes(&nodes, 0, 1);
6971         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6972
6973         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6974
6975         // First hop
6976         let mut payment_event = {
6977                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6978                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6979                 check_added_monitors!(nodes[0], 1);
6980                 SendEvent::from_node(&nodes[0])
6981         };
6982
6983         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6984         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6985         expect_pending_htlcs_forwardable!(nodes[1]);
6986         check_added_monitors!(nodes[1], 1);
6987         payment_event = SendEvent::from_node(&nodes[1]);
6988         assert_eq!(payment_event.msgs.len(), 1);
6989
6990         // Second Hop
6991         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6992         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6993         check_added_monitors!(nodes[2], 0);
6994         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6995
6996         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6997         assert_eq!(events_3.len(), 1);
6998         match events_3[0] {
6999                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7000                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7001                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7002                         update_msg.failure_code |= 0x2000;
7003
7004                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7005                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7006                 },
7007                 _ => panic!("Unexpected event"),
7008         }
7009
7010         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7011                 vec![HTLCDestination::NextHopChannel {
7012                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7013         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7014         assert_eq!(events_4.len(), 1);
7015         check_added_monitors!(nodes[1], 1);
7016
7017         match events_4[0] {
7018                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7019                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7020                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7021                 },
7022                 _ => panic!("Unexpected event"),
7023         }
7024
7025         let events_5 = nodes[0].node.get_and_clear_pending_events();
7026         assert_eq!(events_5.len(), 2);
7027
7028         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7029         // the node originating the error to its next hop.
7030         match events_5[0] {
7031                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
7032                 } => {
7033                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7034                         assert!(is_permanent);
7035                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7036                 },
7037                 _ => panic!("Unexpected event"),
7038         }
7039         match events_5[1] {
7040                 Event::PaymentFailed { payment_hash, .. } => {
7041                         assert_eq!(payment_hash, our_payment_hash);
7042                 },
7043                 _ => panic!("Unexpected event"),
7044         }
7045
7046         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7047 }
7048
7049 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7050         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7051         // 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
7052         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7053
7054         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7055         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7056         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7057         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7058         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7059         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7060
7061         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7062                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7063
7064         // We route 2 dust-HTLCs between A and B
7065         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7066         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7067         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7068
7069         // Cache one local commitment tx as previous
7070         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7071
7072         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7073         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7074         check_added_monitors!(nodes[1], 0);
7075         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7076         check_added_monitors!(nodes[1], 1);
7077
7078         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7079         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7080         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7081         check_added_monitors!(nodes[0], 1);
7082
7083         // Cache one local commitment tx as lastest
7084         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7085
7086         let events = nodes[0].node.get_and_clear_pending_msg_events();
7087         match events[0] {
7088                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7089                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7090                 },
7091                 _ => panic!("Unexpected event"),
7092         }
7093         match events[1] {
7094                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7095                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7096                 },
7097                 _ => panic!("Unexpected event"),
7098         }
7099
7100         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7101         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7102         if announce_latest {
7103                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7104         } else {
7105                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7106         }
7107
7108         check_closed_broadcast!(nodes[0], true);
7109         check_added_monitors!(nodes[0], 1);
7110         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7111
7112         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7113         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7114         let events = nodes[0].node.get_and_clear_pending_events();
7115         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7116         assert_eq!(events.len(), 4);
7117         let mut first_failed = false;
7118         for event in events {
7119                 match event {
7120                         Event::PaymentPathFailed { payment_hash, .. } => {
7121                                 if payment_hash == payment_hash_1 {
7122                                         assert!(!first_failed);
7123                                         first_failed = true;
7124                                 } else {
7125                                         assert_eq!(payment_hash, payment_hash_2);
7126                                 }
7127                         },
7128                         Event::PaymentFailed { .. } => {}
7129                         _ => panic!("Unexpected event"),
7130                 }
7131         }
7132 }
7133
7134 #[test]
7135 fn test_failure_delay_dust_htlc_local_commitment() {
7136         do_test_failure_delay_dust_htlc_local_commitment(true);
7137         do_test_failure_delay_dust_htlc_local_commitment(false);
7138 }
7139
7140 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7141         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7142         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7143         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7144         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7145         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7146         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7147
7148         let chanmon_cfgs = create_chanmon_cfgs(3);
7149         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7150         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7151         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7152         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7153
7154         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7155                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7156
7157         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7158         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7159
7160         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7161         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7162
7163         // We revoked bs_commitment_tx
7164         if revoked {
7165                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7166                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7167         }
7168
7169         let mut timeout_tx = Vec::new();
7170         if local {
7171                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7172                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7173                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7174                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7175                 expect_payment_failed!(nodes[0], dust_hash, false);
7176
7177                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7178                 check_closed_broadcast!(nodes[0], true);
7179                 check_added_monitors!(nodes[0], 1);
7180                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7181                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7182                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7183                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7184                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7185                 mine_transaction(&nodes[0], &timeout_tx[0]);
7186                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7187                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7188         } else {
7189                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7190                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7191                 check_closed_broadcast!(nodes[0], true);
7192                 check_added_monitors!(nodes[0], 1);
7193                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7194                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7195
7196                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7197                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7198                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7199                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7200                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7201                 // dust HTLC should have been failed.
7202                 expect_payment_failed!(nodes[0], dust_hash, false);
7203
7204                 if !revoked {
7205                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7206                 } else {
7207                         assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7208                 }
7209                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7210                 mine_transaction(&nodes[0], &timeout_tx[0]);
7211                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7212                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7213                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7214         }
7215 }
7216
7217 #[test]
7218 fn test_sweep_outbound_htlc_failure_update() {
7219         do_test_sweep_outbound_htlc_failure_update(false, true);
7220         do_test_sweep_outbound_htlc_failure_update(false, false);
7221         do_test_sweep_outbound_htlc_failure_update(true, false);
7222 }
7223
7224 #[test]
7225 fn test_user_configurable_csv_delay() {
7226         // We test our channel constructors yield errors when we pass them absurd csv delay
7227
7228         let mut low_our_to_self_config = UserConfig::default();
7229         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7230         let mut high_their_to_self_config = UserConfig::default();
7231         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7232         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7233         let chanmon_cfgs = create_chanmon_cfgs(2);
7234         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7235         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7236         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7237
7238         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7239         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7240                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7241                 &low_our_to_self_config, 0, 42, None)
7242         {
7243                 match error {
7244                         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())); },
7245                         _ => panic!("Unexpected event"),
7246                 }
7247         } else { assert!(false) }
7248
7249         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7250         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7251         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7252         open_channel.common_fields.to_self_delay = 200;
7253         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7254                 &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,
7255                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7256         {
7257                 match error {
7258                         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()));  },
7259                         _ => panic!("Unexpected event"),
7260                 }
7261         } else { assert!(false); }
7262
7263         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7264         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7265         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()));
7266         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7267         accept_channel.common_fields.to_self_delay = 200;
7268         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7269         let reason_msg;
7270         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7271                 match action {
7272                         &ErrorAction::SendErrorMessage { ref msg } => {
7273                                 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()));
7274                                 reason_msg = msg.data.clone();
7275                         },
7276                         _ => { panic!(); }
7277                 }
7278         } else { panic!(); }
7279         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7280
7281         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7282         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7283         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7284         open_channel.common_fields.to_self_delay = 200;
7285         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7286                 &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,
7287                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7288         {
7289                 match error {
7290                         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())); },
7291                         _ => panic!("Unexpected event"),
7292                 }
7293         } else { assert!(false); }
7294 }
7295
7296 #[test]
7297 fn test_check_htlc_underpaying() {
7298         // Send payment through A -> B but A is maliciously
7299         // sending a probe payment (i.e less than expected value0
7300         // to B, B should refuse payment.
7301
7302         let chanmon_cfgs = create_chanmon_cfgs(2);
7303         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7304         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7305         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7306
7307         // Create some initial channels
7308         create_announced_chan_between_nodes(&nodes, 0, 1);
7309
7310         let scorer = test_utils::TestScorer::new();
7311         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7312         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7313                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7314         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7315         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7316                 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7317         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7318         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7319         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7320                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7321         check_added_monitors!(nodes[0], 1);
7322
7323         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7324         assert_eq!(events.len(), 1);
7325         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7326         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7327         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7328
7329         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7330         // and then will wait a second random delay before failing the HTLC back:
7331         expect_pending_htlcs_forwardable!(nodes[1]);
7332         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7333
7334         // Node 3 is expecting payment of 100_000 but received 10_000,
7335         // it should fail htlc like we didn't know the preimage.
7336         nodes[1].node.process_pending_htlc_forwards();
7337
7338         let events = nodes[1].node.get_and_clear_pending_msg_events();
7339         assert_eq!(events.len(), 1);
7340         let (update_fail_htlc, commitment_signed) = match events[0] {
7341                 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 } } => {
7342                         assert!(update_add_htlcs.is_empty());
7343                         assert!(update_fulfill_htlcs.is_empty());
7344                         assert_eq!(update_fail_htlcs.len(), 1);
7345                         assert!(update_fail_malformed_htlcs.is_empty());
7346                         assert!(update_fee.is_none());
7347                         (update_fail_htlcs[0].clone(), commitment_signed)
7348                 },
7349                 _ => panic!("Unexpected event"),
7350         };
7351         check_added_monitors!(nodes[1], 1);
7352
7353         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7354         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7355
7356         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7357         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7358         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7359         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7360 }
7361
7362 #[test]
7363 fn test_announce_disable_channels() {
7364         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7365         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7366
7367         let chanmon_cfgs = create_chanmon_cfgs(2);
7368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7370         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7371
7372         // Connect a dummy node for proper future events broadcasting
7373         connect_dummy_node(&nodes[0]);
7374
7375         create_announced_chan_between_nodes(&nodes, 0, 1);
7376         create_announced_chan_between_nodes(&nodes, 1, 0);
7377         create_announced_chan_between_nodes(&nodes, 0, 1);
7378
7379         // Disconnect peers
7380         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7381         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7382
7383         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7384                 nodes[0].node.timer_tick_occurred();
7385         }
7386         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7387         assert_eq!(msg_events.len(), 3);
7388         let mut chans_disabled = new_hash_map();
7389         for e in msg_events {
7390                 match e {
7391                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7392                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7393                                 // Check that each channel gets updated exactly once
7394                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7395                                         panic!("Generated ChannelUpdate for wrong chan!");
7396                                 }
7397                         },
7398                         _ => panic!("Unexpected event"),
7399                 }
7400         }
7401         // Reconnect peers
7402         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7403                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7404         }, true).unwrap();
7405         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7406         assert_eq!(reestablish_1.len(), 3);
7407         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7408                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7409         }, false).unwrap();
7410         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7411         assert_eq!(reestablish_2.len(), 3);
7412
7413         // Reestablish chan_1
7414         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7415         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7416         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7417         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7418         // Reestablish chan_2
7419         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7420         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7421         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7422         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7423         // Reestablish chan_3
7424         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7425         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7426         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7427         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7428
7429         for _ in 0..ENABLE_GOSSIP_TICKS {
7430                 nodes[0].node.timer_tick_occurred();
7431         }
7432         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7433         nodes[0].node.timer_tick_occurred();
7434         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7435         assert_eq!(msg_events.len(), 3);
7436         for e in msg_events {
7437                 match e {
7438                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7439                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7440                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7441                                         // Each update should have a higher timestamp than the previous one, replacing
7442                                         // the old one.
7443                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7444                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7445                                 }
7446                         },
7447                         _ => panic!("Unexpected event"),
7448                 }
7449         }
7450         // Check that each channel gets updated exactly once
7451         assert!(chans_disabled.is_empty());
7452 }
7453
7454 #[test]
7455 fn test_bump_penalty_txn_on_revoked_commitment() {
7456         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7457         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7458
7459         let chanmon_cfgs = create_chanmon_cfgs(2);
7460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7463
7464         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7465
7466         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7467         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7468                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7469         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7470         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7471
7472         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7473         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7474         assert_eq!(revoked_txn[0].output.len(), 4);
7475         assert_eq!(revoked_txn[0].input.len(), 1);
7476         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7477         let revoked_txid = revoked_txn[0].txid();
7478
7479         let mut penalty_sum = 0;
7480         for outp in revoked_txn[0].output.iter() {
7481                 if outp.script_pubkey.is_p2wsh() {
7482                         penalty_sum += outp.value.to_sat();
7483                 }
7484         }
7485
7486         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7487         let header_114 = connect_blocks(&nodes[1], 14);
7488
7489         // Actually revoke tx by claiming a HTLC
7490         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7491         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7492         check_added_monitors!(nodes[1], 1);
7493
7494         // One or more justice tx should have been broadcast, check it
7495         let penalty_1;
7496         let feerate_1;
7497         {
7498                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7499                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7500                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7501                 assert_eq!(node_txn[0].output.len(), 1);
7502                 check_spends!(node_txn[0], revoked_txn[0]);
7503                 let fee_1 = penalty_sum - node_txn[0].output[0].value.to_sat();
7504                 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7505                 penalty_1 = node_txn[0].txid();
7506                 node_txn.clear();
7507         };
7508
7509         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7510         connect_blocks(&nodes[1], 15);
7511         let mut penalty_2 = penalty_1;
7512         let mut feerate_2 = 0;
7513         {
7514                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7515                 assert_eq!(node_txn.len(), 1);
7516                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7517                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7518                         assert_eq!(node_txn[0].output.len(), 1);
7519                         check_spends!(node_txn[0], revoked_txn[0]);
7520                         penalty_2 = node_txn[0].txid();
7521                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7522                         assert_ne!(penalty_2, penalty_1);
7523                         let fee_2 = penalty_sum - node_txn[0].output[0].value.to_sat();
7524                         feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7525                         // Verify 25% bump heuristic
7526                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7527                         node_txn.clear();
7528                 }
7529         }
7530         assert_ne!(feerate_2, 0);
7531
7532         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7533         connect_blocks(&nodes[1], 1);
7534         let penalty_3;
7535         let mut feerate_3 = 0;
7536         {
7537                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7538                 assert_eq!(node_txn.len(), 1);
7539                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7540                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7541                         assert_eq!(node_txn[0].output.len(), 1);
7542                         check_spends!(node_txn[0], revoked_txn[0]);
7543                         penalty_3 = node_txn[0].txid();
7544                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7545                         assert_ne!(penalty_3, penalty_2);
7546                         let fee_3 = penalty_sum - node_txn[0].output[0].value.to_sat();
7547                         feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7548                         // Verify 25% bump heuristic
7549                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7550                         node_txn.clear();
7551                 }
7552         }
7553         assert_ne!(feerate_3, 0);
7554
7555         nodes[1].node.get_and_clear_pending_events();
7556         nodes[1].node.get_and_clear_pending_msg_events();
7557 }
7558
7559 #[test]
7560 fn test_bump_penalty_txn_on_revoked_htlcs() {
7561         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7562         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7563
7564         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7565         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7568         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7569
7570         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7571         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7572         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();
7573         let scorer = test_utils::TestScorer::new();
7574         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7575         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7576         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7577                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7578         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7579         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7580                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7581         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7582         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7583                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7584         let failed_payment_hash = send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000).1;
7585
7586         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7587         assert_eq!(revoked_local_txn[0].input.len(), 1);
7588         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7589
7590         // Revoke local commitment tx
7591         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7592
7593         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7594         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7595         check_closed_broadcast!(nodes[1], true);
7596         check_added_monitors!(nodes[1], 1);
7597         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7598         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7599
7600         let revoked_htlc_txn = {
7601                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7602                 assert_eq!(txn.len(), 2);
7603
7604                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7605                 assert_eq!(txn[0].input.len(), 1);
7606                 check_spends!(txn[0], revoked_local_txn[0]);
7607
7608                 assert_eq!(txn[1].input.len(), 1);
7609                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7610                 assert_eq!(txn[1].output.len(), 1);
7611                 check_spends!(txn[1], revoked_local_txn[0]);
7612
7613                 txn
7614         };
7615
7616         // Broadcast set of revoked txn on A
7617         let hash_128 = connect_blocks(&nodes[0], 40);
7618         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7619         connect_block(&nodes[0], &block_11);
7620         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7621         connect_block(&nodes[0], &block_129);
7622         let events = nodes[0].node.get_and_clear_pending_events();
7623         expect_pending_htlcs_forwardable_conditions(events[0..2].to_vec(), &[HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
7624         match events.last().unwrap() {
7625                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7626                 _ => panic!("Unexpected event"),
7627         }
7628         let first;
7629         let feerate_1;
7630         let penalty_txn;
7631         {
7632                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7633                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7634                 // Verify claim tx are spending revoked HTLC txn
7635
7636                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7637                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7638                 // which are included in the same block (they are broadcasted because we scan the
7639                 // transactions linearly and generate claims as we go, they likely should be removed in the
7640                 // future).
7641                 assert_eq!(node_txn[0].input.len(), 1);
7642                 check_spends!(node_txn[0], revoked_local_txn[0]);
7643                 assert_eq!(node_txn[1].input.len(), 1);
7644                 check_spends!(node_txn[1], revoked_local_txn[0]);
7645                 assert_eq!(node_txn[2].input.len(), 1);
7646                 check_spends!(node_txn[2], revoked_local_txn[0]);
7647
7648                 // Each of the three justice transactions claim a separate (single) output of the three
7649                 // available, which we check here:
7650                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7651                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7652                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7653
7654                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7655                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7656
7657                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7658                 // output, checked above).
7659                 assert_eq!(node_txn[3].input.len(), 2);
7660                 assert_eq!(node_txn[3].output.len(), 1);
7661                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7662
7663                 first = node_txn[3].txid();
7664                 // Store both feerates for later comparison
7665                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7666                 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7667                 penalty_txn = vec![node_txn[2].clone()];
7668                 node_txn.clear();
7669         }
7670
7671         // Connect one more block to see if bumped penalty are issued for HTLC txn
7672         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7673         connect_block(&nodes[0], &block_130);
7674         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7675         connect_block(&nodes[0], &block_131);
7676
7677         // Few more blocks to confirm penalty txn
7678         connect_blocks(&nodes[0], 4);
7679         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7680         let header_144 = connect_blocks(&nodes[0], 9);
7681         let node_txn = {
7682                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7683                 assert_eq!(node_txn.len(), 1);
7684
7685                 assert_eq!(node_txn[0].input.len(), 2);
7686                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7687                 // Verify bumped tx is different and 25% bump heuristic
7688                 assert_ne!(first, node_txn[0].txid());
7689                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7690                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7691                 assert!(feerate_2 * 100 > feerate_1 * 125);
7692                 let txn = vec![node_txn[0].clone()];
7693                 node_txn.clear();
7694                 txn
7695         };
7696         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7697         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7698         connect_blocks(&nodes[0], 20);
7699         {
7700                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7701                 // We verify than no new transaction has been broadcast because previously
7702                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7703                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7704                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7705                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7706                 // up bumped justice generation.
7707                 assert_eq!(node_txn.len(), 0);
7708                 node_txn.clear();
7709         }
7710         check_closed_broadcast!(nodes[0], true);
7711         check_added_monitors!(nodes[0], 1);
7712 }
7713
7714 #[test]
7715 fn test_bump_penalty_txn_on_remote_commitment() {
7716         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7717         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7718
7719         // Create 2 HTLCs
7720         // Provide preimage for one
7721         // Check aggregation
7722
7723         let chanmon_cfgs = create_chanmon_cfgs(2);
7724         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7725         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7726         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7727
7728         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7729         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7730         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7731
7732         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7733         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7734         assert_eq!(remote_txn[0].output.len(), 4);
7735         assert_eq!(remote_txn[0].input.len(), 1);
7736         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7737
7738         // Claim a HTLC without revocation (provide B monitor with preimage)
7739         nodes[1].node.claim_funds(payment_preimage);
7740         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7741         mine_transaction(&nodes[1], &remote_txn[0]);
7742         check_added_monitors!(nodes[1], 2);
7743         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7744
7745         // One or more claim tx should have been broadcast, check it
7746         let timeout;
7747         let preimage;
7748         let preimage_bump;
7749         let feerate_timeout;
7750         let feerate_preimage;
7751         {
7752                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7753                 // 3 transactions including:
7754                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7755                 assert_eq!(node_txn.len(), 3);
7756                 assert_eq!(node_txn[0].input.len(), 1);
7757                 assert_eq!(node_txn[1].input.len(), 1);
7758                 assert_eq!(node_txn[2].input.len(), 1);
7759                 check_spends!(node_txn[0], remote_txn[0]);
7760                 check_spends!(node_txn[1], remote_txn[0]);
7761                 check_spends!(node_txn[2], remote_txn[0]);
7762
7763                 preimage = node_txn[0].txid();
7764                 let index = node_txn[0].input[0].previous_output.vout;
7765                 let fee = remote_txn[0].output[index as usize].value.to_sat() - node_txn[0].output[0].value.to_sat();
7766                 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7767
7768                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7769                         (node_txn[2].clone(), node_txn[1].clone())
7770                 } else {
7771                         (node_txn[1].clone(), node_txn[2].clone())
7772                 };
7773
7774                 preimage_bump = preimage_bump_tx;
7775                 check_spends!(preimage_bump, remote_txn[0]);
7776                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7777
7778                 timeout = timeout_tx.txid();
7779                 let index = timeout_tx.input[0].previous_output.vout;
7780                 let fee = remote_txn[0].output[index as usize].value.to_sat() - timeout_tx.output[0].value.to_sat();
7781                 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7782
7783                 node_txn.clear();
7784         };
7785         assert_ne!(feerate_timeout, 0);
7786         assert_ne!(feerate_preimage, 0);
7787
7788         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7789         connect_blocks(&nodes[1], 1);
7790         {
7791                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7792                 assert_eq!(node_txn.len(), 1);
7793                 assert_eq!(node_txn[0].input.len(), 1);
7794                 assert_eq!(preimage_bump.input.len(), 1);
7795                 check_spends!(node_txn[0], remote_txn[0]);
7796                 check_spends!(preimage_bump, remote_txn[0]);
7797
7798                 let index = preimage_bump.input[0].previous_output.vout;
7799                 let fee = remote_txn[0].output[index as usize].value.to_sat() - preimage_bump.output[0].value.to_sat();
7800                 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7801                 assert!(new_feerate * 100 > feerate_timeout * 125);
7802                 assert_ne!(timeout, preimage_bump.txid());
7803
7804                 let index = node_txn[0].input[0].previous_output.vout;
7805                 let fee = remote_txn[0].output[index as usize].value.to_sat() - node_txn[0].output[0].value.to_sat();
7806                 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7807                 assert!(new_feerate * 100 > feerate_preimage * 125);
7808                 assert_ne!(preimage, node_txn[0].txid());
7809
7810                 node_txn.clear();
7811         }
7812
7813         nodes[1].node.get_and_clear_pending_events();
7814         nodes[1].node.get_and_clear_pending_msg_events();
7815 }
7816
7817 #[test]
7818 fn test_counterparty_raa_skip_no_crash() {
7819         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7820         // commitment transaction, we would have happily carried on and provided them the next
7821         // commitment transaction based on one RAA forward. This would probably eventually have led to
7822         // channel closure, but it would not have resulted in funds loss. Still, our
7823         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7824         // check simply that the channel is closed in response to such an RAA, but don't check whether
7825         // we decide to punish our counterparty for revoking their funds (as we don't currently
7826         // implement that).
7827         let chanmon_cfgs = create_chanmon_cfgs(2);
7828         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7829         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7830         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7831         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7832
7833         let per_commitment_secret;
7834         let next_per_commitment_point;
7835         {
7836                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7837                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7838                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7839                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7840                 ).flatten().unwrap().get_signer();
7841
7842                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7843
7844                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7845                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7846                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7847
7848                 // Must revoke without gaps
7849                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7850                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7851
7852                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7853                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7854                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7855         }
7856
7857         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7858                 &msgs::RevokeAndACK {
7859                         channel_id,
7860                         per_commitment_secret,
7861                         next_per_commitment_point,
7862                         #[cfg(taproot)]
7863                         next_local_nonce: None,
7864                 });
7865         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7866         check_added_monitors!(nodes[1], 1);
7867         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7868                 , [nodes[0].node.get_our_node_id()], 100000);
7869 }
7870
7871 #[test]
7872 fn test_bump_txn_sanitize_tracking_maps() {
7873         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7874         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7875
7876         let chanmon_cfgs = create_chanmon_cfgs(2);
7877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7879         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7880
7881         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7882         // Lock HTLC in both directions
7883         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7884         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7885
7886         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7887         assert_eq!(revoked_local_txn[0].input.len(), 1);
7888         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7889
7890         // Revoke local commitment tx
7891         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7892
7893         // Broadcast set of revoked txn on A
7894         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7895         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7896         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7897
7898         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7899         check_closed_broadcast!(nodes[0], true);
7900         check_added_monitors!(nodes[0], 1);
7901         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7902         let penalty_txn = {
7903                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7904                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7905                 check_spends!(node_txn[0], revoked_local_txn[0]);
7906                 check_spends!(node_txn[1], revoked_local_txn[0]);
7907                 check_spends!(node_txn[2], revoked_local_txn[0]);
7908                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7909                 node_txn.clear();
7910                 penalty_txn
7911         };
7912         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7913         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7914         {
7915                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7916                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7917                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7918         }
7919 }
7920
7921 #[test]
7922 fn test_channel_conf_timeout() {
7923         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7924         // confirm within 2016 blocks, as recommended by BOLT 2.
7925         let chanmon_cfgs = create_chanmon_cfgs(2);
7926         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7927         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7928         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7929
7930         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7931
7932         // The outbound node should wait forever for confirmation:
7933         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7934         // copied here instead of directly referencing the constant.
7935         connect_blocks(&nodes[0], 2016);
7936         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7937
7938         // The inbound node should fail the channel after exactly 2016 blocks
7939         connect_blocks(&nodes[1], 2015);
7940         check_added_monitors!(nodes[1], 0);
7941         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7942
7943         connect_blocks(&nodes[1], 1);
7944         check_added_monitors!(nodes[1], 1);
7945         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7946         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7947         assert_eq!(close_ev.len(), 1);
7948         match close_ev[0] {
7949                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7950                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7951                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7952                 },
7953                 _ => panic!("Unexpected event"),
7954         }
7955 }
7956
7957 #[test]
7958 fn test_override_channel_config() {
7959         let chanmon_cfgs = create_chanmon_cfgs(2);
7960         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7961         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7962         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7963
7964         // Node0 initiates a channel to node1 using the override config.
7965         let mut override_config = UserConfig::default();
7966         override_config.channel_handshake_config.our_to_self_delay = 200;
7967
7968         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7969
7970         // Assert the channel created by node0 is using the override config.
7971         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7972         assert_eq!(res.common_fields.channel_flags, 0);
7973         assert_eq!(res.common_fields.to_self_delay, 200);
7974 }
7975
7976 #[test]
7977 fn test_override_0msat_htlc_minimum() {
7978         let mut zero_config = UserConfig::default();
7979         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7980         let chanmon_cfgs = create_chanmon_cfgs(2);
7981         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7982         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7983         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7984
7985         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7986         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7987         assert_eq!(res.common_fields.htlc_minimum_msat, 1);
7988
7989         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7990         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7991         assert_eq!(res.common_fields.htlc_minimum_msat, 1);
7992 }
7993
7994 #[test]
7995 fn test_channel_update_has_correct_htlc_maximum_msat() {
7996         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7997         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7998         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7999         // 90% of the `channel_value`.
8000         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8001
8002         let mut config_30_percent = UserConfig::default();
8003         config_30_percent.channel_handshake_config.announced_channel = true;
8004         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8005         let mut config_50_percent = UserConfig::default();
8006         config_50_percent.channel_handshake_config.announced_channel = true;
8007         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8008         let mut config_95_percent = UserConfig::default();
8009         config_95_percent.channel_handshake_config.announced_channel = true;
8010         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8011         let mut config_100_percent = UserConfig::default();
8012         config_100_percent.channel_handshake_config.announced_channel = true;
8013         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8014
8015         let chanmon_cfgs = create_chanmon_cfgs(4);
8016         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8017         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)]);
8018         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8019
8020         let channel_value_satoshis = 100000;
8021         let channel_value_msat = channel_value_satoshis * 1000;
8022         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8023         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8024         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8025
8026         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
8027         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
8028
8029         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8030         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8031         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8032         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8033         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8034         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8035
8036         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8037         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8038         // `channel_value`.
8039         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8040         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8041         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8042         // `channel_value`.
8043         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8044 }
8045
8046 #[test]
8047 fn test_manually_accept_inbound_channel_request() {
8048         let mut manually_accept_conf = UserConfig::default();
8049         manually_accept_conf.manually_accept_inbound_channels = true;
8050         let chanmon_cfgs = create_chanmon_cfgs(2);
8051         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8052         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8053         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8054
8055         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();
8056         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8057
8058         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8059
8060         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8061         // accepting the inbound channel request.
8062         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8063
8064         let events = nodes[1].node.get_and_clear_pending_events();
8065         match events[0] {
8066                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8067                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8068                 }
8069                 _ => panic!("Unexpected event"),
8070         }
8071
8072         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8073         assert_eq!(accept_msg_ev.len(), 1);
8074
8075         match accept_msg_ev[0] {
8076                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8077                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8078                 }
8079                 _ => panic!("Unexpected event"),
8080         }
8081
8082         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8083
8084         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8085         assert_eq!(close_msg_ev.len(), 1);
8086
8087         let events = nodes[1].node.get_and_clear_pending_events();
8088         match events[0] {
8089                 Event::ChannelClosed { user_channel_id, .. } => {
8090                         assert_eq!(user_channel_id, 23);
8091                 }
8092                 _ => panic!("Unexpected event"),
8093         }
8094 }
8095
8096 #[test]
8097 fn test_manually_reject_inbound_channel_request() {
8098         let mut manually_accept_conf = UserConfig::default();
8099         manually_accept_conf.manually_accept_inbound_channels = true;
8100         let chanmon_cfgs = create_chanmon_cfgs(2);
8101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8103         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8104
8105         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8106         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8107
8108         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8109
8110         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8111         // rejecting the inbound channel request.
8112         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8113
8114         let events = nodes[1].node.get_and_clear_pending_events();
8115         match events[0] {
8116                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8117                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8118                 }
8119                 _ => panic!("Unexpected event"),
8120         }
8121
8122         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8123         assert_eq!(close_msg_ev.len(), 1);
8124
8125         match close_msg_ev[0] {
8126                 MessageSendEvent::HandleError { ref node_id, .. } => {
8127                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8128                 }
8129                 _ => panic!("Unexpected event"),
8130         }
8131
8132         // There should be no more events to process, as the channel was never opened.
8133         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8134 }
8135
8136 #[test]
8137 fn test_can_not_accept_inbound_channel_twice() {
8138         let mut manually_accept_conf = UserConfig::default();
8139         manually_accept_conf.manually_accept_inbound_channels = true;
8140         let chanmon_cfgs = create_chanmon_cfgs(2);
8141         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8142         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8143         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8144
8145         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8146         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8147
8148         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8149
8150         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8151         // accepting the inbound channel request.
8152         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8153
8154         let events = nodes[1].node.get_and_clear_pending_events();
8155         match events[0] {
8156                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8157                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8158                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8159                         match api_res {
8160                                 Err(APIError::APIMisuseError { err }) => {
8161                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8162                                 },
8163                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8164                                 Err(e) => panic!("Unexpected Error {:?}", e),
8165                         }
8166                 }
8167                 _ => panic!("Unexpected event"),
8168         }
8169
8170         // Ensure that the channel wasn't closed after attempting to accept it twice.
8171         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8172         assert_eq!(accept_msg_ev.len(), 1);
8173
8174         match accept_msg_ev[0] {
8175                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8176                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8177                 }
8178                 _ => panic!("Unexpected event"),
8179         }
8180 }
8181
8182 #[test]
8183 fn test_can_not_accept_unknown_inbound_channel() {
8184         let chanmon_cfg = create_chanmon_cfgs(2);
8185         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8186         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8187         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8188
8189         let unknown_channel_id = ChannelId::new_zero();
8190         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8191         match api_res {
8192                 Err(APIError::APIMisuseError { err }) => {
8193                         assert_eq!(err, "No such channel awaiting to be accepted.");
8194                 },
8195                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8196                 Err(e) => panic!("Unexpected Error: {:?}", e),
8197         }
8198 }
8199
8200 #[test]
8201 fn test_onion_value_mpp_set_calculation() {
8202         // Test that we use the onion value `amt_to_forward` when
8203         // calculating whether we've reached the `total_msat` of an MPP
8204         // by having a routing node forward more than `amt_to_forward`
8205         // and checking that the receiving node doesn't generate
8206         // a PaymentClaimable event too early
8207         let node_count = 4;
8208         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8209         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8210         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8211         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8212
8213         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8214         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8215         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8216         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8217
8218         let total_msat = 100_000;
8219         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8220         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8221         let sample_path = route.paths.pop().unwrap();
8222
8223         let mut path_1 = sample_path.clone();
8224         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8225         path_1.hops[0].short_channel_id = chan_1_id;
8226         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8227         path_1.hops[1].short_channel_id = chan_3_id;
8228         path_1.hops[1].fee_msat = 100_000;
8229         route.paths.push(path_1);
8230
8231         let mut path_2 = sample_path.clone();
8232         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8233         path_2.hops[0].short_channel_id = chan_2_id;
8234         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8235         path_2.hops[1].short_channel_id = chan_4_id;
8236         path_2.hops[1].fee_msat = 1_000;
8237         route.paths.push(path_2);
8238
8239         // Send payment
8240         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8241         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8242                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8243         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8244                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8245         check_added_monitors!(nodes[0], expected_paths.len());
8246
8247         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8248         assert_eq!(events.len(), expected_paths.len());
8249
8250         // First path
8251         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8252         let mut payment_event = SendEvent::from_event(ev);
8253         let mut prev_node = &nodes[0];
8254
8255         for (idx, &node) in expected_paths[0].iter().enumerate() {
8256                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8257
8258                 if idx == 0 { // routing node
8259                         let session_priv = [3; 32];
8260                         let height = nodes[0].best_block_info().1;
8261                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8262                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8263                         let recipient_onion_fields = RecipientOnionFields::secret_only(our_payment_secret);
8264                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8265                                 &recipient_onion_fields, height + 1, &None).unwrap();
8266                         // Edit amt_to_forward to simulate the sender having set
8267                         // the final amount and the routing node taking less fee
8268                         if let msgs::OutboundOnionPayload::Receive {
8269                                 ref mut sender_intended_htlc_amt_msat, ..
8270                         } = onion_payloads[1] {
8271                                 *sender_intended_htlc_amt_msat = 99_000;
8272                         } else { panic!() }
8273                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8274                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8275                 }
8276
8277                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8278                 check_added_monitors!(node, 0);
8279                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8280                 expect_pending_htlcs_forwardable!(node);
8281
8282                 if idx == 0 {
8283                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8284                         assert_eq!(events_2.len(), 1);
8285                         check_added_monitors!(node, 1);
8286                         payment_event = SendEvent::from_event(events_2.remove(0));
8287                         assert_eq!(payment_event.msgs.len(), 1);
8288                 } else {
8289                         let events_2 = node.node.get_and_clear_pending_events();
8290                         assert!(events_2.is_empty());
8291                 }
8292
8293                 prev_node = node;
8294         }
8295
8296         // Second path
8297         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8298         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8299
8300         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8301 }
8302
8303 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8304
8305         let routing_node_count = msat_amounts.len();
8306         let node_count = routing_node_count + 2;
8307
8308         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8309         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8310         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8311         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8312
8313         let src_idx = 0;
8314         let dst_idx = 1;
8315
8316         // Create channels for each amount
8317         let mut expected_paths = Vec::with_capacity(routing_node_count);
8318         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8319         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8320         for i in 0..routing_node_count {
8321                 let routing_node = 2 + i;
8322                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8323                 src_chan_ids.push(src_chan_id);
8324                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8325                 dst_chan_ids.push(dst_chan_id);
8326                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8327                 expected_paths.push(path);
8328         }
8329         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8330
8331         // Create a route for each amount
8332         let example_amount = 100000;
8333         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);
8334         let sample_path = route.paths.pop().unwrap();
8335         for i in 0..routing_node_count {
8336                 let routing_node = 2 + i;
8337                 let mut path = sample_path.clone();
8338                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8339                 path.hops[0].short_channel_id = src_chan_ids[i];
8340                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8341                 path.hops[1].short_channel_id = dst_chan_ids[i];
8342                 path.hops[1].fee_msat = msat_amounts[i];
8343                 route.paths.push(path);
8344         }
8345
8346         // Send payment with manually set total_msat
8347         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8348         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8349                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8350         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8351                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8352         check_added_monitors!(nodes[src_idx], expected_paths.len());
8353
8354         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8355         assert_eq!(events.len(), expected_paths.len());
8356         let mut amount_received = 0;
8357         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8358                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8359
8360                 let current_path_amount = msat_amounts[path_idx];
8361                 amount_received += current_path_amount;
8362                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8363                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8364         }
8365
8366         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8367 }
8368
8369 #[test]
8370 fn test_overshoot_mpp() {
8371         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8372         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8373 }
8374
8375 #[test]
8376 fn test_simple_mpp() {
8377         // Simple test of sending a multi-path payment.
8378         let chanmon_cfgs = create_chanmon_cfgs(4);
8379         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8380         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8381         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8382
8383         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8384         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8385         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8386         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8387
8388         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8389         let path = route.paths[0].clone();
8390         route.paths.push(path);
8391         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8392         route.paths[0].hops[0].short_channel_id = chan_1_id;
8393         route.paths[0].hops[1].short_channel_id = chan_3_id;
8394         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8395         route.paths[1].hops[0].short_channel_id = chan_2_id;
8396         route.paths[1].hops[1].short_channel_id = chan_4_id;
8397         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8398         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8399 }
8400
8401 #[test]
8402 fn test_preimage_storage() {
8403         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8404         let chanmon_cfgs = create_chanmon_cfgs(2);
8405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8407         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8408
8409         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8410
8411         {
8412                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8413                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8414                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8415                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8416                 check_added_monitors!(nodes[0], 1);
8417                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8418                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8419                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8420                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8421         }
8422         // Note that after leaving the above scope we have no knowledge of any arguments or return
8423         // values from previous calls.
8424         expect_pending_htlcs_forwardable!(nodes[1]);
8425         let events = nodes[1].node.get_and_clear_pending_events();
8426         assert_eq!(events.len(), 1);
8427         match events[0] {
8428                 Event::PaymentClaimable { ref purpose, .. } => {
8429                         match &purpose {
8430                                 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => {
8431                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8432                                 },
8433                                 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
8434                         }
8435                 },
8436                 _ => panic!("Unexpected event"),
8437         }
8438 }
8439
8440 #[test]
8441 fn test_bad_secret_hash() {
8442         // Simple test of unregistered payment hash/invalid payment secret handling
8443         let chanmon_cfgs = create_chanmon_cfgs(2);
8444         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8445         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8446         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8447
8448         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8449
8450         let random_payment_hash = PaymentHash([42; 32]);
8451         let random_payment_secret = PaymentSecret([43; 32]);
8452         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8453         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8454
8455         // All the below cases should end up being handled exactly identically, so we macro the
8456         // resulting events.
8457         macro_rules! handle_unknown_invalid_payment_data {
8458                 ($payment_hash: expr) => {
8459                         check_added_monitors!(nodes[0], 1);
8460                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8461                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8462                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8463                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8464
8465                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8466                         // again to process the pending backwards-failure of the HTLC
8467                         expect_pending_htlcs_forwardable!(nodes[1]);
8468                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8469                         check_added_monitors!(nodes[1], 1);
8470
8471                         // We should fail the payment back
8472                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8473                         match events.pop().unwrap() {
8474                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8475                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8476                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8477                                 },
8478                                 _ => panic!("Unexpected event"),
8479                         }
8480                 }
8481         }
8482
8483         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8484         // Error data is the HTLC value (100,000) and current block height
8485         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8486
8487         // Send a payment with the right payment hash but the wrong payment secret
8488         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8489                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8490         handle_unknown_invalid_payment_data!(our_payment_hash);
8491         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8492
8493         // Send a payment with a random payment hash, but the right payment secret
8494         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8495                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8496         handle_unknown_invalid_payment_data!(random_payment_hash);
8497         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8498
8499         // Send a payment with a random payment hash and random payment secret
8500         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8501                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8502         handle_unknown_invalid_payment_data!(random_payment_hash);
8503         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8504 }
8505
8506 #[test]
8507 fn test_update_err_monitor_lockdown() {
8508         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8509         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8510         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8511         // error.
8512         //
8513         // This scenario may happen in a watchtower setup, where watchtower process a block height
8514         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8515         // commitment at same time.
8516
8517         let chanmon_cfgs = create_chanmon_cfgs(2);
8518         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8519         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8520         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8521
8522         // Create some initial channel
8523         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8524         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8525
8526         // Rebalance the network to generate htlc in the two directions
8527         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8528
8529         // Route a HTLC from node 0 to node 1 (but don't settle)
8530         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8531
8532         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8533         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8534         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8535         let persister = test_utils::TestPersister::new();
8536         let watchtower = {
8537                 let new_monitor = {
8538                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8539                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8540                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8541                         assert!(new_monitor == *monitor);
8542                         new_monitor
8543                 };
8544                 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);
8545                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8546                 watchtower
8547         };
8548         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8549         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8550         // transaction lock time requirements here.
8551         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8552         watchtower.chain_monitor.block_connected(&block, 200);
8553
8554         // Try to update ChannelMonitor
8555         nodes[1].node.claim_funds(preimage);
8556         check_added_monitors!(nodes[1], 1);
8557         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8558
8559         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8560         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8561         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8562         {
8563                 let mut node_0_per_peer_lock;
8564                 let mut node_0_peer_state_lock;
8565                 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) {
8566                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8567                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8568                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8569                         } else { assert!(false); }
8570                 } else {
8571                         assert!(false);
8572                 }
8573         }
8574         // Our local monitor is in-sync and hasn't processed yet timeout
8575         check_added_monitors!(nodes[0], 1);
8576         let events = nodes[0].node.get_and_clear_pending_events();
8577         assert_eq!(events.len(), 1);
8578 }
8579
8580 #[test]
8581 fn test_concurrent_monitor_claim() {
8582         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8583         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8584         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8585         // state N+1 confirms. Alice claims output from state N+1.
8586
8587         let chanmon_cfgs = create_chanmon_cfgs(2);
8588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8590         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8591
8592         // Create some initial channel
8593         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8594         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8595
8596         // Rebalance the network to generate htlc in the two directions
8597         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8598
8599         // Route a HTLC from node 0 to node 1 (but don't settle)
8600         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8601
8602         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8603         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8604         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8605         let persister = test_utils::TestPersister::new();
8606         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8607                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8608         );
8609         let watchtower_alice = {
8610                 let new_monitor = {
8611                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8612                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8613                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8614                         assert!(new_monitor == *monitor);
8615                         new_monitor
8616                 };
8617                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8618                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8619                 watchtower
8620         };
8621         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8622         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8623         // requirements here.
8624         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8625         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8626         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8627
8628         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8629         {
8630                 let mut txn = alice_broadcaster.txn_broadcast();
8631                 assert_eq!(txn.len(), 2);
8632                 check_spends!(txn[0], chan_1.3);
8633                 check_spends!(txn[1], txn[0]);
8634         };
8635
8636         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8637         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8638         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8639         let persister = test_utils::TestPersister::new();
8640         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8641         let watchtower_bob = {
8642                 let new_monitor = {
8643                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8644                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8645                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8646                         assert!(new_monitor == *monitor);
8647                         new_monitor
8648                 };
8649                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8650                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8651                 watchtower
8652         };
8653         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8654
8655         // Route another payment to generate another update with still previous HTLC pending
8656         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8657         nodes[1].node.send_payment_with_route(&route, payment_hash,
8658                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8659         check_added_monitors!(nodes[1], 1);
8660
8661         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8662         assert_eq!(updates.update_add_htlcs.len(), 1);
8663         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8664         {
8665                 let mut node_0_per_peer_lock;
8666                 let mut node_0_peer_state_lock;
8667                 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) {
8668                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8669                                 // Watchtower Alice should already have seen the block and reject the update
8670                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8671                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8672                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8673                         } else { assert!(false); }
8674                 } else {
8675                         assert!(false);
8676                 }
8677         }
8678         // Our local monitor is in-sync and hasn't processed yet timeout
8679         check_added_monitors!(nodes[0], 1);
8680
8681         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8682         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8683
8684         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8685         let bob_state_y;
8686         {
8687                 let mut txn = bob_broadcaster.txn_broadcast();
8688                 assert_eq!(txn.len(), 2);
8689                 bob_state_y = txn.remove(0);
8690         };
8691
8692         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8693         let height = HTLC_TIMEOUT_BROADCAST + 1;
8694         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8695         check_closed_broadcast(&nodes[0], 1, true);
8696         check_closed_event!(&nodes[0], 1, ClosureReason::HTLCsTimedOut, false,
8697                 [nodes[1].node.get_our_node_id()], 100000);
8698         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8699         check_added_monitors(&nodes[0], 1);
8700         {
8701                 let htlc_txn = alice_broadcaster.txn_broadcast();
8702                 assert_eq!(htlc_txn.len(), 1);
8703                 check_spends!(htlc_txn[0], bob_state_y);
8704         }
8705 }
8706
8707 #[test]
8708 fn test_pre_lockin_no_chan_closed_update() {
8709         // Test that if a peer closes a channel in response to a funding_created message we don't
8710         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8711         // message).
8712         //
8713         // Doing so would imply a channel monitor update before the initial channel monitor
8714         // registration, violating our API guarantees.
8715         //
8716         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8717         // then opening a second channel with the same funding output as the first (which is not
8718         // rejected because the first channel does not exist in the ChannelManager) and closing it
8719         // before receiving funding_signed.
8720         let chanmon_cfgs = create_chanmon_cfgs(2);
8721         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8722         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8723         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8724
8725         // Create an initial channel
8726         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8727         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8728         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8729         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8730         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8731
8732         // Move the first channel through the funding flow...
8733         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8734
8735         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8736         check_added_monitors!(nodes[0], 0);
8737
8738         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8739         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 });
8740         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8741         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8742         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8743                 [nodes[1].node.get_our_node_id()], 100000);
8744 }
8745
8746 #[test]
8747 fn test_htlc_no_detection() {
8748         // This test is a mutation to underscore the detection logic bug we had
8749         // before #653. HTLC value routed is above the remaining balance, thus
8750         // inverting HTLC and `to_remote` output. HTLC will come second and
8751         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8752         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8753         // outputs order detection for correct spending children filtring.
8754
8755         let chanmon_cfgs = create_chanmon_cfgs(2);
8756         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8757         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8758         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8759
8760         // Create some initial channels
8761         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8762
8763         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8764         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8765         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8766         assert_eq!(local_txn[0].input.len(), 1);
8767         assert_eq!(local_txn[0].output.len(), 3);
8768         check_spends!(local_txn[0], chan_1.3);
8769
8770         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8771         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8772         connect_block(&nodes[0], &block);
8773         // We deliberately connect the local tx twice as this should provoke a failure calling
8774         // this test before #653 fix.
8775         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8776         check_closed_broadcast!(nodes[0], true);
8777         check_added_monitors!(nodes[0], 1);
8778         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8779         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8780
8781         let htlc_timeout = {
8782                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8783                 assert_eq!(node_txn.len(), 1);
8784                 assert_eq!(node_txn[0].input.len(), 1);
8785                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8786                 check_spends!(node_txn[0], local_txn[0]);
8787                 node_txn[0].clone()
8788         };
8789
8790         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8791         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8792         expect_payment_failed!(nodes[0], our_payment_hash, false);
8793 }
8794
8795 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8796         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8797         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8798         // Carol, Alice would be the upstream node, and Carol the downstream.)
8799         //
8800         // Steps of the test:
8801         // 1) Alice sends a HTLC to Carol through Bob.
8802         // 2) Carol doesn't settle the HTLC.
8803         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8804         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8805         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8806         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8807         // 5) Carol release the preimage to Bob off-chain.
8808         // 6) Bob claims the offered output on the broadcasted commitment.
8809         let chanmon_cfgs = create_chanmon_cfgs(3);
8810         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8811         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8812         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8813
8814         // Create some initial channels
8815         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8816         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8817
8818         // Steps (1) and (2):
8819         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8820         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8821
8822         // Check that Alice's commitment transaction now contains an output for this HTLC.
8823         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8824         check_spends!(alice_txn[0], chan_ab.3);
8825         assert_eq!(alice_txn[0].output.len(), 2);
8826         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8827         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8828         assert_eq!(alice_txn.len(), 2);
8829
8830         // Steps (3) and (4):
8831         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8832         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8833         let mut force_closing_node = 0; // Alice force-closes
8834         let mut counterparty_node = 1; // Bob if Alice force-closes
8835
8836         // Bob force-closes
8837         if !broadcast_alice {
8838                 force_closing_node = 1;
8839                 counterparty_node = 0;
8840         }
8841         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8842         check_closed_broadcast!(nodes[force_closing_node], true);
8843         check_added_monitors!(nodes[force_closing_node], 1);
8844         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8845         if go_onchain_before_fulfill {
8846                 let txn_to_broadcast = match broadcast_alice {
8847                         true => alice_txn.clone(),
8848                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8849                 };
8850                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8851                 if broadcast_alice {
8852                         check_closed_broadcast!(nodes[1], true);
8853                         check_added_monitors!(nodes[1], 1);
8854                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8855                 }
8856         }
8857
8858         // Step (5):
8859         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8860         // process of removing the HTLC from their commitment transactions.
8861         nodes[2].node.claim_funds(payment_preimage);
8862         check_added_monitors!(nodes[2], 1);
8863         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8864
8865         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8866         assert!(carol_updates.update_add_htlcs.is_empty());
8867         assert!(carol_updates.update_fail_htlcs.is_empty());
8868         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8869         assert!(carol_updates.update_fee.is_none());
8870         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8871
8872         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8873         let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8874         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8875         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8876         if !go_onchain_before_fulfill && broadcast_alice {
8877                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8878                 assert_eq!(events.len(), 1);
8879                 match events[0] {
8880                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8881                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8882                         },
8883                         _ => panic!("Unexpected event"),
8884                 };
8885         }
8886         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8887         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8888         // Carol<->Bob's updated commitment transaction info.
8889         check_added_monitors!(nodes[1], 2);
8890
8891         let events = nodes[1].node.get_and_clear_pending_msg_events();
8892         assert_eq!(events.len(), 2);
8893         let bob_revocation = match events[0] {
8894                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8895                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8896                         (*msg).clone()
8897                 },
8898                 _ => panic!("Unexpected event"),
8899         };
8900         let bob_updates = match events[1] {
8901                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8902                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8903                         (*updates).clone()
8904                 },
8905                 _ => panic!("Unexpected event"),
8906         };
8907
8908         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8909         check_added_monitors!(nodes[2], 1);
8910         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8911         check_added_monitors!(nodes[2], 1);
8912
8913         let events = nodes[2].node.get_and_clear_pending_msg_events();
8914         assert_eq!(events.len(), 1);
8915         let carol_revocation = match events[0] {
8916                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8917                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8918                         (*msg).clone()
8919                 },
8920                 _ => panic!("Unexpected event"),
8921         };
8922         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8923         check_added_monitors!(nodes[1], 1);
8924
8925         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8926         // here's where we put said channel's commitment tx on-chain.
8927         let mut txn_to_broadcast = alice_txn.clone();
8928         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8929         if !go_onchain_before_fulfill {
8930                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8931                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8932                 if broadcast_alice {
8933                         check_closed_broadcast!(nodes[1], true);
8934                         check_added_monitors!(nodes[1], 1);
8935                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8936                 }
8937                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8938                 if broadcast_alice {
8939                         assert_eq!(bob_txn.len(), 1);
8940                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8941                 } else {
8942                         if nodes[1].connect_style.borrow().updates_best_block_first() {
8943                                 assert_eq!(bob_txn.len(), 3);
8944                                 assert_eq!(bob_txn[0].txid(), bob_txn[1].txid());
8945                         } else {
8946                                 assert_eq!(bob_txn.len(), 2);
8947                         }
8948                         check_spends!(bob_txn[0], chan_ab.3);
8949                 }
8950         }
8951
8952         // Step (6):
8953         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8954         // broadcasted commitment transaction.
8955         {
8956                 let script_weight = match broadcast_alice {
8957                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8958                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8959                 };
8960                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8961                 // Bob force-closed and broadcasts the commitment transaction along with a
8962                 // HTLC-output-claiming transaction.
8963                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8964                 if broadcast_alice {
8965                         assert_eq!(bob_txn.len(), 1);
8966                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8967                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8968                 } else {
8969                         assert_eq!(bob_txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
8970                         let htlc_tx = bob_txn.pop().unwrap();
8971                         check_spends!(htlc_tx, txn_to_broadcast[0]);
8972                         assert_eq!(htlc_tx.input[0].witness.last().unwrap().len(), script_weight);
8973                 }
8974         }
8975 }
8976
8977 #[test]
8978 fn test_onchain_htlc_settlement_after_close() {
8979         do_test_onchain_htlc_settlement_after_close(true, true);
8980         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8981         do_test_onchain_htlc_settlement_after_close(true, false);
8982         do_test_onchain_htlc_settlement_after_close(false, false);
8983 }
8984
8985 #[test]
8986 fn test_duplicate_temporary_channel_id_from_different_peers() {
8987         // Tests that we can accept two different `OpenChannel` requests with the same
8988         // `temporary_channel_id`, as long as they are from different peers.
8989         let chanmon_cfgs = create_chanmon_cfgs(3);
8990         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8991         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8992         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8993
8994         // Create an first channel channel
8995         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8996         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8997
8998         // Create an second channel
8999         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
9000         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
9001
9002         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
9003         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
9004         open_chan_msg_chan_2_0.common_fields.temporary_channel_id = open_chan_msg_chan_1_0.common_fields.temporary_channel_id;
9005
9006         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
9007         // `temporary_channel_id` as they are from different peers.
9008         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
9009         {
9010                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9011                 assert_eq!(events.len(), 1);
9012                 match &events[0] {
9013                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
9014                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
9015                                 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
9016                         },
9017                         _ => panic!("Unexpected event"),
9018                 }
9019         }
9020
9021         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
9022         {
9023                 let events = nodes[0].node.get_and_clear_pending_msg_events();
9024                 assert_eq!(events.len(), 1);
9025                 match &events[0] {
9026                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
9027                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
9028                                 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
9029                         },
9030                         _ => panic!("Unexpected event"),
9031                 }
9032         }
9033 }
9034
9035 #[test]
9036 fn test_peer_funding_sidechannel() {
9037         // Test that if a peer somehow learns which txid we'll use for our channel funding before we
9038         // receive `funding_transaction_generated` the peer cannot cause us to crash. We'd previously
9039         // assumed that LDK would receive `funding_transaction_generated` prior to our peer learning
9040         // the txid and panicked if the peer tried to open a redundant channel to us with the same
9041         // funding outpoint.
9042         //
9043         // While this assumption is generally safe, some users may have out-of-band protocols where
9044         // they notify their LSP about a funding outpoint first, or this may be violated in the future
9045         // with collaborative transaction construction protocols, i.e. dual-funding.
9046         let chanmon_cfgs = create_chanmon_cfgs(3);
9047         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9048         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9049         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9050
9051         let temp_chan_id_ab = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9052         let temp_chan_id_ca = exchange_open_accept_chan(&nodes[2], &nodes[0], 1_000_000, 0);
9053
9054         let (_, tx, funding_output) =
9055                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9056
9057         let cs_funding_events = nodes[2].node.get_and_clear_pending_events();
9058         assert_eq!(cs_funding_events.len(), 1);
9059         match cs_funding_events[0] {
9060                 Event::FundingGenerationReady { .. } => {}
9061                 _ => panic!("Unexpected event {:?}", cs_funding_events),
9062         }
9063
9064         nodes[2].node.funding_transaction_generated_unchecked(&temp_chan_id_ca, &nodes[0].node.get_our_node_id(), tx.clone(), funding_output.index).unwrap();
9065         let funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[0].node.get_our_node_id());
9066         nodes[0].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9067         get_event_msg!(nodes[0], MessageSendEvent::SendFundingSigned, nodes[2].node.get_our_node_id());
9068         expect_channel_pending_event(&nodes[0], &nodes[2].node.get_our_node_id());
9069         check_added_monitors!(nodes[0], 1);
9070
9071         let res = nodes[0].node.funding_transaction_generated(&temp_chan_id_ab, &nodes[1].node.get_our_node_id(), tx.clone());
9072         let err_msg = format!("{:?}", res.unwrap_err());
9073         assert!(err_msg.contains("An existing channel using outpoint "));
9074         assert!(err_msg.contains(" is open with peer"));
9075         // Even though the last funding_transaction_generated errored, it still generated a
9076         // SendFundingCreated. However, when the peer responds with a funding_signed it will send the
9077         // appropriate error message.
9078         let as_funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9079         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &as_funding_created);
9080         check_added_monitors!(nodes[1], 1);
9081         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9082         let reason = ClosureReason::ProcessingError { err: format!("An existing channel using outpoint {} is open with peer {}", funding_output, nodes[2].node.get_our_node_id()), };
9083         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(ChannelId::v1_from_funding_outpoint(funding_output), true, reason)]);
9084
9085         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9086         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9087         get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9088 }
9089
9090 #[test]
9091 fn test_duplicate_conflicting_funding_from_second_peer() {
9092         // Test that if a user tries to fund a channel with a funding outpoint they'd previously used
9093         // we don't try to remove the previous ChannelMonitor. This is largely a test to ensure we
9094         // don't regress in the fuzzer, as such funding getting passed our outpoint-matches checks
9095         // implies the user (and our counterparty) has reused cryptographic keys across channels, which
9096         // we require the user not do.
9097         let chanmon_cfgs = create_chanmon_cfgs(4);
9098         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9099         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9100         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9101
9102         let temp_chan_id = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9103
9104         let (_, tx, funding_output) =
9105                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9106
9107         // Now that we have a funding outpoint, create a dummy `ChannelMonitor` and insert it into
9108         // nodes[0]'s ChainMonitor so that the initial `ChannelMonitor` write fails.
9109         let dummy_chan_id = create_chan_between_nodes(&nodes[2], &nodes[3]).3;
9110         let dummy_monitor = get_monitor!(nodes[2], dummy_chan_id).clone();
9111         nodes[0].chain_monitor.chain_monitor.watch_channel(funding_output, dummy_monitor).unwrap();
9112
9113         nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9114
9115         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9116         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9117         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9118         check_added_monitors!(nodes[1], 1);
9119         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9120
9121         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9122         // At this point, the channel should be closed, after having generated one monitor write (the
9123         // watch_channel call which failed), but zero monitor updates.
9124         check_added_monitors!(nodes[0], 1);
9125         get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9126         let err_reason = ClosureReason::ProcessingError { err: "Channel funding outpoint was a duplicate".to_owned() };
9127         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(funding_signed_msg.channel_id, true, err_reason)]);
9128 }
9129
9130 #[test]
9131 fn test_duplicate_funding_err_in_funding() {
9132         // Test that if we have a live channel with one peer, then another peer comes along and tries
9133         // to create a second channel with the same txid we'll fail and not overwrite the
9134         // outpoint_to_peer map in `ChannelManager`.
9135         //
9136         // This was previously broken.
9137         let chanmon_cfgs = create_chanmon_cfgs(3);
9138         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9139         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9140         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9141
9142         let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
9143         let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
9144         assert_eq!(ChannelId::v1_from_funding_outpoint(real_chan_funding_txo), real_channel_id);
9145
9146         nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9147         let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9148         let node_c_temp_chan_id = open_chan_msg.common_fields.temporary_channel_id;
9149         open_chan_msg.common_fields.temporary_channel_id = real_channel_id;
9150         nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
9151         let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
9152         accept_chan_msg.common_fields.temporary_channel_id = node_c_temp_chan_id;
9153         nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
9154
9155         // Now that we have a second channel with the same funding txo, send a bogus funding message
9156         // and let nodes[1] remove the inbound channel.
9157         let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9158
9159         nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9160
9161         let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9162         funding_created_msg.temporary_channel_id = real_channel_id;
9163         // Make the signature invalid by changing the funding output
9164         funding_created_msg.funding_output_index += 10;
9165         nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9166         get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9167         let err = "Invalid funding_created signature from peer".to_owned();
9168         let reason = ClosureReason::ProcessingError { err };
9169         let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9170         check_closed_events(&nodes[1], &[expected_closing]);
9171
9172         assert_eq!(
9173                 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9174                 nodes[0].node.get_our_node_id()
9175         );
9176 }
9177
9178 #[test]
9179 fn test_duplicate_chan_id() {
9180         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9181         // already open we reject it and keep the old channel.
9182         //
9183         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9184         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9185         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9186         // updating logic for the existing channel.
9187         let chanmon_cfgs = create_chanmon_cfgs(2);
9188         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9189         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9190         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9191
9192         // Create an initial channel
9193         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9194         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9195         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9196         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()));
9197
9198         // Try to create a second channel with the same temporary_channel_id as the first and check
9199         // that it is rejected.
9200         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9201         {
9202                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9203                 assert_eq!(events.len(), 1);
9204                 match events[0] {
9205                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9206                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9207                                 // first (valid) and second (invalid) channels are closed, given they both have
9208                                 // the same non-temporary channel_id. However, currently we do not, so we just
9209                                 // move forward with it.
9210                                 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9211                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9212                         },
9213                         _ => panic!("Unexpected event"),
9214                 }
9215         }
9216
9217         // Move the first channel through the funding flow...
9218         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9219
9220         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9221         check_added_monitors!(nodes[0], 0);
9222
9223         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9224         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9225         {
9226                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9227                 assert_eq!(added_monitors.len(), 1);
9228                 assert_eq!(added_monitors[0].0, funding_output);
9229                 added_monitors.clear();
9230         }
9231         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9232
9233         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9234
9235         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9236         let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
9237
9238         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9239         // temporary one).
9240
9241         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9242         // Technically this is allowed by the spec, but we don't support it and there's little reason
9243         // to. Still, it shouldn't cause any other issues.
9244         open_chan_msg.common_fields.temporary_channel_id = channel_id;
9245         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9246         {
9247                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9248                 assert_eq!(events.len(), 1);
9249                 match events[0] {
9250                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9251                                 // Technically, at this point, nodes[1] would be justified in thinking both
9252                                 // channels are closed, but currently we do not, so we just move forward with it.
9253                                 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9254                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9255                         },
9256                         _ => panic!("Unexpected event"),
9257                 }
9258         }
9259
9260         // Now try to create a second channel which has a duplicate funding output.
9261         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9262         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9263         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9264         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()));
9265         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9266
9267         let funding_created = {
9268                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9269                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9270                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9271                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9272                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9273                 // channelmanager in a possibly nonsense state instead).
9274                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.common_fields.temporary_channel_id).unwrap() {
9275                         ChannelPhase::UnfundedOutboundV1(mut chan) => {
9276                                 let logger = test_utils::TestLogger::new();
9277                                 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9278                         },
9279                         _ => panic!("Unexpected ChannelPhase variant"),
9280                 }.unwrap()
9281         };
9282         check_added_monitors!(nodes[0], 0);
9283         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9284         // At this point we'll look up if the channel_id is present and immediately fail the channel
9285         // without trying to persist the `ChannelMonitor`.
9286         check_added_monitors!(nodes[1], 0);
9287
9288         check_closed_events(&nodes[1], &[
9289                 ExpectedCloseEvent::from_id_reason(funding_created.temporary_channel_id, false, ClosureReason::ProcessingError {
9290                         err: "Already had channel with the new channel_id".to_owned()
9291                 })
9292         ]);
9293
9294         // ...still, nodes[1] will reject the duplicate channel.
9295         {
9296                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9297                 assert_eq!(events.len(), 1);
9298                 match events[0] {
9299                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9300                                 // Technically, at this point, nodes[1] would be justified in thinking both
9301                                 // channels are closed, but currently we do not, so we just move forward with it.
9302                                 assert_eq!(msg.channel_id, channel_id);
9303                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9304                         },
9305                         _ => panic!("Unexpected event"),
9306                 }
9307         }
9308
9309         // finally, finish creating the original channel and send a payment over it to make sure
9310         // everything is functional.
9311         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9312         {
9313                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9314                 assert_eq!(added_monitors.len(), 1);
9315                 assert_eq!(added_monitors[0].0, funding_output);
9316                 added_monitors.clear();
9317         }
9318         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9319
9320         let events_4 = nodes[0].node.get_and_clear_pending_events();
9321         assert_eq!(events_4.len(), 0);
9322         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9323         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9324
9325         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9326         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9327         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9328
9329         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9330 }
9331
9332 #[test]
9333 fn test_error_chans_closed() {
9334         // Test that we properly handle error messages, closing appropriate channels.
9335         //
9336         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9337         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9338         // we can test various edge cases around it to ensure we don't regress.
9339         let chanmon_cfgs = create_chanmon_cfgs(3);
9340         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9341         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9342         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9343
9344         // Create some initial channels
9345         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9346         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9347         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9348
9349         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9350         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9351         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9352
9353         // Closing a channel from a different peer has no effect
9354         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9355         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9356
9357         // Closing one channel doesn't impact others
9358         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9359         check_added_monitors!(nodes[0], 1);
9360         check_closed_broadcast!(nodes[0], false);
9361         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9362                 [nodes[1].node.get_our_node_id()], 100000);
9363         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9364         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9365         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);
9366         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);
9367
9368         // A null channel ID should close all channels
9369         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9370         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9371         check_added_monitors!(nodes[0], 2);
9372         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9373                 [nodes[1].node.get_our_node_id(); 2], 100000);
9374         let events = nodes[0].node.get_and_clear_pending_msg_events();
9375         assert_eq!(events.len(), 2);
9376         match events[0] {
9377                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9378                         assert_eq!(msg.contents.flags & 2, 2);
9379                 },
9380                 _ => panic!("Unexpected event"),
9381         }
9382         match events[1] {
9383                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9384                         assert_eq!(msg.contents.flags & 2, 2);
9385                 },
9386                 _ => panic!("Unexpected event"),
9387         }
9388         // Note that at this point users of a standard PeerHandler will end up calling
9389         // peer_disconnected.
9390         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9391         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9392
9393         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9394         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9395         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9396 }
9397
9398 #[test]
9399 fn test_invalid_funding_tx() {
9400         // Test that we properly handle invalid funding transactions sent to us from a peer.
9401         //
9402         // Previously, all other major lightning implementations had failed to properly sanitize
9403         // funding transactions from their counterparties, leading to a multi-implementation critical
9404         // security vulnerability (though we always sanitized properly, we've previously had
9405         // un-released crashes in the sanitization process).
9406         //
9407         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9408         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9409         // gave up on it. We test this here by generating such a transaction.
9410         let chanmon_cfgs = create_chanmon_cfgs(2);
9411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9413         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9414
9415         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9416         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()));
9417         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()));
9418
9419         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9420
9421         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9422         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9423         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9424         // its length.
9425         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9426         let wit_program_script: ScriptBuf = wit_program.into();
9427         for output in tx.output.iter_mut() {
9428                 // Make the confirmed funding transaction have a bogus script_pubkey
9429                 output.script_pubkey = ScriptBuf::new_p2wsh(&wit_program_script.wscript_hash());
9430         }
9431
9432         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9433         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()));
9434         check_added_monitors!(nodes[1], 1);
9435         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9436
9437         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()));
9438         check_added_monitors!(nodes[0], 1);
9439         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9440
9441         let events_1 = nodes[0].node.get_and_clear_pending_events();
9442         assert_eq!(events_1.len(), 0);
9443
9444         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9445         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9446         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9447
9448         let expected_err = "funding tx had wrong script/value or output index";
9449         confirm_transaction_at(&nodes[1], &tx, 1);
9450         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9451                 [nodes[0].node.get_our_node_id()], 100000);
9452         check_added_monitors!(nodes[1], 1);
9453         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9454         assert_eq!(events_2.len(), 1);
9455         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9456                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9457                 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9458                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9459                 } else { panic!(); }
9460         } else { panic!(); }
9461         assert_eq!(nodes[1].node.list_channels().len(), 0);
9462
9463         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9464         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9465         // as its not 32 bytes long.
9466         let mut spend_tx = Transaction {
9467                 version: Version::TWO, lock_time: LockTime::ZERO,
9468                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9469                         previous_output: BitcoinOutPoint {
9470                                 txid: tx.txid(),
9471                                 vout: idx as u32,
9472                         },
9473                         script_sig: ScriptBuf::new(),
9474                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9475                         witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9476                 }).collect(),
9477                 output: vec![TxOut {
9478                         value: Amount::from_sat(1000),
9479                         script_pubkey: ScriptBuf::new(),
9480                 }]
9481         };
9482         check_spends!(spend_tx, tx);
9483         mine_transaction(&nodes[1], &spend_tx);
9484 }
9485
9486 #[test]
9487 fn test_coinbase_funding_tx() {
9488         // Miners are able to fund channels directly from coinbase transactions, however
9489         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9490         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9491         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9492         //
9493         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9494         // immediately operational after opening.
9495         let chanmon_cfgs = create_chanmon_cfgs(2);
9496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9499
9500         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9501         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9502
9503         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9504         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9505
9506         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9507
9508         // Create the coinbase funding transaction.
9509         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9510
9511         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9512         check_added_monitors!(nodes[0], 0);
9513         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9514
9515         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9516         check_added_monitors!(nodes[1], 1);
9517         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9518
9519         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9520
9521         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9522         check_added_monitors!(nodes[0], 1);
9523
9524         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9525         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9526
9527         // Starting at height 0, we "confirm" the coinbase at height 1.
9528         confirm_transaction_at(&nodes[0], &tx, 1);
9529         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9530         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9531         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9532         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9533         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9534         connect_blocks(&nodes[0], 1);
9535         // There should now be a `channel_ready` which can be handled.
9536         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()));
9537
9538         confirm_transaction_at(&nodes[1], &tx, 1);
9539         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9540         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9541         connect_blocks(&nodes[1], 1);
9542         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9543         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9544 }
9545
9546 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9547         // In the first version of the chain::Confirm interface, after a refactor was made to not
9548         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9549         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9550         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9551         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9552         // spending transaction until height N+1 (or greater). This was due to the way
9553         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9554         // spending transaction at the height the input transaction was confirmed at, not whether we
9555         // should broadcast a spending transaction at the current height.
9556         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9557         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9558         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9559         // until we learned about an additional block.
9560         //
9561         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9562         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9563         let chanmon_cfgs = create_chanmon_cfgs(3);
9564         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9565         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9566         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9567         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9568
9569         create_announced_chan_between_nodes(&nodes, 0, 1);
9570         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9571         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9572         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9573         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9574
9575         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9576         check_closed_broadcast!(nodes[1], true);
9577         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9578         check_added_monitors!(nodes[1], 1);
9579         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9580         assert_eq!(node_txn.len(), 1);
9581
9582         let conf_height = nodes[1].best_block_info().1;
9583         if !test_height_before_timelock {
9584                 connect_blocks(&nodes[1], 24 * 6);
9585         }
9586         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9587                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9588         if test_height_before_timelock {
9589                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9590                 // generate any events or broadcast any transactions
9591                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9592                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9593         } else {
9594                 // We should broadcast an HTLC transaction spending our funding transaction first
9595                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9596                 assert_eq!(spending_txn.len(), 2);
9597                 let htlc_tx = if spending_txn[0].txid() == node_txn[0].txid() {
9598                         &spending_txn[1]
9599                 } else {
9600                         &spending_txn[0]
9601                 };
9602                 check_spends!(htlc_tx, node_txn[0]);
9603                 // We should also generate a SpendableOutputs event with the to_self output (as its
9604                 // timelock is up).
9605                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9606                 assert_eq!(descriptor_spend_txn.len(), 1);
9607
9608                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9609                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9610                 // additional block built on top of the current chain.
9611                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9612                         &nodes[1].get_block_header(conf_height + 1), &[(0, htlc_tx)], conf_height + 1);
9613                 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 }]);
9614                 check_added_monitors!(nodes[1], 1);
9615
9616                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9617                 assert!(updates.update_add_htlcs.is_empty());
9618                 assert!(updates.update_fulfill_htlcs.is_empty());
9619                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9620                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9621                 assert!(updates.update_fee.is_none());
9622                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9623                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9624                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9625         }
9626 }
9627
9628 #[test]
9629 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9630         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9631         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9632 }
9633
9634 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9635         let chanmon_cfgs = create_chanmon_cfgs(2);
9636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9638         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9639
9640         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9641
9642         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9643                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9644         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9645
9646         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9647
9648         {
9649                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9650                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9651                 check_added_monitors!(nodes[0], 1);
9652                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9653                 assert_eq!(events.len(), 1);
9654                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9655                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9656                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9657         }
9658         expect_pending_htlcs_forwardable!(nodes[1]);
9659         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9660
9661         {
9662                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9663                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9664                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9665                 check_added_monitors!(nodes[0], 1);
9666                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9667                 assert_eq!(events.len(), 1);
9668                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9669                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9670                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9671                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9672                 // assume the second is a privacy attack (no longer particularly relevant
9673                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9674                 // the first HTLC delivered above.
9675         }
9676
9677         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9678         nodes[1].node.process_pending_htlc_forwards();
9679
9680         if test_for_second_fail_panic {
9681                 // Now we go fail back the first HTLC from the user end.
9682                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9683
9684                 let expected_destinations = vec![
9685                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9686                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9687                 ];
9688                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9689                 nodes[1].node.process_pending_htlc_forwards();
9690
9691                 check_added_monitors!(nodes[1], 1);
9692                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9693                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9694
9695                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9696                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9697                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9698
9699                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9700                 assert_eq!(failure_events.len(), 4);
9701                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9702                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9703                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9704                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9705         } else {
9706                 // Let the second HTLC fail and claim the first
9707                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9708                 nodes[1].node.process_pending_htlc_forwards();
9709
9710                 check_added_monitors!(nodes[1], 1);
9711                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9712                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9713                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9714
9715                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9716
9717                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9718         }
9719 }
9720
9721 #[test]
9722 fn test_dup_htlc_second_fail_panic() {
9723         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9724         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9725         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9726         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9727         do_test_dup_htlc_second_rejected(true);
9728 }
9729
9730 #[test]
9731 fn test_dup_htlc_second_rejected() {
9732         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9733         // simply reject the second HTLC but are still able to claim the first HTLC.
9734         do_test_dup_htlc_second_rejected(false);
9735 }
9736
9737 #[test]
9738 fn test_inconsistent_mpp_params() {
9739         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9740         // such HTLC and allow the second to stay.
9741         let chanmon_cfgs = create_chanmon_cfgs(4);
9742         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9743         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9744         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9745
9746         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9747         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9748         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9749         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9750
9751         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9752                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9753         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9754         assert_eq!(route.paths.len(), 2);
9755         route.paths.sort_by(|path_a, _| {
9756                 // Sort the path so that the path through nodes[1] comes first
9757                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9758                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9759         });
9760
9761         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9762
9763         let cur_height = nodes[0].best_block_info().1;
9764         let payment_id = PaymentId([42; 32]);
9765
9766         let session_privs = {
9767                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9768                 // ultimately have, just not right away.
9769                 let mut dup_route = route.clone();
9770                 dup_route.paths.push(route.paths[1].clone());
9771                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9772                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9773         };
9774         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9775                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9776                 &None, session_privs[0]).unwrap();
9777         check_added_monitors!(nodes[0], 1);
9778
9779         {
9780                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9781                 assert_eq!(events.len(), 1);
9782                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9783         }
9784         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9785
9786         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9787                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9788         check_added_monitors!(nodes[0], 1);
9789
9790         {
9791                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9792                 assert_eq!(events.len(), 1);
9793                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9794
9795                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9796                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9797
9798                 expect_pending_htlcs_forwardable!(nodes[2]);
9799                 check_added_monitors!(nodes[2], 1);
9800
9801                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9802                 assert_eq!(events.len(), 1);
9803                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9804
9805                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9806                 check_added_monitors!(nodes[3], 0);
9807                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9808
9809                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9810                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9811                 // post-payment_secrets) and fail back the new HTLC.
9812         }
9813         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9814         nodes[3].node.process_pending_htlc_forwards();
9815         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9816         nodes[3].node.process_pending_htlc_forwards();
9817
9818         check_added_monitors!(nodes[3], 1);
9819
9820         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9821         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9822         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9823
9824         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 }]);
9825         check_added_monitors!(nodes[2], 1);
9826
9827         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9828         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9829         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9830
9831         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9832
9833         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9834                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9835                 &None, session_privs[2]).unwrap();
9836         check_added_monitors!(nodes[0], 1);
9837
9838         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9839         assert_eq!(events.len(), 1);
9840         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9841
9842         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9843         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9844 }
9845
9846 #[test]
9847 fn test_double_partial_claim() {
9848         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9849         // time out, the sender resends only some of the MPP parts, then the user processes the
9850         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9851         // amount.
9852         let chanmon_cfgs = create_chanmon_cfgs(4);
9853         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9854         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9855         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9856
9857         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9858         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9859         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9860         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9861
9862         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9863         assert_eq!(route.paths.len(), 2);
9864         route.paths.sort_by(|path_a, _| {
9865                 // Sort the path so that the path through nodes[1] comes first
9866                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9867                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9868         });
9869
9870         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9871         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9872         // amount of time to respond to.
9873
9874         // Connect some blocks to time out the payment
9875         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9876         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9877
9878         let failed_destinations = vec![
9879                 HTLCDestination::FailedPayment { payment_hash },
9880                 HTLCDestination::FailedPayment { payment_hash },
9881         ];
9882         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9883
9884         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9885
9886         // nodes[1] now retries one of the two paths...
9887         nodes[0].node.send_payment_with_route(&route, payment_hash,
9888                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9889         check_added_monitors!(nodes[0], 2);
9890
9891         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9892         assert_eq!(events.len(), 2);
9893         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9894         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9895
9896         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9897         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9898         nodes[3].node.claim_funds(payment_preimage);
9899         check_added_monitors!(nodes[3], 0);
9900         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9901 }
9902
9903 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9904 #[derive(Clone, Copy, PartialEq)]
9905 enum ExposureEvent {
9906         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9907         AtHTLCForward,
9908         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9909         AtHTLCReception,
9910         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9911         AtUpdateFeeOutbound,
9912 }
9913
9914 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool, apply_excess_fee: bool) {
9915         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9916         // policy.
9917         //
9918         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9919         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9920         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9921         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9922         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9923         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9924         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9925         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9926
9927         let chanmon_cfgs = create_chanmon_cfgs(2);
9928         let mut config = test_default_channel_config();
9929
9930         // We hard-code the feerate values here but they're re-calculated furter down and asserted.
9931         // If the values ever change below these constants should simply be updated.
9932         const AT_FEE_OUTBOUND_HTLCS: u64 = 20;
9933         let nondust_htlc_count_in_limit =
9934         if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound  {
9935                 AT_FEE_OUTBOUND_HTLCS
9936         } else { 0 };
9937         let initial_feerate = if apply_excess_fee { 253 * 2 } else { 253 };
9938         let expected_dust_buffer_feerate = initial_feerate + 2530;
9939         let mut commitment_tx_cost = commit_tx_fee_msat(initial_feerate - 253, nondust_htlc_count_in_limit, &ChannelTypeFeatures::empty());
9940         commitment_tx_cost +=
9941                 if on_holder_tx {
9942                         htlc_success_tx_weight(&ChannelTypeFeatures::empty())
9943                 } else {
9944                         htlc_timeout_tx_weight(&ChannelTypeFeatures::empty())
9945                 } * (initial_feerate as u64 - 253) / 1000 * nondust_htlc_count_in_limit;
9946         {
9947                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9948                 *feerate_lock = initial_feerate;
9949         }
9950         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9951                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9952                 // to get roughly the same initial value as the default setting when this test was
9953                 // originally written.
9954                 MaxDustHTLCExposure::FeeRateMultiplier((5_000_000 + commitment_tx_cost) / 253)
9955         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000 + commitment_tx_cost) };
9956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9958         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9959
9960         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9961         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9962         open_channel.common_fields.max_htlc_value_in_flight_msat = 50_000_000;
9963         open_channel.common_fields.max_accepted_htlcs = 60;
9964         if on_holder_tx {
9965                 open_channel.common_fields.dust_limit_satoshis = 546;
9966         }
9967         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9968         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9969         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9970
9971         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9972
9973         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9974
9975         if on_holder_tx {
9976                 let mut node_0_per_peer_lock;
9977                 let mut node_0_peer_state_lock;
9978                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9979                         ChannelPhase::UnfundedOutboundV1(chan) => {
9980                                 chan.context.holder_dust_limit_satoshis = 546;
9981                         },
9982                         _ => panic!("Unexpected ChannelPhase variant"),
9983                 }
9984         }
9985
9986         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9987         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()));
9988         check_added_monitors!(nodes[1], 1);
9989         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9990
9991         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()));
9992         check_added_monitors!(nodes[0], 1);
9993         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9994
9995         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9996         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9997         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9998
9999         {
10000                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10001                 *feerate_lock = 253;
10002         }
10003
10004         // Fetch a route in advance as we will be unable to once we're unable to send.
10005         let (mut route, payment_hash, _, payment_secret) =
10006                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
10007
10008         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
10009                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10010                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10011                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
10012                 (chan.context().get_dust_buffer_feerate(None) as u64,
10013                 chan.context().get_max_dust_htlc_exposure_msat(253))
10014         };
10015         assert_eq!(dust_buffer_feerate, expected_dust_buffer_feerate as u64);
10016         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;
10017         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10018
10019         // Substract 3 sats for multiplier and 2 sats for fixed limit to make sure we are 50% below the dust limit.
10020         // This is to make sure we fully use the dust limit. If we don't, we could end up with `dust_ibd_htlc_on_holder_tx` being 1
10021         // while `max_dust_htlc_exposure_msat` is not equal to `dust_outbound_htlc_on_holder_tx_msat`.
10022         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - if multiplier_dust_limit { 3 } else { 2 }) * 1000;
10023         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10024
10025         // This test was written with a fixed dust value here, which we retain, but assert that it is,
10026         // indeed, dust on both transactions.
10027         let dust_htlc_on_counterparty_tx: u64 = 4;
10028         let dust_htlc_on_counterparty_tx_msat: u64 = 1_250_000;
10029         let calcd_dust_htlc_on_counterparty_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - if multiplier_dust_limit { 3 } else { 2 }) * 1000;
10030         assert!(dust_htlc_on_counterparty_tx_msat < dust_inbound_htlc_on_holder_tx_msat);
10031         assert!(dust_htlc_on_counterparty_tx_msat < calcd_dust_htlc_on_counterparty_tx_msat);
10032
10033         if on_holder_tx {
10034                 if dust_outbound_balance {
10035                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10036                         // Outbound dust balance: 4372 sats
10037                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10038                         for _ in 0..dust_outbound_htlc_on_holder_tx {
10039                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10040                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10041                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10042                         }
10043                 } else {
10044                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10045                         // Inbound dust balance: 4372 sats
10046                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10047                         for _ in 0..dust_inbound_htlc_on_holder_tx {
10048                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10049                         }
10050                 }
10051         } else {
10052                 if dust_outbound_balance {
10053                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10054                         // Outbound dust balance: 5000 sats
10055                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
10056                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10057                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
10058                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10059                         }
10060                 } else {
10061                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10062                         // Inbound dust balance: 5000 sats
10063                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
10064                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10065                         }
10066                 }
10067         }
10068
10069         if exposure_breach_event == ExposureEvent::AtHTLCForward {
10070                 route.paths[0].hops.last_mut().unwrap().fee_msat =
10071                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
10072                 // With default dust exposure: 5000 sats
10073                 if on_holder_tx {
10074                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10075                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10076                                 ), true, APIError::ChannelUnavailable { .. }, {});
10077                 } else {
10078                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10079                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10080                                 ), true, APIError::ChannelUnavailable { .. }, {});
10081                 }
10082         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10083                 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 });
10084                 nodes[1].node.send_payment_with_route(&route, payment_hash,
10085                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10086                 check_added_monitors!(nodes[1], 1);
10087                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10088                 assert_eq!(events.len(), 1);
10089                 let payment_event = SendEvent::from_event(events.remove(0));
10090                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10091                 // With default dust exposure: 5000 sats
10092                 if on_holder_tx {
10093                         // Outbound dust balance: 6399 sats
10094                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10095                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10096                         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);
10097                 } else {
10098                         // Outbound dust balance: 5200 sats
10099                         nodes[0].logger.assert_log("lightning::ln::channel",
10100                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
10101                                         dust_htlc_on_counterparty_tx_msat * dust_htlc_on_counterparty_tx + commitment_tx_cost + 4,
10102                                         max_dust_htlc_exposure_msat), 1);
10103                 }
10104         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10105                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
10106                 // For the multiplier dust exposure limit, since it scales with feerate,
10107                 // we need to add a lot of HTLCs that will become dust at the new feerate
10108                 // to cross the threshold.
10109                 for _ in 0..AT_FEE_OUTBOUND_HTLCS {
10110                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
10111                         nodes[0].node.send_payment_with_route(&route, payment_hash,
10112                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10113                 }
10114                 {
10115                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10116                         *feerate_lock = *feerate_lock * 10;
10117                 }
10118                 nodes[0].node.timer_tick_occurred();
10119                 check_added_monitors!(nodes[0], 1);
10120                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
10121         }
10122
10123         let _ = nodes[0].node.get_and_clear_pending_msg_events();
10124         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10125         added_monitors.clear();
10126 }
10127
10128 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool, apply_excess_fee: bool) {
10129         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit, apply_excess_fee);
10130         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit, apply_excess_fee);
10131         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit, apply_excess_fee);
10132         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit, apply_excess_fee);
10133         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit, apply_excess_fee);
10134         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit, apply_excess_fee);
10135         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit, apply_excess_fee);
10136         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit, apply_excess_fee);
10137         if !multiplier_dust_limit && !apply_excess_fee {
10138                 // Because non-dust HTLC transaction fees are included in the dust exposure, trying to
10139                 // increase the fee to hit a higher dust exposure with a
10140                 // `MaxDustHTLCExposure::FeeRateMultiplier` is no longer super practical, so we skip these
10141                 // in the `multiplier_dust_limit` case.
10142                 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit, apply_excess_fee);
10143                 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit, apply_excess_fee);
10144                 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit, apply_excess_fee);
10145                 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit, apply_excess_fee);
10146         }
10147 }
10148
10149 #[test]
10150 fn test_max_dust_htlc_exposure() {
10151         do_test_max_dust_htlc_exposure_by_threshold_type(false, false);
10152         do_test_max_dust_htlc_exposure_by_threshold_type(false, true);
10153         do_test_max_dust_htlc_exposure_by_threshold_type(true, false);
10154         do_test_max_dust_htlc_exposure_by_threshold_type(true, true);
10155 }
10156
10157 #[test]
10158 fn test_nondust_htlc_fees_are_dust() {
10159         // Test that the transaction fees paid in nondust HTLCs count towards our dust limit
10160         let chanmon_cfgs = create_chanmon_cfgs(3);
10161         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10162
10163         let mut config = test_default_channel_config();
10164         // Set the dust limit to the default value
10165         config.channel_config.max_dust_htlc_exposure =
10166                 MaxDustHTLCExposure::FeeRateMultiplier(10_000);
10167         // Make sure the HTLC limits don't get in the way
10168         config.channel_handshake_limits.min_max_accepted_htlcs = 400;
10169         config.channel_handshake_config.our_max_accepted_htlcs = 400;
10170         config.channel_handshake_config.our_htlc_minimum_msat = 1;
10171
10172         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
10173         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10174
10175         // Create a channel from 1 -> 0 but immediately push all of the funds towards 0
10176         let chan_id_1 = create_announced_chan_between_nodes(&nodes, 1, 0).2;
10177         while nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat > 0 {
10178                 send_payment(&nodes[1], &[&nodes[0]], nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat);
10179         }
10180
10181         // First get the channel one HTLC_VALUE HTLC away from the dust limit by sending dust HTLCs
10182         // repeatedly until we run out of space.
10183         const HTLC_VALUE: u64 = 1_000_000; // Doesn't matter, tune until the test passes
10184         let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], HTLC_VALUE).0;
10185
10186         while nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat == 0 {
10187                 route_payment(&nodes[0], &[&nodes[1]], HTLC_VALUE);
10188         }
10189         assert_ne!(nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat, 0,
10190                 "We don't want to run out of ability to send because of some non-dust limit");
10191         assert!(nodes[0].node.list_channels()[0].pending_outbound_htlcs.len() < 10,
10192                 "We should be able to fill our dust limit without too many HTLCs");
10193
10194         let dust_limit = nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat;
10195         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
10196         assert_ne!(nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat, 0,
10197                 "Make sure we are able to send once we clear one HTLC");
10198
10199         // At this point we have somewhere between dust_limit and dust_limit * 2 left in our dust
10200         // exposure limit, and we want to max that out using non-dust HTLCs.
10201         let commitment_tx_per_htlc_cost =
10202                 htlc_success_tx_weight(&ChannelTypeFeatures::empty()) * 253;
10203         let max_htlcs_remaining = dust_limit * 2 / commitment_tx_per_htlc_cost;
10204         assert!(max_htlcs_remaining < 30,
10205                 "We should be able to fill our dust limit without too many HTLCs");
10206         for i in 0..max_htlcs_remaining + 1 {
10207                 assert_ne!(i, max_htlcs_remaining);
10208                 if nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat < dust_limit {
10209                         // We found our limit, and it was less than max_htlcs_remaining!
10210                         // At this point we can only send dust HTLCs as any non-dust HTLCs will overuse our
10211                         // remaining dust exposure.
10212                         break;
10213                 }
10214                 route_payment(&nodes[0], &[&nodes[1]], dust_limit * 2);
10215         }
10216
10217         // At this point non-dust HTLCs are no longer accepted from node 0 -> 1, we also check that
10218         // such HTLCs can't be routed over the same channel either.
10219         create_announced_chan_between_nodes(&nodes, 2, 0);
10220         let (route, payment_hash, _, payment_secret) =
10221                 get_route_and_payment_hash!(nodes[2], nodes[1], dust_limit * 2);
10222         let onion = RecipientOnionFields::secret_only(payment_secret);
10223         nodes[2].node.send_payment_with_route(&route, payment_hash, onion, PaymentId([0; 32])).unwrap();
10224         check_added_monitors(&nodes[2], 1);
10225         let send = SendEvent::from_node(&nodes[2]);
10226
10227         nodes[0].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send.msgs[0]);
10228         commitment_signed_dance!(nodes[0], nodes[2], send.commitment_msg, false, true);
10229
10230         expect_pending_htlcs_forwardable!(nodes[0]);
10231         check_added_monitors(&nodes[0], 1);
10232         let node_id_1 = nodes[1].node.get_our_node_id();
10233         expect_htlc_handling_failed_destinations!(
10234                 nodes[0].node.get_and_clear_pending_events(),
10235                 &[HTLCDestination::NextHopChannel { node_id: Some(node_id_1), channel_id: chan_id_1 }]
10236         );
10237
10238         let fail = get_htlc_update_msgs(&nodes[0], &nodes[2].node.get_our_node_id());
10239         nodes[2].node.handle_update_fail_htlc(&nodes[0].node.get_our_node_id(), &fail.update_fail_htlcs[0]);
10240         commitment_signed_dance!(nodes[2], nodes[0], fail.commitment_signed, false);
10241         expect_payment_failed_conditions(&nodes[2], payment_hash, false, PaymentFailedConditions::new());
10242 }
10243
10244
10245 #[test]
10246 fn test_non_final_funding_tx() {
10247         let chanmon_cfgs = create_chanmon_cfgs(2);
10248         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10249         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10250         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10251
10252         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10253         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10254         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10255         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10256         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10257
10258         let best_height = nodes[0].node.best_block.read().unwrap().height;
10259
10260         let chan_id = *nodes[0].network_chan_count.borrow();
10261         let events = nodes[0].node.get_and_clear_pending_events();
10262         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
10263         assert_eq!(events.len(), 1);
10264         let mut tx = match events[0] {
10265                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10266                         // Timelock the transaction _beyond_ the best client height + 1.
10267                         Transaction { version: Version(chan_id as i32), lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
10268                                 value: Amount::from_sat(*channel_value_satoshis), script_pubkey: output_script.clone(),
10269                         }]}
10270                 },
10271                 _ => panic!("Unexpected event"),
10272         };
10273         // Transaction should fail as it's evaluated as non-final for propagation.
10274         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10275                 Err(APIError::APIMisuseError { err }) => {
10276                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10277                 },
10278                 _ => panic!()
10279         }
10280         let err = "Error in transaction funding: Misuse error: Funding transaction absolute timelock is non-final".to_owned();
10281         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(temp_channel_id, false, ClosureReason::ProcessingError { err })]);
10282         assert_eq!(get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id()).data, "Failed to fund channel");
10283 }
10284
10285 #[test]
10286 fn test_non_final_funding_tx_within_headroom() {
10287         let chanmon_cfgs = create_chanmon_cfgs(2);
10288         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10289         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10290         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10291
10292         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10293         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10294         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10295         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10296         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10297
10298         let best_height = nodes[0].node.best_block.read().unwrap().height;
10299
10300         let chan_id = *nodes[0].network_chan_count.borrow();
10301         let events = nodes[0].node.get_and_clear_pending_events();
10302         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10303         assert_eq!(events.len(), 1);
10304         let mut tx = match events[0] {
10305                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10306                         // Timelock the transaction within a +1 headroom from the best block.
10307                         Transaction { version: Version(chan_id as i32), lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10308                                 value: Amount::from_sat(*channel_value_satoshis), script_pubkey: output_script.clone(),
10309                         }]}
10310                 },
10311                 _ => panic!("Unexpected event"),
10312         };
10313
10314         // Transaction should be accepted if it's in a +1 headroom from best block.
10315         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10316         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10317 }
10318
10319 #[test]
10320 fn accept_busted_but_better_fee() {
10321         // If a peer sends us a fee update that is too low, but higher than our previous channel
10322         // feerate, we should accept it. In the future we may want to consider closing the channel
10323         // later, but for now we only accept the update.
10324         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10327         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10328
10329         create_chan_between_nodes(&nodes[0], &nodes[1]);
10330
10331         // Set nodes[1] to expect 5,000 sat/kW.
10332         {
10333                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10334                 *feerate_lock = 5000;
10335         }
10336
10337         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10338         {
10339                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10340                 *feerate_lock = 1000;
10341         }
10342         nodes[0].node.timer_tick_occurred();
10343         check_added_monitors!(nodes[0], 1);
10344
10345         let events = nodes[0].node.get_and_clear_pending_msg_events();
10346         assert_eq!(events.len(), 1);
10347         match events[0] {
10348                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10349                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10350                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10351                 },
10352                 _ => panic!("Unexpected event"),
10353         };
10354
10355         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10356         // it.
10357         {
10358                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10359                 *feerate_lock = 2000;
10360         }
10361         nodes[0].node.timer_tick_occurred();
10362         check_added_monitors!(nodes[0], 1);
10363
10364         let events = nodes[0].node.get_and_clear_pending_msg_events();
10365         assert_eq!(events.len(), 1);
10366         match events[0] {
10367                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10368                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10369                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10370                 },
10371                 _ => panic!("Unexpected event"),
10372         };
10373
10374         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10375         // channel.
10376         {
10377                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10378                 *feerate_lock = 1000;
10379         }
10380         nodes[0].node.timer_tick_occurred();
10381         check_added_monitors!(nodes[0], 1);
10382
10383         let events = nodes[0].node.get_and_clear_pending_msg_events();
10384         assert_eq!(events.len(), 1);
10385         match events[0] {
10386                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10387                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10388                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10389                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10390                                 [nodes[0].node.get_our_node_id()], 100000);
10391                         check_closed_broadcast!(nodes[1], true);
10392                         check_added_monitors!(nodes[1], 1);
10393                 },
10394                 _ => panic!("Unexpected event"),
10395         };
10396 }
10397
10398 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10399         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10400         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10401         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10402         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10403         let min_final_cltv_expiry_delta = 120;
10404         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10405                 min_final_cltv_expiry_delta - 2 };
10406         let recv_value = 100_000;
10407
10408         create_chan_between_nodes(&nodes[0], &nodes[1]);
10409
10410         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10411         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10412                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10413                         Some(recv_value), Some(min_final_cltv_expiry_delta));
10414                 (payment_hash, payment_preimage, payment_secret)
10415         } else {
10416                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10417                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10418         };
10419         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10420         nodes[0].node.send_payment_with_route(&route, payment_hash,
10421                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10422         check_added_monitors!(nodes[0], 1);
10423         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10424         assert_eq!(events.len(), 1);
10425         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10426         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10427         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10428         expect_pending_htlcs_forwardable!(nodes[1]);
10429
10430         if valid_delta {
10431                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10432                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10433
10434                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10435         } else {
10436                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10437
10438                 check_added_monitors!(nodes[1], 1);
10439
10440                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10441                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10442                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10443
10444                 expect_payment_failed!(nodes[0], payment_hash, true);
10445         }
10446 }
10447
10448 #[test]
10449 fn test_payment_with_custom_min_cltv_expiry_delta() {
10450         do_payment_with_custom_min_final_cltv_expiry(false, false);
10451         do_payment_with_custom_min_final_cltv_expiry(false, true);
10452         do_payment_with_custom_min_final_cltv_expiry(true, false);
10453         do_payment_with_custom_min_final_cltv_expiry(true, true);
10454 }
10455
10456 #[test]
10457 fn test_disconnects_peer_awaiting_response_ticks() {
10458         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10459         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10460         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10461         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10462         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10463         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10464
10465         // Asserts a disconnect event is queued to the user.
10466         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10467                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10468                         if let MessageSendEvent::HandleError { action, .. } = event {
10469                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10470                                         Some(())
10471                                 } else {
10472                                         None
10473                                 }
10474                         } else {
10475                                 None
10476                         }
10477                 );
10478                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10479         };
10480
10481         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10482         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10483         let check_disconnect = |node: &Node| {
10484                 // No disconnect without any timer ticks.
10485                 check_disconnect_event(node, false);
10486
10487                 // No disconnect with 1 timer tick less than required.
10488                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10489                         node.node.timer_tick_occurred();
10490                         check_disconnect_event(node, false);
10491                 }
10492
10493                 // Disconnect after reaching the required ticks.
10494                 node.node.timer_tick_occurred();
10495                 check_disconnect_event(node, true);
10496
10497                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10498                 node.node.timer_tick_occurred();
10499                 check_disconnect_event(node, true);
10500         };
10501
10502         create_chan_between_nodes(&nodes[0], &nodes[1]);
10503
10504         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10505         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10506         nodes[0].node.timer_tick_occurred();
10507         check_added_monitors!(&nodes[0], 1);
10508         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10509         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10510         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10511         check_added_monitors!(&nodes[1], 1);
10512
10513         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10514         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10515         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10516         check_added_monitors!(&nodes[0], 1);
10517         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10518         check_added_monitors(&nodes[0], 1);
10519
10520         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10521         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10522         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10523         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10524         check_disconnect(&nodes[1]);
10525
10526         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10527         //
10528         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10529         // final `RevokeAndACK` to Bob to complete it.
10530         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10531         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10532         let bob_init = msgs::Init {
10533                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10534         };
10535         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10536         let alice_init = msgs::Init {
10537                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10538         };
10539         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10540
10541         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10542         // received Bob's yet, so she should disconnect him after reaching
10543         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10544         let alice_channel_reestablish = get_event_msg!(
10545                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10546         );
10547         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10548         check_disconnect(&nodes[0]);
10549
10550         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10551         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10552                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10553                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10554                         Some(msg.clone())
10555                 } else {
10556                         None
10557                 }
10558         ).unwrap();
10559         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10560
10561         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10562         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10563                 nodes[0].node.timer_tick_occurred();
10564                 check_disconnect_event(&nodes[0], false);
10565         }
10566
10567         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10568         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10569         check_disconnect(&nodes[1]);
10570
10571         // Finally, have Bob process the last message.
10572         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10573         check_added_monitors(&nodes[1], 1);
10574
10575         // At this point, neither node should attempt to disconnect each other, since they aren't
10576         // waiting on any messages.
10577         for node in &nodes {
10578                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10579                         node.node.timer_tick_occurred();
10580                         check_disconnect_event(node, false);
10581                 }
10582         }
10583 }
10584
10585 #[test]
10586 fn test_remove_expired_outbound_unfunded_channels() {
10587         let chanmon_cfgs = create_chanmon_cfgs(2);
10588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10590         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10591
10592         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10593         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10594         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10595         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10596         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10597
10598         let events = nodes[0].node.get_and_clear_pending_events();
10599         assert_eq!(events.len(), 1);
10600         match events[0] {
10601                 Event::FundingGenerationReady { .. } => (),
10602                 _ => panic!("Unexpected event"),
10603         };
10604
10605         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10606         let check_outbound_channel_existence = |should_exist: bool| {
10607                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10608                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10609                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10610         };
10611
10612         // Channel should exist without any timer ticks.
10613         check_outbound_channel_existence(true);
10614
10615         // Channel should exist with 1 timer tick less than required.
10616         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10617                 nodes[0].node.timer_tick_occurred();
10618                 check_outbound_channel_existence(true)
10619         }
10620
10621         // Remove channel after reaching the required ticks.
10622         nodes[0].node.timer_tick_occurred();
10623         check_outbound_channel_existence(false);
10624
10625         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10626         assert_eq!(msg_events.len(), 1);
10627         match msg_events[0] {
10628                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10629                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10630                 },
10631                 _ => panic!("Unexpected event"),
10632         }
10633         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10634 }
10635
10636 #[test]
10637 fn test_remove_expired_inbound_unfunded_channels() {
10638         let chanmon_cfgs = create_chanmon_cfgs(2);
10639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10641         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10642
10643         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10644         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10645         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10646         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10647         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10648
10649         let events = nodes[0].node.get_and_clear_pending_events();
10650         assert_eq!(events.len(), 1);
10651         match events[0] {
10652                 Event::FundingGenerationReady { .. } => (),
10653                 _ => panic!("Unexpected event"),
10654         };
10655
10656         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10657         let check_inbound_channel_existence = |should_exist: bool| {
10658                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10659                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10660                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10661         };
10662
10663         // Channel should exist without any timer ticks.
10664         check_inbound_channel_existence(true);
10665
10666         // Channel should exist with 1 timer tick less than required.
10667         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10668                 nodes[1].node.timer_tick_occurred();
10669                 check_inbound_channel_existence(true)
10670         }
10671
10672         // Remove channel after reaching the required ticks.
10673         nodes[1].node.timer_tick_occurred();
10674         check_inbound_channel_existence(false);
10675
10676         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10677         assert_eq!(msg_events.len(), 1);
10678         match msg_events[0] {
10679                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10680                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10681                 },
10682                 _ => panic!("Unexpected event"),
10683         }
10684         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10685 }
10686
10687 #[test]
10688 fn test_channel_close_when_not_timely_accepted() {
10689         // Create network of two nodes
10690         let chanmon_cfgs = create_chanmon_cfgs(2);
10691         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10692         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10693         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10694
10695         // Simulate peer-disconnects mid-handshake
10696         // The channel is initiated from the node 0 side,
10697         // but the nodes disconnect before node 1 could send accept channel
10698         let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10699         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10700         assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10701
10702         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10703         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10704
10705         // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10706         assert_eq!(nodes[0].node.list_channels().len(), 1);
10707
10708         // Since channel was inbound from node[1] perspective, it should have been dropped immediately.
10709         assert_eq!(nodes[1].node.list_channels().len(), 0);
10710
10711         // In the meantime, some time passes.
10712         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
10713                 nodes[0].node.timer_tick_occurred();
10714         }
10715
10716         // Since we disconnected from peer and did not connect back within time,
10717         // we should have forced-closed the channel by now.
10718         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
10719         assert_eq!(nodes[0].node.list_channels().len(), 0);
10720
10721         {
10722                 // Since accept channel message was never received
10723                 // The channel should be forced close by now from node 0 side
10724                 // and the peer removed from per_peer_state
10725                 let node_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10726                 assert_eq!(node_0_per_peer_state.len(), 0);
10727         }
10728 }
10729
10730 #[test]
10731 fn test_rebroadcast_open_channel_when_reconnect_mid_handshake() {
10732         // Create network of two nodes
10733         let chanmon_cfgs = create_chanmon_cfgs(2);
10734         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10735         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10736         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10737
10738         // Simulate peer-disconnects mid-handshake
10739         // The channel is initiated from the node 0 side,
10740         // but the nodes disconnect before node 1 could send accept channel
10741         let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10742         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10743         assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10744
10745         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10746         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10747
10748         // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10749         assert_eq!(nodes[0].node.list_channels().len(), 1);
10750
10751         // Since channel was inbound from node[1] perspective, it should have been immediately dropped.
10752         assert_eq!(nodes[1].node.list_channels().len(), 0);
10753
10754         // The peers now reconnect
10755         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
10756                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10757         }, true).unwrap();
10758         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10759                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10760         }, false).unwrap();
10761
10762         // Make sure the SendOpenChannel message is added to node_0 pending message events
10763         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10764         assert_eq!(msg_events.len(), 1);
10765         match &msg_events[0] {
10766                 MessageSendEvent::SendOpenChannel { msg, .. } => assert_eq!(msg, &open_channel_msg),
10767                 _ => panic!("Unexpected message."),
10768         }
10769 }
10770
10771 fn do_test_multi_post_event_actions(do_reload: bool) {
10772         // Tests handling multiple post-Event actions at once.
10773         // There is specific code in ChannelManager to handle channels where multiple post-Event
10774         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10775         //
10776         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10777         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10778         // - one from an RAA and one from an inbound commitment_signed.
10779         let chanmon_cfgs = create_chanmon_cfgs(3);
10780         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10781         let (persister, chain_monitor);
10782         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10783         let nodes_0_deserialized;
10784         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10785
10786         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10787         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10788
10789         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10790         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10791
10792         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10793         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10794
10795         nodes[1].node.claim_funds(our_payment_preimage);
10796         check_added_monitors!(nodes[1], 1);
10797         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10798
10799         nodes[2].node.claim_funds(payment_preimage_2);
10800         check_added_monitors!(nodes[2], 1);
10801         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10802
10803         for dest in &[1, 2] {
10804                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10805                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10806                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10807                 check_added_monitors(&nodes[0], 0);
10808         }
10809
10810         let (route, payment_hash_3, _, payment_secret_3) =
10811                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10812         let payment_id = PaymentId(payment_hash_3.0);
10813         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10814                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10815         check_added_monitors(&nodes[1], 1);
10816
10817         let send_event = SendEvent::from_node(&nodes[1]);
10818         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10819         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10820         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10821
10822         if do_reload {
10823                 let nodes_0_serialized = nodes[0].node.encode();
10824                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10825                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10826                 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);
10827
10828                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10829                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10830
10831                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10832                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10833         }
10834
10835         let events = nodes[0].node.get_and_clear_pending_events();
10836         assert_eq!(events.len(), 4);
10837         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10838                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10839         } else { panic!(); }
10840         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10841                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10842         } else { panic!(); }
10843         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10844         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10845
10846         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10847         // completion, we'll respond to nodes[1] with an RAA + CS.
10848         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10849         check_added_monitors(&nodes[0], 3);
10850 }
10851
10852 #[test]
10853 fn test_multi_post_event_actions() {
10854         do_test_multi_post_event_actions(true);
10855         do_test_multi_post_event_actions(false);
10856 }
10857
10858 #[test]
10859 fn test_batch_channel_open() {
10860         let chanmon_cfgs = create_chanmon_cfgs(3);
10861         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10862         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10863         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10864
10865         // Initiate channel opening and create the batch channel funding transaction.
10866         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10867                 (&nodes[1], 100_000, 0, 42, None),
10868                 (&nodes[2], 200_000, 0, 43, None),
10869         ]);
10870
10871         // Go through the funding_created and funding_signed flow with node 1.
10872         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10873         check_added_monitors(&nodes[1], 1);
10874         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10875
10876         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10877         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10878         check_added_monitors(&nodes[0], 1);
10879
10880         // The transaction should not have been broadcast before all channels are ready.
10881         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10882
10883         // Go through the funding_created and funding_signed flow with node 2.
10884         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10885         check_added_monitors(&nodes[2], 1);
10886         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10887
10888         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10889         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10890         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10891         check_added_monitors(&nodes[0], 1);
10892
10893         // The transaction should not have been broadcast before persisting all monitors has been
10894         // completed.
10895         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10896         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10897
10898         // Complete the persistence of the monitor.
10899         nodes[0].chain_monitor.complete_sole_pending_chan_update(
10900                 &ChannelId::v1_from_funding_outpoint(OutPoint { txid: tx.txid(), index: 1 })
10901         );
10902         let events = nodes[0].node.get_and_clear_pending_events();
10903
10904         // The transaction should only have been broadcast now.
10905         let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10906         assert_eq!(broadcasted_txs.len(), 1);
10907         assert_eq!(broadcasted_txs[0], tx);
10908
10909         assert_eq!(events.len(), 2);
10910         assert!(events.iter().any(|e| matches!(
10911                 *e,
10912                 crate::events::Event::ChannelPending {
10913                         ref counterparty_node_id,
10914                         ..
10915                 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10916         )));
10917         assert!(events.iter().any(|e| matches!(
10918                 *e,
10919                 crate::events::Event::ChannelPending {
10920                         ref counterparty_node_id,
10921                         ..
10922                 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10923         )));
10924 }
10925
10926 #[test]
10927 fn test_close_in_funding_batch() {
10928         // This test ensures that if one of the channels
10929         // in the batch closes, the complete batch will close.
10930         let chanmon_cfgs = create_chanmon_cfgs(3);
10931         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10932         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10933         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10934
10935         // Initiate channel opening and create the batch channel funding transaction.
10936         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10937                 (&nodes[1], 100_000, 0, 42, None),
10938                 (&nodes[2], 200_000, 0, 43, None),
10939         ]);
10940
10941         // Go through the funding_created and funding_signed flow with node 1.
10942         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10943         check_added_monitors(&nodes[1], 1);
10944         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10945
10946         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10947         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10948         check_added_monitors(&nodes[0], 1);
10949
10950         // The transaction should not have been broadcast before all channels are ready.
10951         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10952
10953         // Force-close the channel for which we've completed the initial monitor.
10954         let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10955         let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10956         let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10957         let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10958
10959         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10960
10961         // The monitor should become closed.
10962         check_added_monitors(&nodes[0], 1);
10963         {
10964                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10965                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10966                 assert_eq!(monitor_updates_1.len(), 1);
10967                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10968         }
10969
10970         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10971         match msg_events[0] {
10972                 MessageSendEvent::HandleError { .. } => (),
10973                 _ => panic!("Unexpected message."),
10974         }
10975
10976         // We broadcast the commitment transaction as part of the force-close.
10977         {
10978                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10979                 assert_eq!(broadcasted_txs.len(), 1);
10980                 assert!(broadcasted_txs[0].txid() != tx.txid());
10981                 assert_eq!(broadcasted_txs[0].input.len(), 1);
10982                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10983         }
10984
10985         // All channels in the batch should close immediately.
10986         check_closed_events(&nodes[0], &[
10987                 ExpectedCloseEvent {
10988                         channel_id: Some(channel_id_1),
10989                         discard_funding: true,
10990                         channel_funding_txo: Some(funding_txo_1),
10991                         user_channel_id: Some(42),
10992                         ..Default::default()
10993                 },
10994                 ExpectedCloseEvent {
10995                         channel_id: Some(channel_id_2),
10996                         discard_funding: true,
10997                         channel_funding_txo: Some(funding_txo_2),
10998                         user_channel_id: Some(43),
10999                         ..Default::default()
11000                 },
11001         ]);
11002
11003         // Ensure the channels don't exist anymore.
11004         assert!(nodes[0].node.list_channels().is_empty());
11005 }
11006
11007 #[test]
11008 fn test_batch_funding_close_after_funding_signed() {
11009         let chanmon_cfgs = create_chanmon_cfgs(3);
11010         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11011         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
11012         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11013
11014         // Initiate channel opening and create the batch channel funding transaction.
11015         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
11016                 (&nodes[1], 100_000, 0, 42, None),
11017                 (&nodes[2], 200_000, 0, 43, None),
11018         ]);
11019
11020         // Go through the funding_created and funding_signed flow with node 1.
11021         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
11022         check_added_monitors(&nodes[1], 1);
11023         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11024
11025         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11026         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
11027         check_added_monitors(&nodes[0], 1);
11028
11029         // Go through the funding_created and funding_signed flow with node 2.
11030         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
11031         check_added_monitors(&nodes[2], 1);
11032         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
11033
11034         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11035         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
11036         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
11037         check_added_monitors(&nodes[0], 1);
11038
11039         // The transaction should not have been broadcast before all channels are ready.
11040         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
11041
11042         // Force-close the channel for which we've completed the initial monitor.
11043         let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
11044         let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
11045         let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
11046         let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
11047         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
11048         check_added_monitors(&nodes[0], 2);
11049         {
11050                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
11051                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
11052                 assert_eq!(monitor_updates_1.len(), 1);
11053                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
11054                 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
11055                 assert_eq!(monitor_updates_2.len(), 1);
11056                 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
11057         }
11058         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
11059         match msg_events[0] {
11060                 MessageSendEvent::HandleError { .. } => (),
11061                 _ => panic!("Unexpected message."),
11062         }
11063
11064         // We broadcast the commitment transaction as part of the force-close.
11065         {
11066                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
11067                 assert_eq!(broadcasted_txs.len(), 1);
11068                 assert!(broadcasted_txs[0].txid() != tx.txid());
11069                 assert_eq!(broadcasted_txs[0].input.len(), 1);
11070                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
11071         }
11072
11073         // All channels in the batch should close immediately.
11074         check_closed_events(&nodes[0], &[
11075                 ExpectedCloseEvent {
11076                         channel_id: Some(channel_id_1),
11077                         discard_funding: true,
11078                         channel_funding_txo: Some(funding_txo_1),
11079                         user_channel_id: Some(42),
11080                         ..Default::default()
11081                 },
11082                 ExpectedCloseEvent {
11083                         channel_id: Some(channel_id_2),
11084                         discard_funding: true,
11085                         channel_funding_txo: Some(funding_txo_2),
11086                         user_channel_id: Some(43),
11087                         ..Default::default()
11088                 },
11089         ]);
11090
11091         // Ensure the channels don't exist anymore.
11092         assert!(nodes[0].node.list_channels().is_empty());
11093 }
11094
11095 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
11096         // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
11097         // funding and commitment transaction confirm in the same block.
11098         let chanmon_cfgs = create_chanmon_cfgs(2);
11099         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11100         let mut min_depth_1_block_cfg = test_default_channel_config();
11101         min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
11102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
11103         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11104
11105         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
11106         let chan_id = ChannelId::v1_from_funding_outpoint(chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 });
11107
11108         assert_eq!(nodes[0].node.list_channels().len(), 1);
11109         assert_eq!(nodes[1].node.list_channels().len(), 1);
11110
11111         let (closing_node, other_node) = if confirm_remote_commitment {
11112                 (&nodes[1], &nodes[0])
11113         } else {
11114                 (&nodes[0], &nodes[1])
11115         };
11116
11117         closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
11118         let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
11119         assert_eq!(msg_events.len(), 1);
11120         match msg_events.pop().unwrap() {
11121                 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
11122                 _ => panic!("Unexpected event"),
11123         }
11124         check_added_monitors(closing_node, 1);
11125         check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
11126
11127         let commitment_tx = {
11128                 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
11129                 assert_eq!(txn.len(), 1);
11130                 let commitment_tx = txn.pop().unwrap();
11131                 check_spends!(commitment_tx, funding_tx);
11132                 commitment_tx
11133         };
11134
11135         mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
11136         mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
11137
11138         check_closed_broadcast(other_node, 1, true);
11139         check_added_monitors(other_node, 1);
11140         check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
11141
11142         assert!(nodes[0].node.list_channels().is_empty());
11143         assert!(nodes[1].node.list_channels().is_empty());
11144 }
11145
11146 #[test]
11147 fn test_funding_and_commitment_tx_confirm_same_block() {
11148         do_test_funding_and_commitment_tx_confirm_same_block(false);
11149         do_test_funding_and_commitment_tx_confirm_same_block(true);
11150 }
11151
11152 #[test]
11153 fn test_accept_inbound_channel_errors_queued() {
11154         // For manually accepted inbound channels, tests that a close error is correctly handled
11155         // and the channel fails for the initiator.
11156         let mut config0 = test_default_channel_config();
11157         let mut config1 = config0.clone();
11158         config1.channel_handshake_limits.their_to_self_delay = 1000;
11159         config1.manually_accept_inbound_channels = true;
11160         config0.channel_handshake_config.our_to_self_delay = 2000;
11161
11162         let chanmon_cfgs = create_chanmon_cfgs(2);
11163         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11164         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config0), Some(config1)]);
11165         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11166
11167         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11168         let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11169
11170         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11171         let events = nodes[1].node.get_and_clear_pending_events();
11172         match events[0] {
11173                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11174                         match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23) {
11175                                 Err(APIError::ChannelUnavailable { err: _ }) => (),
11176                                 _ => panic!(),
11177                         }
11178                 }
11179                 _ => panic!("Unexpected event"),
11180         }
11181         assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11182                 open_channel_msg.common_fields.temporary_channel_id);
11183 }