Use `Default::default()` to construct `()` as a test scoring param
[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::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex, RwLock};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
65
66 #[test]
67 fn test_insane_channel_opens() {
68         // Stand up a network of 2 nodes
69         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
70         let mut cfg = UserConfig::default();
71         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
72         let chanmon_cfgs = create_chanmon_cfgs(2);
73         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
74         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
75         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
76
77         // Instantiate channel parameters where we push the maximum msats given our
78         // funding satoshis
79         let channel_value_sat = 31337; // same as funding satoshis
80         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
81         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
82
83         // Have node0 initiate a channel to node1 with aforementioned parameters
84         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
85
86         // Extract the channel open message from node0 to node1
87         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
88
89         // Test helper that asserts we get the correct error string given a mutator
90         // that supposedly makes the channel open message insane
91         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
92                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
93                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
94                 assert_eq!(msg_events.len(), 1);
95                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
96                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
97                         match action {
98                                 &ErrorAction::SendErrorMessage { .. } => {
99                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
100                                 },
101                                 _ => panic!("unexpected event!"),
102                         }
103                 } else { assert!(false); }
104         };
105
106         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
107
108         // Test all mutations that would make the channel open message insane
109         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
110         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
111
112         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
113
114         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
115
116         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
117
118         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
119
120         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
121
122         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
123
124         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 }
126
127 #[test]
128 fn test_funding_exceeds_no_wumbo_limit() {
129         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
130         // them.
131         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
132         let chanmon_cfgs = create_chanmon_cfgs(2);
133         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
134         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
135         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
136         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
137
138         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
139                 Err(APIError::APIMisuseError { err }) => {
140                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
141                 },
142                 _ => panic!()
143         }
144 }
145
146 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
147         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
148         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
149         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
150         // in normal testing, we test it explicitly here.
151         let chanmon_cfgs = create_chanmon_cfgs(2);
152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
155         let default_config = UserConfig::default();
156
157         // Have node0 initiate a channel to node1 with aforementioned parameters
158         let mut push_amt = 100_000_000;
159         let feerate_per_kw = 253;
160         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
161         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
162         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
163
164         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
165         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
166         if !send_from_initiator {
167                 open_channel_message.channel_reserve_satoshis = 0;
168                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169         }
170         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
171
172         // Extract the channel accept message from node1 to node0
173         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
174         if send_from_initiator {
175                 accept_channel_message.channel_reserve_satoshis = 0;
176                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
177         }
178         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
179         {
180                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
181                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
182                 let mut sender_node_per_peer_lock;
183                 let mut sender_node_peer_state_lock;
184
185                 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
186                 match channel_phase {
187                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
188                                 let chan_context = channel_phase.context_mut();
189                                 chan_context.holder_selected_channel_reserve_satoshis = 0;
190                                 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
191                         },
192                         ChannelPhase::Funded(_) => assert!(false),
193                 }
194         }
195
196         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
197         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
198         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
199
200         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
201         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
202         if send_from_initiator {
203                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
204                         // Note that for outbound channels we have to consider the commitment tx fee and the
205                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
206                         // well as an additional HTLC.
207                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
208         } else {
209                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
210         }
211 }
212
213 #[test]
214 fn test_counterparty_no_reserve() {
215         do_test_counterparty_no_reserve(true);
216         do_test_counterparty_no_reserve(false);
217 }
218
219 #[test]
220 fn test_async_inbound_update_fee() {
221         let chanmon_cfgs = create_chanmon_cfgs(2);
222         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
223         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
224         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
225         create_announced_chan_between_nodes(&nodes, 0, 1);
226
227         // balancing
228         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
229
230         // A                                        B
231         // update_fee                            ->
232         // send (1) commitment_signed            -.
233         //                                       <- update_add_htlc/commitment_signed
234         // send (2) RAA (awaiting remote revoke) -.
235         // (1) commitment_signed is delivered    ->
236         //                                       .- send (3) RAA (awaiting remote revoke)
237         // (2) RAA is delivered                  ->
238         //                                       .- send (4) commitment_signed
239         //                                       <- (3) RAA is delivered
240         // send (5) commitment_signed            -.
241         //                                       <- (4) commitment_signed is delivered
242         // send (6) RAA                          -.
243         // (5) commitment_signed is delivered    ->
244         //                                       <- RAA
245         // (6) RAA is delivered                  ->
246
247         // First nodes[0] generates an update_fee
248         {
249                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
250                 *feerate_lock += 20;
251         }
252         nodes[0].node.timer_tick_occurred();
253         check_added_monitors!(nodes[0], 1);
254
255         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
256         assert_eq!(events_0.len(), 1);
257         let (update_msg, commitment_signed) = match events_0[0] { // (1)
258                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
259                         (update_fee.as_ref(), commitment_signed)
260                 },
261                 _ => panic!("Unexpected event"),
262         };
263
264         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
265
266         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
267         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
268         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
269                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
270         check_added_monitors!(nodes[1], 1);
271
272         let payment_event = {
273                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
274                 assert_eq!(events_1.len(), 1);
275                 SendEvent::from_event(events_1.remove(0))
276         };
277         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
278         assert_eq!(payment_event.msgs.len(), 1);
279
280         // ...now when the messages get delivered everyone should be happy
281         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
282         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
283         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
284         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
285         check_added_monitors!(nodes[0], 1);
286
287         // deliver(1), generate (3):
288         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
289         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
290         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
291         check_added_monitors!(nodes[1], 1);
292
293         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
294         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
295         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
296         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
298         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
299         assert!(bs_update.update_fee.is_none()); // (4)
300         check_added_monitors!(nodes[1], 1);
301
302         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
303         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
304         assert!(as_update.update_add_htlcs.is_empty()); // (5)
305         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
307         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
308         assert!(as_update.update_fee.is_none()); // (5)
309         check_added_monitors!(nodes[0], 1);
310
311         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
312         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
313         // only (6) so get_event_msg's assert(len == 1) passes
314         check_added_monitors!(nodes[0], 1);
315
316         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
317         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
318         check_added_monitors!(nodes[1], 1);
319
320         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
321         check_added_monitors!(nodes[0], 1);
322
323         let events_2 = nodes[0].node.get_and_clear_pending_events();
324         assert_eq!(events_2.len(), 1);
325         match events_2[0] {
326                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
327                 _ => panic!("Unexpected event"),
328         }
329
330         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
331         check_added_monitors!(nodes[1], 1);
332 }
333
334 #[test]
335 fn test_update_fee_unordered_raa() {
336         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
337         // crash in an earlier version of the update_fee patch)
338         let chanmon_cfgs = create_chanmon_cfgs(2);
339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
342         create_announced_chan_between_nodes(&nodes, 0, 1);
343
344         // balancing
345         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
346
347         // First nodes[0] generates an update_fee
348         {
349                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
350                 *feerate_lock += 20;
351         }
352         nodes[0].node.timer_tick_occurred();
353         check_added_monitors!(nodes[0], 1);
354
355         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
356         assert_eq!(events_0.len(), 1);
357         let update_msg = match events_0[0] { // (1)
358                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
359                         update_fee.as_ref()
360                 },
361                 _ => panic!("Unexpected event"),
362         };
363
364         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
365
366         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
367         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
368         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
369                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
370         check_added_monitors!(nodes[1], 1);
371
372         let payment_event = {
373                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
374                 assert_eq!(events_1.len(), 1);
375                 SendEvent::from_event(events_1.remove(0))
376         };
377         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
378         assert_eq!(payment_event.msgs.len(), 1);
379
380         // ...now when the messages get delivered everyone should be happy
381         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
382         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
383         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
384         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
385         check_added_monitors!(nodes[0], 1);
386
387         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
388         check_added_monitors!(nodes[1], 1);
389
390         // We can't continue, sadly, because our (1) now has a bogus signature
391 }
392
393 #[test]
394 fn test_multi_flight_update_fee() {
395         let chanmon_cfgs = create_chanmon_cfgs(2);
396         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
397         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
398         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
399         create_announced_chan_between_nodes(&nodes, 0, 1);
400
401         // A                                        B
402         // update_fee/commitment_signed          ->
403         //                                       .- send (1) RAA and (2) commitment_signed
404         // update_fee (never committed)          ->
405         // (3) update_fee                        ->
406         // We have to manually generate the above update_fee, it is allowed by the protocol but we
407         // don't track which updates correspond to which revoke_and_ack responses so we're in
408         // AwaitingRAA mode and will not generate the update_fee yet.
409         //                                       <- (1) RAA delivered
410         // (3) is generated and send (4) CS      -.
411         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
412         // know the per_commitment_point to use for it.
413         //                                       <- (2) commitment_signed delivered
414         // revoke_and_ack                        ->
415         //                                          B should send no response here
416         // (4) commitment_signed delivered       ->
417         //                                       <- RAA/commitment_signed delivered
418         // revoke_and_ack                        ->
419
420         // First nodes[0] generates an update_fee
421         let initial_feerate;
422         {
423                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
424                 initial_feerate = *feerate_lock;
425                 *feerate_lock = initial_feerate + 20;
426         }
427         nodes[0].node.timer_tick_occurred();
428         check_added_monitors!(nodes[0], 1);
429
430         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
431         assert_eq!(events_0.len(), 1);
432         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
433                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
434                         (update_fee.as_ref().unwrap(), commitment_signed)
435                 },
436                 _ => panic!("Unexpected event"),
437         };
438
439         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
440         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
441         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
442         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
443         check_added_monitors!(nodes[1], 1);
444
445         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
446         // transaction:
447         {
448                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
449                 *feerate_lock = initial_feerate + 40;
450         }
451         nodes[0].node.timer_tick_occurred();
452         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
453         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
454
455         // Create the (3) update_fee message that nodes[0] will generate before it does...
456         let mut update_msg_2 = msgs::UpdateFee {
457                 channel_id: update_msg_1.channel_id.clone(),
458                 feerate_per_kw: (initial_feerate + 30) as u32,
459         };
460
461         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
462
463         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
464         // Deliver (3)
465         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
466
467         // Deliver (1), generating (3) and (4)
468         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
469         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
470         check_added_monitors!(nodes[0], 1);
471         assert!(as_second_update.update_add_htlcs.is_empty());
472         assert!(as_second_update.update_fulfill_htlcs.is_empty());
473         assert!(as_second_update.update_fail_htlcs.is_empty());
474         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
475         // Check that the update_fee newly generated matches what we delivered:
476         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
477         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
478
479         // Deliver (2) commitment_signed
480         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
481         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
482         check_added_monitors!(nodes[0], 1);
483         // No commitment_signed so get_event_msg's assert(len == 1) passes
484
485         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
486         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
487         check_added_monitors!(nodes[1], 1);
488
489         // Delever (4)
490         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
491         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
492         check_added_monitors!(nodes[1], 1);
493
494         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
495         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
496         check_added_monitors!(nodes[0], 1);
497
498         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
499         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
500         // No commitment_signed so get_event_msg's assert(len == 1) passes
501         check_added_monitors!(nodes[0], 1);
502
503         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
504         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
505         check_added_monitors!(nodes[1], 1);
506 }
507
508 fn do_test_sanity_on_in_flight_opens(steps: u8) {
509         // Previously, we had issues deserializing channels when we hadn't connected the first block
510         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
511         // serialization round-trips and simply do steps towards opening a channel and then drop the
512         // Node objects.
513
514         let chanmon_cfgs = create_chanmon_cfgs(2);
515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
517         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
518
519         if steps & 0b1000_0000 != 0{
520                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
521                 connect_block(&nodes[0], &block);
522                 connect_block(&nodes[1], &block);
523         }
524
525         if steps & 0x0f == 0 { return; }
526         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
527         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
528
529         if steps & 0x0f == 1 { return; }
530         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
531         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
532
533         if steps & 0x0f == 2 { return; }
534         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
535
536         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
537
538         if steps & 0x0f == 3 { return; }
539         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
540         check_added_monitors!(nodes[0], 0);
541         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
542
543         if steps & 0x0f == 4 { return; }
544         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
545         {
546                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
547                 assert_eq!(added_monitors.len(), 1);
548                 assert_eq!(added_monitors[0].0, funding_output);
549                 added_monitors.clear();
550         }
551         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
552
553         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
554
555         if steps & 0x0f == 5 { return; }
556         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
557         {
558                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
559                 assert_eq!(added_monitors.len(), 1);
560                 assert_eq!(added_monitors[0].0, funding_output);
561                 added_monitors.clear();
562         }
563
564         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
565         let events_4 = nodes[0].node.get_and_clear_pending_events();
566         assert_eq!(events_4.len(), 0);
567
568         if steps & 0x0f == 6 { return; }
569         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
570
571         if steps & 0x0f == 7 { return; }
572         confirm_transaction_at(&nodes[0], &tx, 2);
573         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
574         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
575         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
576 }
577
578 #[test]
579 fn test_sanity_on_in_flight_opens() {
580         do_test_sanity_on_in_flight_opens(0);
581         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
582         do_test_sanity_on_in_flight_opens(1);
583         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
584         do_test_sanity_on_in_flight_opens(2);
585         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
586         do_test_sanity_on_in_flight_opens(3);
587         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
588         do_test_sanity_on_in_flight_opens(4);
589         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
590         do_test_sanity_on_in_flight_opens(5);
591         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
592         do_test_sanity_on_in_flight_opens(6);
593         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
594         do_test_sanity_on_in_flight_opens(7);
595         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
596         do_test_sanity_on_in_flight_opens(8);
597         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
598 }
599
600 #[test]
601 fn test_update_fee_vanilla() {
602         let chanmon_cfgs = create_chanmon_cfgs(2);
603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
606         create_announced_chan_between_nodes(&nodes, 0, 1);
607
608         {
609                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
610                 *feerate_lock += 25;
611         }
612         nodes[0].node.timer_tick_occurred();
613         check_added_monitors!(nodes[0], 1);
614
615         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
616         assert_eq!(events_0.len(), 1);
617         let (update_msg, commitment_signed) = match events_0[0] {
618                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
619                         (update_fee.as_ref(), commitment_signed)
620                 },
621                 _ => panic!("Unexpected event"),
622         };
623         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
624
625         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
626         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
627         check_added_monitors!(nodes[1], 1);
628
629         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
630         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
631         check_added_monitors!(nodes[0], 1);
632
633         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
634         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
635         // No commitment_signed so get_event_msg's assert(len == 1) passes
636         check_added_monitors!(nodes[0], 1);
637
638         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
639         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
640         check_added_monitors!(nodes[1], 1);
641 }
642
643 #[test]
644 fn test_update_fee_that_funder_cannot_afford() {
645         let chanmon_cfgs = create_chanmon_cfgs(2);
646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
648         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
649         let channel_value = 5000;
650         let push_sats = 700;
651         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
652         let channel_id = chan.2;
653         let secp_ctx = Secp256k1::new();
654         let default_config = UserConfig::default();
655         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
656
657         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
658
659         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
660         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
661         // calculate two different feerates here - the expected local limit as well as the expected
662         // remote limit.
663         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(&channel_type_features) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
664         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
665         {
666                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
667                 *feerate_lock = feerate;
668         }
669         nodes[0].node.timer_tick_occurred();
670         check_added_monitors!(nodes[0], 1);
671         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
672
673         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
674
675         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
676
677         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
678         {
679                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
680
681                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
682                 assert_eq!(commitment_tx.output.len(), 2);
683                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
684                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
685                 actual_fee = channel_value - actual_fee;
686                 assert_eq!(total_fee, actual_fee);
687         }
688
689         {
690                 // Increment the feerate by a small constant, accounting for rounding errors
691                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
692                 *feerate_lock += 4;
693         }
694         nodes[0].node.timer_tick_occurred();
695         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
696         check_added_monitors!(nodes[0], 0);
697
698         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
699
700         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
701         // needed to sign the new commitment tx and (2) sign the new commitment tx.
702         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
703                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
704                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
705                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
706                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
707                 ).flatten().unwrap();
708                 let chan_signer = local_chan.get_signer();
709                 let pubkeys = chan_signer.as_ref().pubkeys();
710                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
711                  pubkeys.funding_pubkey)
712         };
713         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
714                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
715                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
716                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
717                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
718                 ).flatten().unwrap();
719                 let chan_signer = remote_chan.get_signer();
720                 let pubkeys = chan_signer.as_ref().pubkeys();
721                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
722                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
723                  pubkeys.funding_pubkey)
724         };
725
726         // Assemble the set of keys we can use for signatures for our commitment_signed message.
727         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
728                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
729
730         let res = {
731                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
732                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
733                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
734                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
735                 ).flatten().unwrap();
736                 let local_chan_signer = local_chan.get_signer();
737                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
738                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
739                         INITIAL_COMMITMENT_NUMBER - 1,
740                         push_sats,
741                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
742                         local_funding, remote_funding,
743                         commit_tx_keys.clone(),
744                         non_buffer_feerate + 4,
745                         &mut htlcs,
746                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
747                 );
748                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
749         };
750
751         let commit_signed_msg = msgs::CommitmentSigned {
752                 channel_id: chan.2,
753                 signature: res.0,
754                 htlc_signatures: res.1,
755                 #[cfg(taproot)]
756                 partial_signature_with_nonce: None,
757         };
758
759         let update_fee = msgs::UpdateFee {
760                 channel_id: chan.2,
761                 feerate_per_kw: non_buffer_feerate + 4,
762         };
763
764         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
765
766         //While producing the commitment_signed response after handling a received update_fee request the
767         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
768         //Should produce and error.
769         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
770         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
771         check_added_monitors!(nodes[1], 1);
772         check_closed_broadcast!(nodes[1], true);
773         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
774                 [nodes[0].node.get_our_node_id()], channel_value);
775 }
776
777 #[test]
778 fn test_update_fee_with_fundee_update_add_htlc() {
779         let chanmon_cfgs = create_chanmon_cfgs(2);
780         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
781         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
782         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
783         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
784
785         // balancing
786         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
787
788         {
789                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
790                 *feerate_lock += 20;
791         }
792         nodes[0].node.timer_tick_occurred();
793         check_added_monitors!(nodes[0], 1);
794
795         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
796         assert_eq!(events_0.len(), 1);
797         let (update_msg, commitment_signed) = match events_0[0] {
798                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
799                         (update_fee.as_ref(), commitment_signed)
800                 },
801                 _ => panic!("Unexpected event"),
802         };
803         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
804         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
805         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
806         check_added_monitors!(nodes[1], 1);
807
808         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
809
810         // nothing happens since node[1] is in AwaitingRemoteRevoke
811         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
812                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
813         {
814                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
815                 assert_eq!(added_monitors.len(), 0);
816                 added_monitors.clear();
817         }
818         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
819         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
820         // node[1] has nothing to do
821
822         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
823         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
824         check_added_monitors!(nodes[0], 1);
825
826         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
827         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
828         // No commitment_signed so get_event_msg's assert(len == 1) passes
829         check_added_monitors!(nodes[0], 1);
830         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
831         check_added_monitors!(nodes[1], 1);
832         // AwaitingRemoteRevoke ends here
833
834         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
835         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
836         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
837         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
838         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
839         assert_eq!(commitment_update.update_fee.is_none(), true);
840
841         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
842         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
843         check_added_monitors!(nodes[0], 1);
844         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
845
846         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
847         check_added_monitors!(nodes[1], 1);
848         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
849
850         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
851         check_added_monitors!(nodes[1], 1);
852         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
853         // No commitment_signed so get_event_msg's assert(len == 1) passes
854
855         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
856         check_added_monitors!(nodes[0], 1);
857         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
858
859         expect_pending_htlcs_forwardable!(nodes[0]);
860
861         let events = nodes[0].node.get_and_clear_pending_events();
862         assert_eq!(events.len(), 1);
863         match events[0] {
864                 Event::PaymentClaimable { .. } => { },
865                 _ => panic!("Unexpected event"),
866         };
867
868         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
869
870         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
871         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
872         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
873         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
874         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
875 }
876
877 #[test]
878 fn test_update_fee() {
879         let chanmon_cfgs = create_chanmon_cfgs(2);
880         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
881         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
882         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
883         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
884         let channel_id = chan.2;
885
886         // A                                        B
887         // (1) update_fee/commitment_signed      ->
888         //                                       <- (2) revoke_and_ack
889         //                                       .- send (3) commitment_signed
890         // (4) update_fee/commitment_signed      ->
891         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
892         //                                       <- (3) commitment_signed delivered
893         // send (6) revoke_and_ack               -.
894         //                                       <- (5) deliver revoke_and_ack
895         // (6) deliver revoke_and_ack            ->
896         //                                       .- send (7) commitment_signed in response to (4)
897         //                                       <- (7) deliver commitment_signed
898         // revoke_and_ack                        ->
899
900         // Create and deliver (1)...
901         let feerate;
902         {
903                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
904                 feerate = *feerate_lock;
905                 *feerate_lock = feerate + 20;
906         }
907         nodes[0].node.timer_tick_occurred();
908         check_added_monitors!(nodes[0], 1);
909
910         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
911         assert_eq!(events_0.len(), 1);
912         let (update_msg, commitment_signed) = match events_0[0] {
913                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
914                         (update_fee.as_ref(), commitment_signed)
915                 },
916                 _ => panic!("Unexpected event"),
917         };
918         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
919
920         // Generate (2) and (3):
921         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
922         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
923         check_added_monitors!(nodes[1], 1);
924
925         // Deliver (2):
926         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
927         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
928         check_added_monitors!(nodes[0], 1);
929
930         // Create and deliver (4)...
931         {
932                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
933                 *feerate_lock = feerate + 30;
934         }
935         nodes[0].node.timer_tick_occurred();
936         check_added_monitors!(nodes[0], 1);
937         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
938         assert_eq!(events_0.len(), 1);
939         let (update_msg, commitment_signed) = match events_0[0] {
940                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
941                         (update_fee.as_ref(), commitment_signed)
942                 },
943                 _ => panic!("Unexpected event"),
944         };
945
946         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
947         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
948         check_added_monitors!(nodes[1], 1);
949         // ... creating (5)
950         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
951         // No commitment_signed so get_event_msg's assert(len == 1) passes
952
953         // Handle (3), creating (6):
954         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
955         check_added_monitors!(nodes[0], 1);
956         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
957         // No commitment_signed so get_event_msg's assert(len == 1) passes
958
959         // Deliver (5):
960         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
961         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
962         check_added_monitors!(nodes[0], 1);
963
964         // Deliver (6), creating (7):
965         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
966         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
967         assert!(commitment_update.update_add_htlcs.is_empty());
968         assert!(commitment_update.update_fulfill_htlcs.is_empty());
969         assert!(commitment_update.update_fail_htlcs.is_empty());
970         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
971         assert!(commitment_update.update_fee.is_none());
972         check_added_monitors!(nodes[1], 1);
973
974         // Deliver (7)
975         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
976         check_added_monitors!(nodes[0], 1);
977         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
978         // No commitment_signed so get_event_msg's assert(len == 1) passes
979
980         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
981         check_added_monitors!(nodes[1], 1);
982         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
983
984         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
985         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
986         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
987         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
988         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
989 }
990
991 #[test]
992 fn fake_network_test() {
993         // Simple test which builds a network of ChannelManagers, connects them to each other, and
994         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
995         let chanmon_cfgs = create_chanmon_cfgs(4);
996         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
997         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
998         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
999
1000         // Create some initial channels
1001         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1002         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1003         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1004
1005         // Rebalance the network a bit by relaying one payment through all the channels...
1006         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1008         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1009         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1010
1011         // Send some more payments
1012         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1013         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1014         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1015
1016         // Test failure packets
1017         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1018         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1019
1020         // Add a new channel that skips 3
1021         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1022
1023         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1024         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1025         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1026         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1027         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1028         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1029         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1030
1031         // Do some rebalance loop payments, simultaneously
1032         let mut hops = Vec::with_capacity(3);
1033         hops.push(RouteHop {
1034                 pubkey: nodes[2].node.get_our_node_id(),
1035                 node_features: NodeFeatures::empty(),
1036                 short_channel_id: chan_2.0.contents.short_channel_id,
1037                 channel_features: ChannelFeatures::empty(),
1038                 fee_msat: 0,
1039                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1040                 maybe_announced_channel: true,
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[3].node.get_our_node_id(),
1044                 node_features: NodeFeatures::empty(),
1045                 short_channel_id: chan_3.0.contents.short_channel_id,
1046                 channel_features: ChannelFeatures::empty(),
1047                 fee_msat: 0,
1048                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1049                 maybe_announced_channel: true,
1050         });
1051         hops.push(RouteHop {
1052                 pubkey: nodes[1].node.get_our_node_id(),
1053                 node_features: nodes[1].node.node_features(),
1054                 short_channel_id: chan_4.0.contents.short_channel_id,
1055                 channel_features: nodes[1].node.channel_features(),
1056                 fee_msat: 1000000,
1057                 cltv_expiry_delta: TEST_FINAL_CLTV,
1058                 maybe_announced_channel: true,
1059         });
1060         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1061         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1062         let payment_preimage_1 = send_along_route(&nodes[1],
1063                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1064                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1065
1066         let mut hops = Vec::with_capacity(3);
1067         hops.push(RouteHop {
1068                 pubkey: nodes[3].node.get_our_node_id(),
1069                 node_features: NodeFeatures::empty(),
1070                 short_channel_id: chan_4.0.contents.short_channel_id,
1071                 channel_features: ChannelFeatures::empty(),
1072                 fee_msat: 0,
1073                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1074                 maybe_announced_channel: true,
1075         });
1076         hops.push(RouteHop {
1077                 pubkey: nodes[2].node.get_our_node_id(),
1078                 node_features: NodeFeatures::empty(),
1079                 short_channel_id: chan_3.0.contents.short_channel_id,
1080                 channel_features: ChannelFeatures::empty(),
1081                 fee_msat: 0,
1082                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1083                 maybe_announced_channel: true,
1084         });
1085         hops.push(RouteHop {
1086                 pubkey: nodes[1].node.get_our_node_id(),
1087                 node_features: nodes[1].node.node_features(),
1088                 short_channel_id: chan_2.0.contents.short_channel_id,
1089                 channel_features: nodes[1].node.channel_features(),
1090                 fee_msat: 1000000,
1091                 cltv_expiry_delta: TEST_FINAL_CLTV,
1092                 maybe_announced_channel: true,
1093         });
1094         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1095         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1096         let payment_hash_2 = send_along_route(&nodes[1],
1097                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1098                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1099
1100         // Claim the rebalances...
1101         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1102         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1103
1104         // Close down the channels...
1105         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1106         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1107         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1108         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1109         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1110         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1111         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1112         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1113         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1114         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1115         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1116         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1117 }
1118
1119 #[test]
1120 fn holding_cell_htlc_counting() {
1121         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1122         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1123         // commitment dance rounds.
1124         let chanmon_cfgs = create_chanmon_cfgs(3);
1125         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1126         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1127         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1128         create_announced_chan_between_nodes(&nodes, 0, 1);
1129         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1130
1131         // Fetch a route in advance as we will be unable to once we're unable to send.
1132         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1133
1134         let mut payments = Vec::new();
1135         for _ in 0..50 {
1136                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1137                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1138                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1139                 payments.push((payment_preimage, payment_hash));
1140         }
1141         check_added_monitors!(nodes[1], 1);
1142
1143         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1144         assert_eq!(events.len(), 1);
1145         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1146         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1147
1148         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1149         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1150         // another HTLC.
1151         {
1152                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1153                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1154                         ), true, APIError::ChannelUnavailable { .. }, {});
1155                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1156         }
1157
1158         // This should also be true if we try to forward a payment.
1159         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1160         {
1161                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1162                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1163                 check_added_monitors!(nodes[0], 1);
1164         }
1165
1166         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1167         assert_eq!(events.len(), 1);
1168         let payment_event = SendEvent::from_event(events.pop().unwrap());
1169         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1170
1171         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1172         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1173         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1174         // fails), the second will process the resulting failure and fail the HTLC backward.
1175         expect_pending_htlcs_forwardable!(nodes[1]);
1176         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1177         check_added_monitors!(nodes[1], 1);
1178
1179         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1180         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1181         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1182
1183         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1184
1185         // Now forward all the pending HTLCs and claim them back
1186         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1187         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1188         check_added_monitors!(nodes[2], 1);
1189
1190         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1191         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1192         check_added_monitors!(nodes[1], 1);
1193         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1194
1195         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1196         check_added_monitors!(nodes[1], 1);
1197         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1198
1199         for ref update in as_updates.update_add_htlcs.iter() {
1200                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1201         }
1202         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1203         check_added_monitors!(nodes[2], 1);
1204         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1205         check_added_monitors!(nodes[2], 1);
1206         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1207
1208         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1209         check_added_monitors!(nodes[1], 1);
1210         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1211         check_added_monitors!(nodes[1], 1);
1212         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1213
1214         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1215         check_added_monitors!(nodes[2], 1);
1216
1217         expect_pending_htlcs_forwardable!(nodes[2]);
1218
1219         let events = nodes[2].node.get_and_clear_pending_events();
1220         assert_eq!(events.len(), payments.len());
1221         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1222                 match event {
1223                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1224                                 assert_eq!(*payment_hash, *hash);
1225                         },
1226                         _ => panic!("Unexpected event"),
1227                 };
1228         }
1229
1230         for (preimage, _) in payments.drain(..) {
1231                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1232         }
1233
1234         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1235 }
1236
1237 #[test]
1238 fn duplicate_htlc_test() {
1239         // Test that we accept duplicate payment_hash HTLCs across the network and that
1240         // claiming/failing them are all separate and don't affect each other
1241         let chanmon_cfgs = create_chanmon_cfgs(6);
1242         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1243         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1244         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1245
1246         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1247         create_announced_chan_between_nodes(&nodes, 0, 3);
1248         create_announced_chan_between_nodes(&nodes, 1, 3);
1249         create_announced_chan_between_nodes(&nodes, 2, 3);
1250         create_announced_chan_between_nodes(&nodes, 3, 4);
1251         create_announced_chan_between_nodes(&nodes, 3, 5);
1252
1253         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1254
1255         *nodes[0].network_payment_count.borrow_mut() -= 1;
1256         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1257
1258         *nodes[0].network_payment_count.borrow_mut() -= 1;
1259         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1260
1261         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1262         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1263         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1264 }
1265
1266 #[test]
1267 fn test_duplicate_htlc_different_direction_onchain() {
1268         // Test that ChannelMonitor doesn't generate 2 preimage txn
1269         // when we have 2 HTLCs with same preimage that go across a node
1270         // in opposite directions, even with the same payment secret.
1271         let chanmon_cfgs = create_chanmon_cfgs(2);
1272         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1273         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1274         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1275
1276         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1277
1278         // balancing
1279         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1280
1281         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1282
1283         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1284         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1285         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1286
1287         // Provide preimage to node 0 by claiming payment
1288         nodes[0].node.claim_funds(payment_preimage);
1289         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1290         check_added_monitors!(nodes[0], 1);
1291
1292         // Broadcast node 1 commitment txn
1293         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1294
1295         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1296         let mut has_both_htlcs = 0; // check htlcs match ones committed
1297         for outp in remote_txn[0].output.iter() {
1298                 if outp.value == 800_000 / 1000 {
1299                         has_both_htlcs += 1;
1300                 } else if outp.value == 900_000 / 1000 {
1301                         has_both_htlcs += 1;
1302                 }
1303         }
1304         assert_eq!(has_both_htlcs, 2);
1305
1306         mine_transaction(&nodes[0], &remote_txn[0]);
1307         check_added_monitors!(nodes[0], 1);
1308         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1309         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1310
1311         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1312         assert_eq!(claim_txn.len(), 3);
1313
1314         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1315         check_spends!(claim_txn[1], remote_txn[0]);
1316         check_spends!(claim_txn[2], remote_txn[0]);
1317         let preimage_tx = &claim_txn[0];
1318         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1319                 (&claim_txn[1], &claim_txn[2])
1320         } else {
1321                 (&claim_txn[2], &claim_txn[1])
1322         };
1323
1324         assert_eq!(preimage_tx.input.len(), 1);
1325         assert_eq!(preimage_bump_tx.input.len(), 1);
1326
1327         assert_eq!(preimage_tx.input.len(), 1);
1328         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1329         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1330
1331         assert_eq!(timeout_tx.input.len(), 1);
1332         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1333         check_spends!(timeout_tx, remote_txn[0]);
1334         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1335
1336         let events = nodes[0].node.get_and_clear_pending_msg_events();
1337         assert_eq!(events.len(), 3);
1338         for e in events {
1339                 match e {
1340                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1341                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1342                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1343                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1344                         },
1345                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1346                                 assert!(update_add_htlcs.is_empty());
1347                                 assert!(update_fail_htlcs.is_empty());
1348                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1349                                 assert!(update_fail_malformed_htlcs.is_empty());
1350                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1351                         },
1352                         _ => panic!("Unexpected event"),
1353                 }
1354         }
1355 }
1356
1357 #[test]
1358 fn test_basic_channel_reserve() {
1359         let chanmon_cfgs = create_chanmon_cfgs(2);
1360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1362         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1363         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1364
1365         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1366         let channel_reserve = chan_stat.channel_reserve_msat;
1367
1368         // The 2* and +1 are for the fee spike reserve.
1369         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, &get_channel_type_features!(nodes[0], nodes[1], chan.2));
1370         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1371         let (mut route, our_payment_hash, _, our_payment_secret) =
1372                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1373         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1374         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1375                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1376         match err {
1377                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1378                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1379                         else { panic!("Unexpected error variant"); }
1380                 },
1381                 _ => panic!("Unexpected error variant"),
1382         }
1383         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1384
1385         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1386 }
1387
1388 #[test]
1389 fn test_fee_spike_violation_fails_htlc() {
1390         let chanmon_cfgs = create_chanmon_cfgs(2);
1391         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1392         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1393         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1394         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1395
1396         let (mut route, payment_hash, _, payment_secret) =
1397                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1398         route.paths[0].hops[0].fee_msat += 1;
1399         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1400         let secp_ctx = Secp256k1::new();
1401         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1402
1403         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1404
1405         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1406         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1407                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1408         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1409         let msg = msgs::UpdateAddHTLC {
1410                 channel_id: chan.2,
1411                 htlc_id: 0,
1412                 amount_msat: htlc_msat,
1413                 payment_hash: payment_hash,
1414                 cltv_expiry: htlc_cltv,
1415                 onion_routing_packet: onion_packet,
1416                 skimmed_fee_msat: None,
1417         };
1418
1419         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1420
1421         // Now manually create the commitment_signed message corresponding to the update_add
1422         // nodes[0] just sent. In the code for construction of this message, "local" refers
1423         // to the sender of the message, and "remote" refers to the receiver.
1424
1425         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1426
1427         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1428
1429         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1430         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1431         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1432                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1433                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1434                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1435                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1436                 ).flatten().unwrap();
1437                 let chan_signer = local_chan.get_signer();
1438                 // Make the signer believe we validated another commitment, so we can release the secret
1439                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1440
1441                 let pubkeys = chan_signer.as_ref().pubkeys();
1442                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1443                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1444                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1445                  chan_signer.as_ref().pubkeys().funding_pubkey)
1446         };
1447         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1448                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1449                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1450                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1451                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1452                 ).flatten().unwrap();
1453                 let chan_signer = remote_chan.get_signer();
1454                 let pubkeys = chan_signer.as_ref().pubkeys();
1455                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1456                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1457                  chan_signer.as_ref().pubkeys().funding_pubkey)
1458         };
1459
1460         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1461         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1462                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1463
1464         // Build the remote commitment transaction so we can sign it, and then later use the
1465         // signature for the commitment_signed message.
1466         let local_chan_balance = 1313;
1467
1468         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1469                 offered: false,
1470                 amount_msat: 3460001,
1471                 cltv_expiry: htlc_cltv,
1472                 payment_hash,
1473                 transaction_output_index: Some(1),
1474         };
1475
1476         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1477
1478         let res = {
1479                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1480                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1481                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1482                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1483                 ).flatten().unwrap();
1484                 let local_chan_signer = local_chan.get_signer();
1485                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1486                         commitment_number,
1487                         95000,
1488                         local_chan_balance,
1489                         local_funding, remote_funding,
1490                         commit_tx_keys.clone(),
1491                         feerate_per_kw,
1492                         &mut vec![(accepted_htlc_info, ())],
1493                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1494                 );
1495                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1496         };
1497
1498         let commit_signed_msg = msgs::CommitmentSigned {
1499                 channel_id: chan.2,
1500                 signature: res.0,
1501                 htlc_signatures: res.1,
1502                 #[cfg(taproot)]
1503                 partial_signature_with_nonce: None,
1504         };
1505
1506         // Send the commitment_signed message to the nodes[1].
1507         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1508         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1509
1510         // Send the RAA to nodes[1].
1511         let raa_msg = msgs::RevokeAndACK {
1512                 channel_id: chan.2,
1513                 per_commitment_secret: local_secret,
1514                 next_per_commitment_point: next_local_point,
1515                 #[cfg(taproot)]
1516                 next_local_nonce: None,
1517         };
1518         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1519
1520         let events = nodes[1].node.get_and_clear_pending_msg_events();
1521         assert_eq!(events.len(), 1);
1522         // Make sure the HTLC failed in the way we expect.
1523         match events[0] {
1524                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1525                         assert_eq!(update_fail_htlcs.len(), 1);
1526                         update_fail_htlcs[0].clone()
1527                 },
1528                 _ => panic!("Unexpected event"),
1529         };
1530         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1531                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1532
1533         check_added_monitors!(nodes[1], 2);
1534 }
1535
1536 #[test]
1537 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1538         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1539         // Set the fee rate for the channel very high, to the point where the fundee
1540         // sending any above-dust amount would result in a channel reserve violation.
1541         // In this test we check that we would be prevented from sending an HTLC in
1542         // this situation.
1543         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1544         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1545         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1546         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1547         let default_config = UserConfig::default();
1548         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1549
1550         let mut push_amt = 100_000_000;
1551         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1552
1553         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1554
1555         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1556
1557         // Fetch a route in advance as we will be unable to once we're unable to send.
1558         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1559         // Sending exactly enough to hit the reserve amount should be accepted
1560         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1561                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1562         }
1563
1564         // However one more HTLC should be significantly over the reserve amount and fail.
1565         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1566                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1567                 ), true, APIError::ChannelUnavailable { .. }, {});
1568         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1569 }
1570
1571 #[test]
1572 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1573         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1574         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1577         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1578         let default_config = UserConfig::default();
1579         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1580
1581         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1582         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1583         // transaction fee with 0 HTLCs (183 sats)).
1584         let mut push_amt = 100_000_000;
1585         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1586         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1587         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1588
1589         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1590         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1591                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1592         }
1593
1594         let (mut route, payment_hash, _, payment_secret) =
1595                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1596         route.paths[0].hops[0].fee_msat = 700_000;
1597         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1598         let secp_ctx = Secp256k1::new();
1599         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1600         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1601         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1602         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1603                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1604         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1605         let msg = msgs::UpdateAddHTLC {
1606                 channel_id: chan.2,
1607                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1608                 amount_msat: htlc_msat,
1609                 payment_hash: payment_hash,
1610                 cltv_expiry: htlc_cltv,
1611                 onion_routing_packet: onion_packet,
1612                 skimmed_fee_msat: None,
1613         };
1614
1615         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1616         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1617         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1618         assert_eq!(nodes[0].node.list_channels().len(), 0);
1619         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1620         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1621         check_added_monitors!(nodes[0], 1);
1622         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() },
1623                 [nodes[1].node.get_our_node_id()], 100000);
1624 }
1625
1626 #[test]
1627 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1628         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1629         // calculating our commitment transaction fee (this was previously broken).
1630         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1631         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1632
1633         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1634         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1635         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1636         let default_config = UserConfig::default();
1637         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1638
1639         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1640         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1641         // transaction fee with 0 HTLCs (183 sats)).
1642         let mut push_amt = 100_000_000;
1643         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1644         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1645         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1646
1647         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1648                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1649         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1650         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1651         // commitment transaction fee.
1652         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1653
1654         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1655         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1656                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1657         }
1658
1659         // One more than the dust amt should fail, however.
1660         let (mut route, our_payment_hash, _, our_payment_secret) =
1661                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1662         route.paths[0].hops[0].fee_msat += 1;
1663         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1664                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1665                 ), true, APIError::ChannelUnavailable { .. }, {});
1666 }
1667
1668 #[test]
1669 fn test_chan_init_feerate_unaffordability() {
1670         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1671         // channel reserve and feerate requirements.
1672         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1673         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1676         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1677         let default_config = UserConfig::default();
1678         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1679
1680         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1681         // HTLC.
1682         let mut push_amt = 100_000_000;
1683         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1684         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1685                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1686
1687         // During open, we don't have a "counterparty channel reserve" to check against, so that
1688         // requirement only comes into play on the open_channel handling side.
1689         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1690         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1691         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1692         open_channel_msg.push_msat += 1;
1693         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1694
1695         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1696         assert_eq!(msg_events.len(), 1);
1697         match msg_events[0] {
1698                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1699                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1700                 },
1701                 _ => panic!("Unexpected event"),
1702         }
1703 }
1704
1705 #[test]
1706 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1707         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1708         // calculating our counterparty's commitment transaction fee (this was previously broken).
1709         let chanmon_cfgs = create_chanmon_cfgs(2);
1710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1712         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1713         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1714
1715         let payment_amt = 46000; // Dust amount
1716         // In the previous code, these first four payments would succeed.
1717         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1718         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1719         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1720         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721
1722         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1723         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1724         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1725         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1726         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1728
1729         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1730         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1731         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1732         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1733 }
1734
1735 #[test]
1736 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1737         let chanmon_cfgs = create_chanmon_cfgs(3);
1738         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1739         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1740         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1741         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1742         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1743
1744         let feemsat = 239;
1745         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1746         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1747         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1748         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1749
1750         // Add a 2* and +1 for the fee spike reserve.
1751         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1752         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1753         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1754
1755         // Add a pending HTLC.
1756         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1757         let payment_event_1 = {
1758                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1759                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1760                 check_added_monitors!(nodes[0], 1);
1761
1762                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1763                 assert_eq!(events.len(), 1);
1764                 SendEvent::from_event(events.remove(0))
1765         };
1766         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1767
1768         // Attempt to trigger a channel reserve violation --> payment failure.
1769         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1770         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1771         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1772         let mut route_2 = route_1.clone();
1773         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1774
1775         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1776         let secp_ctx = Secp256k1::new();
1777         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1778         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1779         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1780         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1781                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1782         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1783         let msg = msgs::UpdateAddHTLC {
1784                 channel_id: chan.2,
1785                 htlc_id: 1,
1786                 amount_msat: htlc_msat + 1,
1787                 payment_hash: our_payment_hash_1,
1788                 cltv_expiry: htlc_cltv,
1789                 onion_routing_packet: onion_packet,
1790                 skimmed_fee_msat: None,
1791         };
1792
1793         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1794         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1795         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1796         assert_eq!(nodes[1].node.list_channels().len(), 1);
1797         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1798         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1799         check_added_monitors!(nodes[1], 1);
1800         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1801                 [nodes[0].node.get_our_node_id()], 100000);
1802 }
1803
1804 #[test]
1805 fn test_inbound_outbound_capacity_is_not_zero() {
1806         let chanmon_cfgs = create_chanmon_cfgs(2);
1807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1809         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1810         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1811         let channels0 = node_chanmgrs[0].list_channels();
1812         let channels1 = node_chanmgrs[1].list_channels();
1813         let default_config = UserConfig::default();
1814         assert_eq!(channels0.len(), 1);
1815         assert_eq!(channels1.len(), 1);
1816
1817         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1818         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1819         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1820
1821         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1822         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1823 }
1824
1825 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1826         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1827 }
1828
1829 #[test]
1830 fn test_channel_reserve_holding_cell_htlcs() {
1831         let chanmon_cfgs = create_chanmon_cfgs(3);
1832         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1833         // When this test was written, the default base fee floated based on the HTLC count.
1834         // It is now fixed, so we simply set the fee to the expected value here.
1835         let mut config = test_default_channel_config();
1836         config.channel_config.forwarding_fee_base_msat = 239;
1837         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1838         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1839         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1840         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1841
1842         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1843         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1844
1845         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1846         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1847
1848         macro_rules! expect_forward {
1849                 ($node: expr) => {{
1850                         let mut events = $node.node.get_and_clear_pending_msg_events();
1851                         assert_eq!(events.len(), 1);
1852                         check_added_monitors!($node, 1);
1853                         let payment_event = SendEvent::from_event(events.remove(0));
1854                         payment_event
1855                 }}
1856         }
1857
1858         let feemsat = 239; // set above
1859         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1860         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1861         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1862
1863         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1864
1865         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1866         {
1867                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1868                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1869                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1870                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1871                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1872
1873                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1874                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1875                         ), true, APIError::ChannelUnavailable { .. }, {});
1876                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1877         }
1878
1879         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1880         // nodes[0]'s wealth
1881         loop {
1882                 let amt_msat = recv_value_0 + total_fee_msat;
1883                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1884                 // Also, ensure that each payment has enough to be over the dust limit to
1885                 // ensure it'll be included in each commit tx fee calculation.
1886                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1887                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1888                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1889                         break;
1890                 }
1891
1892                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1893                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1894                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1895                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1896                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1897
1898                 let (stat01_, stat11_, stat12_, stat22_) = (
1899                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1900                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1901                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1902                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1903                 );
1904
1905                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1906                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1907                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1908                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1909                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1910         }
1911
1912         // adding pending output.
1913         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1914         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1915         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1916         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1917         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1918         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1919         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1920         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1921         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1922         // policy.
1923         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1924         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1925         let amt_msat_1 = recv_value_1 + total_fee_msat;
1926
1927         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1928         let payment_event_1 = {
1929                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1930                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1931                 check_added_monitors!(nodes[0], 1);
1932
1933                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1934                 assert_eq!(events.len(), 1);
1935                 SendEvent::from_event(events.remove(0))
1936         };
1937         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1938
1939         // channel reserve test with htlc pending output > 0
1940         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1941         {
1942                 let mut route = route_1.clone();
1943                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1944                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1945                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1946                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1947                         ), true, APIError::ChannelUnavailable { .. }, {});
1948                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1949         }
1950
1951         // split the rest to test holding cell
1952         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1953         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1954         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1955         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1956         {
1957                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1958                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1959         }
1960
1961         // now see if they go through on both sides
1962         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1963         // but this will stuck in the holding cell
1964         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1965                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1966         check_added_monitors!(nodes[0], 0);
1967         let events = nodes[0].node.get_and_clear_pending_events();
1968         assert_eq!(events.len(), 0);
1969
1970         // test with outbound holding cell amount > 0
1971         {
1972                 let (mut route, our_payment_hash, _, our_payment_secret) =
1973                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1974                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1975                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1976                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1977                         ), true, APIError::ChannelUnavailable { .. }, {});
1978                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1979         }
1980
1981         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1982         // this will also stuck in the holding cell
1983         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1984                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1985         check_added_monitors!(nodes[0], 0);
1986         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1987         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1988
1989         // flush the pending htlc
1990         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1991         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1992         check_added_monitors!(nodes[1], 1);
1993
1994         // the pending htlc should be promoted to committed
1995         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1996         check_added_monitors!(nodes[0], 1);
1997         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1998
1999         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2000         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2001         // No commitment_signed so get_event_msg's assert(len == 1) passes
2002         check_added_monitors!(nodes[0], 1);
2003
2004         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2005         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2006         check_added_monitors!(nodes[1], 1);
2007
2008         expect_pending_htlcs_forwardable!(nodes[1]);
2009
2010         let ref payment_event_11 = expect_forward!(nodes[1]);
2011         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2012         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2013
2014         expect_pending_htlcs_forwardable!(nodes[2]);
2015         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2016
2017         // flush the htlcs in the holding cell
2018         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2019         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2020         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2021         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2022         expect_pending_htlcs_forwardable!(nodes[1]);
2023
2024         let ref payment_event_3 = expect_forward!(nodes[1]);
2025         assert_eq!(payment_event_3.msgs.len(), 2);
2026         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2027         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2028
2029         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2030         expect_pending_htlcs_forwardable!(nodes[2]);
2031
2032         let events = nodes[2].node.get_and_clear_pending_events();
2033         assert_eq!(events.len(), 2);
2034         match events[0] {
2035                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2036                         assert_eq!(our_payment_hash_21, *payment_hash);
2037                         assert_eq!(recv_value_21, amount_msat);
2038                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2039                         assert_eq!(via_channel_id, Some(chan_2.2));
2040                         match &purpose {
2041                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2042                                         assert!(payment_preimage.is_none());
2043                                         assert_eq!(our_payment_secret_21, *payment_secret);
2044                                 },
2045                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2046                         }
2047                 },
2048                 _ => panic!("Unexpected event"),
2049         }
2050         match events[1] {
2051                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2052                         assert_eq!(our_payment_hash_22, *payment_hash);
2053                         assert_eq!(recv_value_22, amount_msat);
2054                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2055                         assert_eq!(via_channel_id, Some(chan_2.2));
2056                         match &purpose {
2057                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2058                                         assert!(payment_preimage.is_none());
2059                                         assert_eq!(our_payment_secret_22, *payment_secret);
2060                                 },
2061                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2062                         }
2063                 },
2064                 _ => panic!("Unexpected event"),
2065         }
2066
2067         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2068         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2069         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2070
2071         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2072         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2073         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2074
2075         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2076         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2077         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2078         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2079         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2080
2081         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2082         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2083 }
2084
2085 #[test]
2086 fn channel_reserve_in_flight_removes() {
2087         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2088         // can send to its counterparty, but due to update ordering, the other side may not yet have
2089         // considered those HTLCs fully removed.
2090         // This tests that we don't count HTLCs which will not be included in the next remote
2091         // commitment transaction towards the reserve value (as it implies no commitment transaction
2092         // will be generated which violates the remote reserve value).
2093         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2094         // To test this we:
2095         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2096         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2097         //    you only consider the value of the first HTLC, it may not),
2098         //  * start routing a third HTLC from A to B,
2099         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2100         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2101         //  * deliver the first fulfill from B
2102         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2103         //    claim,
2104         //  * deliver A's response CS and RAA.
2105         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2106         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2107         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2108         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2109         let chanmon_cfgs = create_chanmon_cfgs(2);
2110         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2111         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2112         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2113         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2114
2115         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2116         // Route the first two HTLCs.
2117         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2118         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2119         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2120
2121         // Start routing the third HTLC (this is just used to get everyone in the right state).
2122         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2123         let send_1 = {
2124                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2125                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2126                 check_added_monitors!(nodes[0], 1);
2127                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2128                 assert_eq!(events.len(), 1);
2129                 SendEvent::from_event(events.remove(0))
2130         };
2131
2132         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2133         // initial fulfill/CS.
2134         nodes[1].node.claim_funds(payment_preimage_1);
2135         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2136         check_added_monitors!(nodes[1], 1);
2137         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2138
2139         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2140         // remove the second HTLC when we send the HTLC back from B to A.
2141         nodes[1].node.claim_funds(payment_preimage_2);
2142         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2143         check_added_monitors!(nodes[1], 1);
2144         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2145
2146         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2147         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2148         check_added_monitors!(nodes[0], 1);
2149         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2150         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2151
2152         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2153         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2154         check_added_monitors!(nodes[1], 1);
2155         // B is already AwaitingRAA, so cant generate a CS here
2156         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2157
2158         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2159         check_added_monitors!(nodes[1], 1);
2160         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2161
2162         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2163         check_added_monitors!(nodes[0], 1);
2164         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2165
2166         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2167         check_added_monitors!(nodes[1], 1);
2168         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2169
2170         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2171         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2172         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2173         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2174         // on-chain as necessary).
2175         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2176         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2177         check_added_monitors!(nodes[0], 1);
2178         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2179         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2180
2181         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2182         check_added_monitors!(nodes[1], 1);
2183         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2184
2185         expect_pending_htlcs_forwardable!(nodes[1]);
2186         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2187
2188         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2189         // resolve the second HTLC from A's point of view.
2190         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2191         check_added_monitors!(nodes[0], 1);
2192         expect_payment_path_successful!(nodes[0]);
2193         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2194
2195         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2196         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2197         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2198         let send_2 = {
2199                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2200                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2201                 check_added_monitors!(nodes[1], 1);
2202                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2203                 assert_eq!(events.len(), 1);
2204                 SendEvent::from_event(events.remove(0))
2205         };
2206
2207         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2208         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2209         check_added_monitors!(nodes[0], 1);
2210         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2211
2212         // Now just resolve all the outstanding messages/HTLCs for completeness...
2213
2214         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2215         check_added_monitors!(nodes[1], 1);
2216         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2217
2218         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2219         check_added_monitors!(nodes[1], 1);
2220
2221         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2222         check_added_monitors!(nodes[0], 1);
2223         expect_payment_path_successful!(nodes[0]);
2224         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2225
2226         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2227         check_added_monitors!(nodes[1], 1);
2228         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2229
2230         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2231         check_added_monitors!(nodes[0], 1);
2232
2233         expect_pending_htlcs_forwardable!(nodes[0]);
2234         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2235
2236         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2237         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2238 }
2239
2240 #[test]
2241 fn channel_monitor_network_test() {
2242         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2243         // tests that ChannelMonitor is able to recover from various states.
2244         let chanmon_cfgs = create_chanmon_cfgs(5);
2245         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2246         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2247         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2248
2249         // Create some initial channels
2250         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2251         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2252         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2253         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2254
2255         // Make sure all nodes are at the same starting height
2256         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2257         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2258         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2259         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2260         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2261
2262         // Rebalance the network a bit by relaying one payment through all the channels...
2263         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2264         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2265         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2266         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2267
2268         // Simple case with no pending HTLCs:
2269         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2270         check_added_monitors!(nodes[1], 1);
2271         check_closed_broadcast!(nodes[1], true);
2272         {
2273                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2274                 assert_eq!(node_txn.len(), 1);
2275                 mine_transaction(&nodes[0], &node_txn[0]);
2276                 check_added_monitors!(nodes[0], 1);
2277                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2278         }
2279         check_closed_broadcast!(nodes[0], true);
2280         assert_eq!(nodes[0].node.list_channels().len(), 0);
2281         assert_eq!(nodes[1].node.list_channels().len(), 1);
2282         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2283         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2284
2285         // One pending HTLC is discarded by the force-close:
2286         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2287
2288         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2289         // broadcasted until we reach the timelock time).
2290         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2291         check_closed_broadcast!(nodes[1], true);
2292         check_added_monitors!(nodes[1], 1);
2293         {
2294                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2295                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2296                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2297                 mine_transaction(&nodes[2], &node_txn[0]);
2298                 check_added_monitors!(nodes[2], 1);
2299                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2300         }
2301         check_closed_broadcast!(nodes[2], true);
2302         assert_eq!(nodes[1].node.list_channels().len(), 0);
2303         assert_eq!(nodes[2].node.list_channels().len(), 1);
2304         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2305         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2306
2307         macro_rules! claim_funds {
2308                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2309                         {
2310                                 $node.node.claim_funds($preimage);
2311                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2312                                 check_added_monitors!($node, 1);
2313
2314                                 let events = $node.node.get_and_clear_pending_msg_events();
2315                                 assert_eq!(events.len(), 1);
2316                                 match events[0] {
2317                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2318                                                 assert!(update_add_htlcs.is_empty());
2319                                                 assert!(update_fail_htlcs.is_empty());
2320                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2321                                         },
2322                                         _ => panic!("Unexpected event"),
2323                                 };
2324                         }
2325                 }
2326         }
2327
2328         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2329         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2330         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2331         check_added_monitors!(nodes[2], 1);
2332         check_closed_broadcast!(nodes[2], true);
2333         let node2_commitment_txid;
2334         {
2335                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2336                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2337                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2338                 node2_commitment_txid = node_txn[0].txid();
2339
2340                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2341                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2342                 mine_transaction(&nodes[3], &node_txn[0]);
2343                 check_added_monitors!(nodes[3], 1);
2344                 check_preimage_claim(&nodes[3], &node_txn);
2345         }
2346         check_closed_broadcast!(nodes[3], true);
2347         assert_eq!(nodes[2].node.list_channels().len(), 0);
2348         assert_eq!(nodes[3].node.list_channels().len(), 1);
2349         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2350         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2351
2352         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2353         // confusing us in the following tests.
2354         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2355
2356         // One pending HTLC to time out:
2357         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2358         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2359         // buffer space).
2360
2361         let (close_chan_update_1, close_chan_update_2) = {
2362                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2363                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2364                 assert_eq!(events.len(), 2);
2365                 let close_chan_update_1 = match events[0] {
2366                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2367                                 msg.clone()
2368                         },
2369                         _ => panic!("Unexpected event"),
2370                 };
2371                 match events[1] {
2372                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2373                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2374                         },
2375                         _ => panic!("Unexpected event"),
2376                 }
2377                 check_added_monitors!(nodes[3], 1);
2378
2379                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2380                 {
2381                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2382                         node_txn.retain(|tx| {
2383                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2384                                         false
2385                                 } else { true }
2386                         });
2387                 }
2388
2389                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2390
2391                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2392                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2393
2394                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2395                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2396                 assert_eq!(events.len(), 2);
2397                 let close_chan_update_2 = match events[0] {
2398                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2399                                 msg.clone()
2400                         },
2401                         _ => panic!("Unexpected event"),
2402                 };
2403                 match events[1] {
2404                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2405                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2406                         },
2407                         _ => panic!("Unexpected event"),
2408                 }
2409                 check_added_monitors!(nodes[4], 1);
2410                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2411
2412                 mine_transaction(&nodes[4], &node_txn[0]);
2413                 check_preimage_claim(&nodes[4], &node_txn);
2414                 (close_chan_update_1, close_chan_update_2)
2415         };
2416         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2417         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2418         assert_eq!(nodes[3].node.list_channels().len(), 0);
2419         assert_eq!(nodes[4].node.list_channels().len(), 0);
2420
2421         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2422                 ChannelMonitorUpdateStatus::Completed);
2423         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2424         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2425 }
2426
2427 #[test]
2428 fn test_justice_tx_htlc_timeout() {
2429         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2430         let mut alice_config = UserConfig::default();
2431         alice_config.channel_handshake_config.announced_channel = true;
2432         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2433         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2434         let mut bob_config = UserConfig::default();
2435         bob_config.channel_handshake_config.announced_channel = true;
2436         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2437         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2438         let user_cfgs = [Some(alice_config), Some(bob_config)];
2439         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2440         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2441         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2444         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2445         // Create some new channels:
2446         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2447
2448         // A pending HTLC which will be revoked:
2449         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2450         // Get the will-be-revoked local txn from nodes[0]
2451         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2452         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2453         assert_eq!(revoked_local_txn[0].input.len(), 1);
2454         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2455         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2456         assert_eq!(revoked_local_txn[1].input.len(), 1);
2457         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2458         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2459         // Revoke the old state
2460         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2461
2462         {
2463                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2464                 {
2465                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2466                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2467                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2468                         check_spends!(node_txn[0], revoked_local_txn[0]);
2469                         node_txn.swap_remove(0);
2470                 }
2471                 check_added_monitors!(nodes[1], 1);
2472                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2473                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2474
2475                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2476                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2477                 // Verify broadcast of revoked HTLC-timeout
2478                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2479                 check_added_monitors!(nodes[0], 1);
2480                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2481                 // Broadcast revoked HTLC-timeout on node 1
2482                 mine_transaction(&nodes[1], &node_txn[1]);
2483                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2484         }
2485         get_announce_close_broadcast_events(&nodes, 0, 1);
2486         assert_eq!(nodes[0].node.list_channels().len(), 0);
2487         assert_eq!(nodes[1].node.list_channels().len(), 0);
2488 }
2489
2490 #[test]
2491 fn test_justice_tx_htlc_success() {
2492         // Test justice txn built on revoked HTLC-Success tx, against both sides
2493         let mut alice_config = UserConfig::default();
2494         alice_config.channel_handshake_config.announced_channel = true;
2495         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2496         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2497         let mut bob_config = UserConfig::default();
2498         bob_config.channel_handshake_config.announced_channel = true;
2499         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2500         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2501         let user_cfgs = [Some(alice_config), Some(bob_config)];
2502         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2503         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2504         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2505         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2506         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2507         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2508         // Create some new channels:
2509         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2510
2511         // A pending HTLC which will be revoked:
2512         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2513         // Get the will-be-revoked local txn from B
2514         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2515         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2516         assert_eq!(revoked_local_txn[0].input.len(), 1);
2517         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2518         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2519         // Revoke the old state
2520         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2521         {
2522                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2523                 {
2524                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2525                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2526                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2527
2528                         check_spends!(node_txn[0], revoked_local_txn[0]);
2529                         node_txn.swap_remove(0);
2530                 }
2531                 check_added_monitors!(nodes[0], 1);
2532                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2533
2534                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2536                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2537                 check_added_monitors!(nodes[1], 1);
2538                 mine_transaction(&nodes[0], &node_txn[1]);
2539                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2540                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2541         }
2542         get_announce_close_broadcast_events(&nodes, 0, 1);
2543         assert_eq!(nodes[0].node.list_channels().len(), 0);
2544         assert_eq!(nodes[1].node.list_channels().len(), 0);
2545 }
2546
2547 #[test]
2548 fn revoked_output_claim() {
2549         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2550         // transaction is broadcast by its counterparty
2551         let chanmon_cfgs = create_chanmon_cfgs(2);
2552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2554         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2555         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2556         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2557         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2558         assert_eq!(revoked_local_txn.len(), 1);
2559         // Only output is the full channel value back to nodes[0]:
2560         assert_eq!(revoked_local_txn[0].output.len(), 1);
2561         // Send a payment through, updating everyone's latest commitment txn
2562         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2563
2564         // Inform nodes[1] that nodes[0] broadcast a stale tx
2565         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2566         check_added_monitors!(nodes[1], 1);
2567         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2568         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2569         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2570
2571         check_spends!(node_txn[0], revoked_local_txn[0]);
2572
2573         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2574         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2575         get_announce_close_broadcast_events(&nodes, 0, 1);
2576         check_added_monitors!(nodes[0], 1);
2577         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2578 }
2579
2580 #[test]
2581 fn test_forming_justice_tx_from_monitor_updates() {
2582         do_test_forming_justice_tx_from_monitor_updates(true);
2583         do_test_forming_justice_tx_from_monitor_updates(false);
2584 }
2585
2586 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2587         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2588         // is properly formed and can be broadcasted/confirmed successfully in the event
2589         // that a revoked commitment transaction is broadcasted
2590         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2591         let chanmon_cfgs = create_chanmon_cfgs(2);
2592         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2593         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2594         let persisters = vec![WatchtowerPersister::new(destination_script0),
2595                 WatchtowerPersister::new(destination_script1)];
2596         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2598         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2599         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2600         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2601
2602         if !broadcast_initial_commitment {
2603                 // Send a payment to move the channel forward
2604                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2605         }
2606
2607         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2608         // We'll keep this commitment transaction to broadcast once it's revoked.
2609         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2610         assert_eq!(revoked_local_txn.len(), 1);
2611         let revoked_commitment_tx = &revoked_local_txn[0];
2612
2613         // Send another payment, now revoking the previous commitment tx
2614         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2615
2616         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2617         check_spends!(justice_tx, revoked_commitment_tx);
2618
2619         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2620         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2621
2622         check_added_monitors!(nodes[1], 1);
2623         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2624                 &[nodes[0].node.get_our_node_id()], 100_000);
2625         get_announce_close_broadcast_events(&nodes, 1, 0);
2626
2627         check_added_monitors!(nodes[0], 1);
2628         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2629                 &[nodes[1].node.get_our_node_id()], 100_000);
2630
2631         // Check that the justice tx has sent the revoked output value to nodes[1]
2632         let monitor = get_monitor!(nodes[1], channel_id);
2633         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2634                 match balance {
2635                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2636                         _ => panic!("Unexpected balance type"),
2637                 }
2638         });
2639         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2640         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2641         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2642         assert_eq!(total_claimable_balance, expected_claimable_balance);
2643 }
2644
2645
2646 #[test]
2647 fn claim_htlc_outputs_shared_tx() {
2648         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2649         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2650         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2653         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2654
2655         // Create some new channel:
2656         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2657
2658         // Rebalance the network to generate htlc in the two directions
2659         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2660         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2661         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2662         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2663
2664         // Get the will-be-revoked local txn from node[0]
2665         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2666         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2667         assert_eq!(revoked_local_txn[0].input.len(), 1);
2668         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2669         assert_eq!(revoked_local_txn[1].input.len(), 1);
2670         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2671         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2672         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2673
2674         //Revoke the old state
2675         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2676
2677         {
2678                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2679                 check_added_monitors!(nodes[0], 1);
2680                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2681                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2682                 check_added_monitors!(nodes[1], 1);
2683                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2684                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2685                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2686
2687                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2688                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2689
2690                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2691                 check_spends!(node_txn[0], revoked_local_txn[0]);
2692
2693                 let mut witness_lens = BTreeSet::new();
2694                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2695                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2696                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2697                 assert_eq!(witness_lens.len(), 3);
2698                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2699                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2700                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2701
2702                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2703                 // ANTI_REORG_DELAY confirmations.
2704                 mine_transaction(&nodes[1], &node_txn[0]);
2705                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2706                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2707         }
2708         get_announce_close_broadcast_events(&nodes, 0, 1);
2709         assert_eq!(nodes[0].node.list_channels().len(), 0);
2710         assert_eq!(nodes[1].node.list_channels().len(), 0);
2711 }
2712
2713 #[test]
2714 fn claim_htlc_outputs_single_tx() {
2715         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2716         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2717         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2721
2722         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2723
2724         // Rebalance the network to generate htlc in the two directions
2725         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2726         // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2727         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2728         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2729         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2730
2731         // Get the will-be-revoked local txn from node[0]
2732         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2733
2734         //Revoke the old state
2735         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2736
2737         {
2738                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2739                 check_added_monitors!(nodes[0], 1);
2740                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2741                 check_added_monitors!(nodes[1], 1);
2742                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2743                 let mut events = nodes[0].node.get_and_clear_pending_events();
2744                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2745                 match events.last().unwrap() {
2746                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2747                         _ => panic!("Unexpected event"),
2748                 }
2749
2750                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2751                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2752
2753                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2754
2755                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2756                 assert_eq!(node_txn[0].input.len(), 1);
2757                 check_spends!(node_txn[0], chan_1.3);
2758                 assert_eq!(node_txn[1].input.len(), 1);
2759                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2760                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2761                 check_spends!(node_txn[1], node_txn[0]);
2762
2763                 // Filter out any non justice transactions.
2764                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2765                 assert!(node_txn.len() > 3);
2766
2767                 assert_eq!(node_txn[0].input.len(), 1);
2768                 assert_eq!(node_txn[1].input.len(), 1);
2769                 assert_eq!(node_txn[2].input.len(), 1);
2770
2771                 check_spends!(node_txn[0], revoked_local_txn[0]);
2772                 check_spends!(node_txn[1], revoked_local_txn[0]);
2773                 check_spends!(node_txn[2], revoked_local_txn[0]);
2774
2775                 let mut witness_lens = BTreeSet::new();
2776                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2777                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2778                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2779                 assert_eq!(witness_lens.len(), 3);
2780                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2781                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2782                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2783
2784                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2785                 // ANTI_REORG_DELAY confirmations.
2786                 mine_transaction(&nodes[1], &node_txn[0]);
2787                 mine_transaction(&nodes[1], &node_txn[1]);
2788                 mine_transaction(&nodes[1], &node_txn[2]);
2789                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2790                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2791         }
2792         get_announce_close_broadcast_events(&nodes, 0, 1);
2793         assert_eq!(nodes[0].node.list_channels().len(), 0);
2794         assert_eq!(nodes[1].node.list_channels().len(), 0);
2795 }
2796
2797 #[test]
2798 fn test_htlc_on_chain_success() {
2799         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2800         // the preimage backward accordingly. So here we test that ChannelManager is
2801         // broadcasting the right event to other nodes in payment path.
2802         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2803         // A --------------------> B ----------------------> C (preimage)
2804         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2805         // commitment transaction was broadcast.
2806         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2807         // towards B.
2808         // B should be able to claim via preimage if A then broadcasts its local tx.
2809         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2810         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2811         // PaymentSent event).
2812
2813         let chanmon_cfgs = create_chanmon_cfgs(3);
2814         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2815         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2816         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2817
2818         // Create some initial channels
2819         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2820         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2821
2822         // Ensure all nodes are at the same height
2823         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2824         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2825         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2826         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2827
2828         // Rebalance the network a bit by relaying one payment through all the channels...
2829         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2830         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2831
2832         let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2833         let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2834
2835         // Broadcast legit commitment tx from C on B's chain
2836         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2837         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2838         assert_eq!(commitment_tx.len(), 1);
2839         check_spends!(commitment_tx[0], chan_2.3);
2840         nodes[2].node.claim_funds(our_payment_preimage);
2841         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2842         nodes[2].node.claim_funds(our_payment_preimage_2);
2843         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2844         check_added_monitors!(nodes[2], 2);
2845         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2846         assert!(updates.update_add_htlcs.is_empty());
2847         assert!(updates.update_fail_htlcs.is_empty());
2848         assert!(updates.update_fail_malformed_htlcs.is_empty());
2849         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2850
2851         mine_transaction(&nodes[2], &commitment_tx[0]);
2852         check_closed_broadcast!(nodes[2], true);
2853         check_added_monitors!(nodes[2], 1);
2854         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2855         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2856         assert_eq!(node_txn.len(), 2);
2857         check_spends!(node_txn[0], commitment_tx[0]);
2858         check_spends!(node_txn[1], commitment_tx[0]);
2859         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2860         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2861         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2862         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2863         assert_eq!(node_txn[0].lock_time.0, 0);
2864         assert_eq!(node_txn[1].lock_time.0, 0);
2865
2866         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2867         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2868         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2869         {
2870                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2871                 assert_eq!(added_monitors.len(), 1);
2872                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2873                 added_monitors.clear();
2874         }
2875         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2876         assert_eq!(forwarded_events.len(), 3);
2877         match forwarded_events[0] {
2878                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2879                 _ => panic!("Unexpected event"),
2880         }
2881         let chan_id = Some(chan_1.2);
2882         match forwarded_events[1] {
2883                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2884                         assert_eq!(fee_earned_msat, Some(1000));
2885                         assert_eq!(prev_channel_id, chan_id);
2886                         assert_eq!(claim_from_onchain_tx, true);
2887                         assert_eq!(next_channel_id, Some(chan_2.2));
2888                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2889                 },
2890                 _ => panic!()
2891         }
2892         match forwarded_events[2] {
2893                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2894                         assert_eq!(fee_earned_msat, Some(1000));
2895                         assert_eq!(prev_channel_id, chan_id);
2896                         assert_eq!(claim_from_onchain_tx, true);
2897                         assert_eq!(next_channel_id, Some(chan_2.2));
2898                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2899                 },
2900                 _ => panic!()
2901         }
2902         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2903         {
2904                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2905                 assert_eq!(added_monitors.len(), 2);
2906                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2907                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2908                 added_monitors.clear();
2909         }
2910         assert_eq!(events.len(), 3);
2911
2912         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2913         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2914
2915         match nodes_2_event {
2916                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2917                 _ => panic!("Unexpected event"),
2918         }
2919
2920         match nodes_0_event {
2921                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2922                         assert!(update_add_htlcs.is_empty());
2923                         assert!(update_fail_htlcs.is_empty());
2924                         assert_eq!(update_fulfill_htlcs.len(), 1);
2925                         assert!(update_fail_malformed_htlcs.is_empty());
2926                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2927                 },
2928                 _ => panic!("Unexpected event"),
2929         };
2930
2931         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2932         match events[0] {
2933                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2934                 _ => panic!("Unexpected event"),
2935         }
2936
2937         macro_rules! check_tx_local_broadcast {
2938                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2939                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2940                         assert_eq!(node_txn.len(), 2);
2941                         // Node[1]: 2 * HTLC-timeout tx
2942                         // Node[0]: 2 * HTLC-timeout tx
2943                         check_spends!(node_txn[0], $commitment_tx);
2944                         check_spends!(node_txn[1], $commitment_tx);
2945                         assert_ne!(node_txn[0].lock_time.0, 0);
2946                         assert_ne!(node_txn[1].lock_time.0, 0);
2947                         if $htlc_offered {
2948                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2949                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2950                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2951                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2952                         } else {
2953                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2954                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2955                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2956                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2957                         }
2958                         node_txn.clear();
2959                 } }
2960         }
2961         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2962         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2963
2964         // Broadcast legit commitment tx from A on B's chain
2965         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2966         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2967         check_spends!(node_a_commitment_tx[0], chan_1.3);
2968         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2969         check_closed_broadcast!(nodes[1], true);
2970         check_added_monitors!(nodes[1], 1);
2971         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2972         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2973         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2974         let commitment_spend =
2975                 if node_txn.len() == 1 {
2976                         &node_txn[0]
2977                 } else {
2978                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2979                         // FullBlockViaListen
2980                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2981                                 check_spends!(node_txn[1], commitment_tx[0]);
2982                                 check_spends!(node_txn[2], commitment_tx[0]);
2983                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2984                                 &node_txn[0]
2985                         } else {
2986                                 check_spends!(node_txn[0], commitment_tx[0]);
2987                                 check_spends!(node_txn[1], commitment_tx[0]);
2988                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2989                                 &node_txn[2]
2990                         }
2991                 };
2992
2993         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2994         assert_eq!(commitment_spend.input.len(), 2);
2995         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2996         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2997         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2998         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2999         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3000         // we already checked the same situation with A.
3001
3002         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3003         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3004         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3005         check_closed_broadcast!(nodes[0], true);
3006         check_added_monitors!(nodes[0], 1);
3007         let events = nodes[0].node.get_and_clear_pending_events();
3008         assert_eq!(events.len(), 5);
3009         let mut first_claimed = false;
3010         for event in events {
3011                 match event {
3012                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3013                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3014                                         assert!(!first_claimed);
3015                                         first_claimed = true;
3016                                 } else {
3017                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3018                                         assert_eq!(payment_hash, payment_hash_2);
3019                                 }
3020                         },
3021                         Event::PaymentPathSuccessful { .. } => {},
3022                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3023                         _ => panic!("Unexpected event"),
3024                 }
3025         }
3026         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3027 }
3028
3029 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3030         // Test that in case of a unilateral close onchain, we detect the state of output and
3031         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3032         // broadcasting the right event to other nodes in payment path.
3033         // A ------------------> B ----------------------> C (timeout)
3034         //    B's commitment tx                 C's commitment tx
3035         //            \                                  \
3036         //         B's HTLC timeout tx               B's timeout tx
3037
3038         let chanmon_cfgs = create_chanmon_cfgs(3);
3039         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3040         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3041         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3042         *nodes[0].connect_style.borrow_mut() = connect_style;
3043         *nodes[1].connect_style.borrow_mut() = connect_style;
3044         *nodes[2].connect_style.borrow_mut() = connect_style;
3045
3046         // Create some intial channels
3047         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3048         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3049
3050         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3051         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3052         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3053
3054         let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3055
3056         // Broadcast legit commitment tx from C on B's chain
3057         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3058         check_spends!(commitment_tx[0], chan_2.3);
3059         nodes[2].node.fail_htlc_backwards(&payment_hash);
3060         check_added_monitors!(nodes[2], 0);
3061         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3062         check_added_monitors!(nodes[2], 1);
3063
3064         let events = nodes[2].node.get_and_clear_pending_msg_events();
3065         assert_eq!(events.len(), 1);
3066         match events[0] {
3067                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3068                         assert!(update_add_htlcs.is_empty());
3069                         assert!(!update_fail_htlcs.is_empty());
3070                         assert!(update_fulfill_htlcs.is_empty());
3071                         assert!(update_fail_malformed_htlcs.is_empty());
3072                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3073                 },
3074                 _ => panic!("Unexpected event"),
3075         };
3076         mine_transaction(&nodes[2], &commitment_tx[0]);
3077         check_closed_broadcast!(nodes[2], true);
3078         check_added_monitors!(nodes[2], 1);
3079         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3080         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3081         assert_eq!(node_txn.len(), 0);
3082
3083         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3084         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3085         mine_transaction(&nodes[1], &commitment_tx[0]);
3086         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3087                 , [nodes[2].node.get_our_node_id()], 100000);
3088         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3089         let timeout_tx = {
3090                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3091                 if nodes[1].connect_style.borrow().skips_blocks() {
3092                         assert_eq!(txn.len(), 1);
3093                 } else {
3094                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3095                 }
3096                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3097                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3098                 txn.remove(0)
3099         };
3100
3101         mine_transaction(&nodes[1], &timeout_tx);
3102         check_added_monitors!(nodes[1], 1);
3103         check_closed_broadcast!(nodes[1], true);
3104
3105         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3106
3107         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3108         check_added_monitors!(nodes[1], 1);
3109         let events = nodes[1].node.get_and_clear_pending_msg_events();
3110         assert_eq!(events.len(), 1);
3111         match events[0] {
3112                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3113                         assert!(update_add_htlcs.is_empty());
3114                         assert!(!update_fail_htlcs.is_empty());
3115                         assert!(update_fulfill_htlcs.is_empty());
3116                         assert!(update_fail_malformed_htlcs.is_empty());
3117                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3118                 },
3119                 _ => panic!("Unexpected event"),
3120         };
3121
3122         // Broadcast legit commitment tx from B on A's chain
3123         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3124         check_spends!(commitment_tx[0], chan_1.3);
3125
3126         mine_transaction(&nodes[0], &commitment_tx[0]);
3127         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3128
3129         check_closed_broadcast!(nodes[0], true);
3130         check_added_monitors!(nodes[0], 1);
3131         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3132         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3133         assert_eq!(node_txn.len(), 1);
3134         check_spends!(node_txn[0], commitment_tx[0]);
3135         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3136 }
3137
3138 #[test]
3139 fn test_htlc_on_chain_timeout() {
3140         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3141         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3142         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3143 }
3144
3145 #[test]
3146 fn test_simple_commitment_revoked_fail_backward() {
3147         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3148         // and fail backward accordingly.
3149
3150         let chanmon_cfgs = create_chanmon_cfgs(3);
3151         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3152         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3153         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3154
3155         // Create some initial channels
3156         create_announced_chan_between_nodes(&nodes, 0, 1);
3157         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3158
3159         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3160         // Get the will-be-revoked local txn from nodes[2]
3161         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3162         // Revoke the old state
3163         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3164
3165         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3166
3167         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3168         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3169         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3170         check_added_monitors!(nodes[1], 1);
3171         check_closed_broadcast!(nodes[1], true);
3172
3173         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3174         check_added_monitors!(nodes[1], 1);
3175         let events = nodes[1].node.get_and_clear_pending_msg_events();
3176         assert_eq!(events.len(), 1);
3177         match events[0] {
3178                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3179                         assert!(update_add_htlcs.is_empty());
3180                         assert_eq!(update_fail_htlcs.len(), 1);
3181                         assert!(update_fulfill_htlcs.is_empty());
3182                         assert!(update_fail_malformed_htlcs.is_empty());
3183                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3184
3185                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3186                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3187                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3188                 },
3189                 _ => panic!("Unexpected event"),
3190         }
3191 }
3192
3193 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3194         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3195         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3196         // commitment transaction anymore.
3197         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3198         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3199         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3200         // technically disallowed and we should probably handle it reasonably.
3201         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3202         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3203         // transactions:
3204         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3205         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3206         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3207         //   and once they revoke the previous commitment transaction (allowing us to send a new
3208         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3209         let chanmon_cfgs = create_chanmon_cfgs(3);
3210         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3211         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3212         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3213
3214         // Create some initial channels
3215         create_announced_chan_between_nodes(&nodes, 0, 1);
3216         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3217
3218         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3219         // Get the will-be-revoked local txn from nodes[2]
3220         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3221         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3222         // Revoke the old state
3223         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3224
3225         let value = if use_dust {
3226                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3227                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3228                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3229                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3230         } else { 3000000 };
3231
3232         let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3233         let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3234         let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3235
3236         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3237         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3238         check_added_monitors!(nodes[2], 1);
3239         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3240         assert!(updates.update_add_htlcs.is_empty());
3241         assert!(updates.update_fulfill_htlcs.is_empty());
3242         assert!(updates.update_fail_malformed_htlcs.is_empty());
3243         assert_eq!(updates.update_fail_htlcs.len(), 1);
3244         assert!(updates.update_fee.is_none());
3245         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3246         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3247         // Drop the last RAA from 3 -> 2
3248
3249         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3250         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3251         check_added_monitors!(nodes[2], 1);
3252         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3253         assert!(updates.update_add_htlcs.is_empty());
3254         assert!(updates.update_fulfill_htlcs.is_empty());
3255         assert!(updates.update_fail_malformed_htlcs.is_empty());
3256         assert_eq!(updates.update_fail_htlcs.len(), 1);
3257         assert!(updates.update_fee.is_none());
3258         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3259         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3260         check_added_monitors!(nodes[1], 1);
3261         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3262         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3263         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3264         check_added_monitors!(nodes[2], 1);
3265
3266         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3267         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3268         check_added_monitors!(nodes[2], 1);
3269         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3270         assert!(updates.update_add_htlcs.is_empty());
3271         assert!(updates.update_fulfill_htlcs.is_empty());
3272         assert!(updates.update_fail_malformed_htlcs.is_empty());
3273         assert_eq!(updates.update_fail_htlcs.len(), 1);
3274         assert!(updates.update_fee.is_none());
3275         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3276         // At this point first_payment_hash has dropped out of the latest two commitment
3277         // transactions that nodes[1] is tracking...
3278         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3279         check_added_monitors!(nodes[1], 1);
3280         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3281         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3282         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3283         check_added_monitors!(nodes[2], 1);
3284
3285         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3286         // on nodes[2]'s RAA.
3287         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3288         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3289                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3290         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3291         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3292         check_added_monitors!(nodes[1], 0);
3293
3294         if deliver_bs_raa {
3295                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3296                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3297                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3298                 check_added_monitors!(nodes[1], 1);
3299                 let events = nodes[1].node.get_and_clear_pending_events();
3300                 assert_eq!(events.len(), 2);
3301                 match events[0] {
3302                         Event::PendingHTLCsForwardable { .. } => { },
3303                         _ => panic!("Unexpected event"),
3304                 };
3305                 match events[1] {
3306                         Event::HTLCHandlingFailed { .. } => { },
3307                         _ => panic!("Unexpected event"),
3308                 }
3309                 // Deliberately don't process the pending fail-back so they all fail back at once after
3310                 // block connection just like the !deliver_bs_raa case
3311         }
3312
3313         let mut failed_htlcs = HashSet::new();
3314         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3315
3316         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3317         check_added_monitors!(nodes[1], 1);
3318         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3319
3320         let events = nodes[1].node.get_and_clear_pending_events();
3321         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3322         match events[0] {
3323                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3324                 _ => panic!("Unexepected event"),
3325         }
3326         match events[1] {
3327                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3328                         assert_eq!(*payment_hash, fourth_payment_hash);
3329                 },
3330                 _ => panic!("Unexpected event"),
3331         }
3332         match events[2] {
3333                 Event::PaymentFailed { ref payment_hash, .. } => {
3334                         assert_eq!(*payment_hash, fourth_payment_hash);
3335                 },
3336                 _ => panic!("Unexpected event"),
3337         }
3338
3339         nodes[1].node.process_pending_htlc_forwards();
3340         check_added_monitors!(nodes[1], 1);
3341
3342         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3343         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3344
3345         if deliver_bs_raa {
3346                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3347                 match nodes_2_event {
3348                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3349                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3350                                 assert_eq!(update_add_htlcs.len(), 1);
3351                                 assert!(update_fulfill_htlcs.is_empty());
3352                                 assert!(update_fail_htlcs.is_empty());
3353                                 assert!(update_fail_malformed_htlcs.is_empty());
3354                         },
3355                         _ => panic!("Unexpected event"),
3356                 }
3357         }
3358
3359         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3360         match nodes_2_event {
3361                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3362                         assert_eq!(channel_id, chan_2.2);
3363                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3364                 },
3365                 _ => panic!("Unexpected event"),
3366         }
3367
3368         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3369         match nodes_0_event {
3370                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3371                         assert!(update_add_htlcs.is_empty());
3372                         assert_eq!(update_fail_htlcs.len(), 3);
3373                         assert!(update_fulfill_htlcs.is_empty());
3374                         assert!(update_fail_malformed_htlcs.is_empty());
3375                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3376
3377                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3378                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3379                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3380
3381                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3382
3383                         let events = nodes[0].node.get_and_clear_pending_events();
3384                         assert_eq!(events.len(), 6);
3385                         match events[0] {
3386                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3387                                         assert!(failed_htlcs.insert(payment_hash.0));
3388                                         // If we delivered B's RAA we got an unknown preimage error, not something
3389                                         // that we should update our routing table for.
3390                                         if !deliver_bs_raa {
3391                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3392                                         }
3393                                 },
3394                                 _ => panic!("Unexpected event"),
3395                         }
3396                         match events[1] {
3397                                 Event::PaymentFailed { ref payment_hash, .. } => {
3398                                         assert_eq!(*payment_hash, first_payment_hash);
3399                                 },
3400                                 _ => panic!("Unexpected event"),
3401                         }
3402                         match events[2] {
3403                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3404                                         assert!(failed_htlcs.insert(payment_hash.0));
3405                                 },
3406                                 _ => panic!("Unexpected event"),
3407                         }
3408                         match events[3] {
3409                                 Event::PaymentFailed { ref payment_hash, .. } => {
3410                                         assert_eq!(*payment_hash, second_payment_hash);
3411                                 },
3412                                 _ => panic!("Unexpected event"),
3413                         }
3414                         match events[4] {
3415                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3416                                         assert!(failed_htlcs.insert(payment_hash.0));
3417                                 },
3418                                 _ => panic!("Unexpected event"),
3419                         }
3420                         match events[5] {
3421                                 Event::PaymentFailed { ref payment_hash, .. } => {
3422                                         assert_eq!(*payment_hash, third_payment_hash);
3423                                 },
3424                                 _ => panic!("Unexpected event"),
3425                         }
3426                 },
3427                 _ => panic!("Unexpected event"),
3428         }
3429
3430         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3431         match events[0] {
3432                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3433                 _ => panic!("Unexpected event"),
3434         }
3435
3436         assert!(failed_htlcs.contains(&first_payment_hash.0));
3437         assert!(failed_htlcs.contains(&second_payment_hash.0));
3438         assert!(failed_htlcs.contains(&third_payment_hash.0));
3439 }
3440
3441 #[test]
3442 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3443         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3444         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3445         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3446         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3447 }
3448
3449 #[test]
3450 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3451         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3452         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3453         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3454         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3455 }
3456
3457 #[test]
3458 fn fail_backward_pending_htlc_upon_channel_failure() {
3459         let chanmon_cfgs = create_chanmon_cfgs(2);
3460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3462         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3463         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3464
3465         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3466         {
3467                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3468                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3469                         PaymentId(payment_hash.0)).unwrap();
3470                 check_added_monitors!(nodes[0], 1);
3471
3472                 let payment_event = {
3473                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3474                         assert_eq!(events.len(), 1);
3475                         SendEvent::from_event(events.remove(0))
3476                 };
3477                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3478                 assert_eq!(payment_event.msgs.len(), 1);
3479         }
3480
3481         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3482         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3483         {
3484                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3485                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3486                 check_added_monitors!(nodes[0], 0);
3487
3488                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3489         }
3490
3491         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3492         {
3493                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3494
3495                 let secp_ctx = Secp256k1::new();
3496                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3497                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3498                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3499                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3500                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3501                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3502
3503                 // Send a 0-msat update_add_htlc to fail the channel.
3504                 let update_add_htlc = msgs::UpdateAddHTLC {
3505                         channel_id: chan.2,
3506                         htlc_id: 0,
3507                         amount_msat: 0,
3508                         payment_hash,
3509                         cltv_expiry,
3510                         onion_routing_packet,
3511                         skimmed_fee_msat: None,
3512                 };
3513                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3514         }
3515         let events = nodes[0].node.get_and_clear_pending_events();
3516         assert_eq!(events.len(), 3);
3517         // Check that Alice fails backward the pending HTLC from the second payment.
3518         match events[0] {
3519                 Event::PaymentPathFailed { payment_hash, .. } => {
3520                         assert_eq!(payment_hash, failed_payment_hash);
3521                 },
3522                 _ => panic!("Unexpected event"),
3523         }
3524         match events[1] {
3525                 Event::PaymentFailed { payment_hash, .. } => {
3526                         assert_eq!(payment_hash, failed_payment_hash);
3527                 },
3528                 _ => panic!("Unexpected event"),
3529         }
3530         match events[2] {
3531                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3532                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3533                 },
3534                 _ => panic!("Unexpected event {:?}", events[1]),
3535         }
3536         check_closed_broadcast!(nodes[0], true);
3537         check_added_monitors!(nodes[0], 1);
3538 }
3539
3540 #[test]
3541 fn test_htlc_ignore_latest_remote_commitment() {
3542         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3543         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3544         let chanmon_cfgs = create_chanmon_cfgs(2);
3545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3548         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3549                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3550                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3551                 // connect_style.
3552                 return;
3553         }
3554         create_announced_chan_between_nodes(&nodes, 0, 1);
3555
3556         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3557         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3558         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3559         check_closed_broadcast!(nodes[0], true);
3560         check_added_monitors!(nodes[0], 1);
3561         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3562
3563         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3564         assert_eq!(node_txn.len(), 3);
3565         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3566
3567         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3568         connect_block(&nodes[1], &block);
3569         check_closed_broadcast!(nodes[1], true);
3570         check_added_monitors!(nodes[1], 1);
3571         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3572
3573         // Duplicate the connect_block call since this may happen due to other listeners
3574         // registering new transactions
3575         connect_block(&nodes[1], &block);
3576 }
3577
3578 #[test]
3579 fn test_force_close_fail_back() {
3580         // Check which HTLCs are failed-backwards on channel force-closure
3581         let chanmon_cfgs = create_chanmon_cfgs(3);
3582         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3583         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3584         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3585         create_announced_chan_between_nodes(&nodes, 0, 1);
3586         create_announced_chan_between_nodes(&nodes, 1, 2);
3587
3588         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3589
3590         let mut payment_event = {
3591                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3592                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3593                 check_added_monitors!(nodes[0], 1);
3594
3595                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3596                 assert_eq!(events.len(), 1);
3597                 SendEvent::from_event(events.remove(0))
3598         };
3599
3600         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3601         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3602
3603         expect_pending_htlcs_forwardable!(nodes[1]);
3604
3605         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3606         assert_eq!(events_2.len(), 1);
3607         payment_event = SendEvent::from_event(events_2.remove(0));
3608         assert_eq!(payment_event.msgs.len(), 1);
3609
3610         check_added_monitors!(nodes[1], 1);
3611         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3612         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3613         check_added_monitors!(nodes[2], 1);
3614         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3615
3616         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3617         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3618         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3619
3620         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3621         check_closed_broadcast!(nodes[2], true);
3622         check_added_monitors!(nodes[2], 1);
3623         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3624         let tx = {
3625                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3626                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3627                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3628                 // back to nodes[1] upon timeout otherwise.
3629                 assert_eq!(node_txn.len(), 1);
3630                 node_txn.remove(0)
3631         };
3632
3633         mine_transaction(&nodes[1], &tx);
3634
3635         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3636         check_closed_broadcast!(nodes[1], true);
3637         check_added_monitors!(nodes[1], 1);
3638         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3639
3640         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3641         {
3642                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3643                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3644         }
3645         mine_transaction(&nodes[2], &tx);
3646         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3647         assert_eq!(node_txn.len(), 1);
3648         assert_eq!(node_txn[0].input.len(), 1);
3649         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3650         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3651         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3652
3653         check_spends!(node_txn[0], tx);
3654 }
3655
3656 #[test]
3657 fn test_dup_events_on_peer_disconnect() {
3658         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3659         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3660         // as we used to generate the event immediately upon receipt of the payment preimage in the
3661         // update_fulfill_htlc message.
3662
3663         let chanmon_cfgs = create_chanmon_cfgs(2);
3664         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3665         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3666         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3667         create_announced_chan_between_nodes(&nodes, 0, 1);
3668
3669         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3670
3671         nodes[1].node.claim_funds(payment_preimage);
3672         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3673         check_added_monitors!(nodes[1], 1);
3674         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3675         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3676         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3677
3678         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3679         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3680
3681         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3682         reconnect_args.pending_htlc_claims.0 = 1;
3683         reconnect_nodes(reconnect_args);
3684         expect_payment_path_successful!(nodes[0]);
3685 }
3686
3687 #[test]
3688 fn test_peer_disconnected_before_funding_broadcasted() {
3689         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3690         // before the funding transaction has been broadcasted.
3691         let chanmon_cfgs = create_chanmon_cfgs(2);
3692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3694         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3695
3696         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3697         // broadcasted, even though it's created by `nodes[0]`.
3698         let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3699         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3700         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3701         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3702         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3703
3704         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3705         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3706
3707         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3708
3709         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3710         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3711
3712         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3713         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3714         // broadcasted.
3715         {
3716                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3717         }
3718
3719         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3720         // disconnected before the funding transaction was broadcasted.
3721         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3722         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3723
3724         check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3725                 , [nodes[1].node.get_our_node_id()], 1000000);
3726         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3727                 , [nodes[0].node.get_our_node_id()], 1000000);
3728 }
3729
3730 #[test]
3731 fn test_simple_peer_disconnect() {
3732         // Test that we can reconnect when there are no lost messages
3733         let chanmon_cfgs = create_chanmon_cfgs(3);
3734         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3735         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3736         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3737         create_announced_chan_between_nodes(&nodes, 0, 1);
3738         create_announced_chan_between_nodes(&nodes, 1, 2);
3739
3740         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3741         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3742         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3743         reconnect_args.send_channel_ready = (true, true);
3744         reconnect_nodes(reconnect_args);
3745
3746         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3747         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3748         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3749         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3750
3751         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3752         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3753         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3754
3755         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3756         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3757         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3758         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3759
3760         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3761         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3762
3763         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3764         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3765
3766         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3767         reconnect_args.pending_cell_htlc_fails.0 = 1;
3768         reconnect_args.pending_cell_htlc_claims.0 = 1;
3769         reconnect_nodes(reconnect_args);
3770         {
3771                 let events = nodes[0].node.get_and_clear_pending_events();
3772                 assert_eq!(events.len(), 4);
3773                 match events[0] {
3774                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3775                                 assert_eq!(payment_preimage, payment_preimage_3);
3776                                 assert_eq!(payment_hash, payment_hash_3);
3777                         },
3778                         _ => panic!("Unexpected event"),
3779                 }
3780                 match events[1] {
3781                         Event::PaymentPathSuccessful { .. } => {},
3782                         _ => panic!("Unexpected event"),
3783                 }
3784                 match events[2] {
3785                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3786                                 assert_eq!(payment_hash, payment_hash_5);
3787                                 assert!(payment_failed_permanently);
3788                         },
3789                         _ => panic!("Unexpected event"),
3790                 }
3791                 match events[3] {
3792                         Event::PaymentFailed { payment_hash, .. } => {
3793                                 assert_eq!(payment_hash, payment_hash_5);
3794                         },
3795                         _ => panic!("Unexpected event"),
3796                 }
3797         }
3798         check_added_monitors(&nodes[0], 1);
3799
3800         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3801         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3802 }
3803
3804 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3805         // Test that we can reconnect when in-flight HTLC updates get dropped
3806         let chanmon_cfgs = create_chanmon_cfgs(2);
3807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3809         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3810
3811         let mut as_channel_ready = None;
3812         let channel_id = if messages_delivered == 0 {
3813                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3814                 as_channel_ready = Some(channel_ready);
3815                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3816                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3817                 // it before the channel_reestablish message.
3818                 chan_id
3819         } else {
3820                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3821         };
3822
3823         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3824
3825         let payment_event = {
3826                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3827                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3828                 check_added_monitors!(nodes[0], 1);
3829
3830                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3831                 assert_eq!(events.len(), 1);
3832                 SendEvent::from_event(events.remove(0))
3833         };
3834         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3835
3836         if messages_delivered < 2 {
3837                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3838         } else {
3839                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3840                 if messages_delivered >= 3 {
3841                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3842                         check_added_monitors!(nodes[1], 1);
3843                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3844
3845                         if messages_delivered >= 4 {
3846                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3847                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3848                                 check_added_monitors!(nodes[0], 1);
3849
3850                                 if messages_delivered >= 5 {
3851                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3852                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3853                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3854                                         check_added_monitors!(nodes[0], 1);
3855
3856                                         if messages_delivered >= 6 {
3857                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3858                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3859                                                 check_added_monitors!(nodes[1], 1);
3860                                         }
3861                                 }
3862                         }
3863                 }
3864         }
3865
3866         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3867         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3868         if messages_delivered < 3 {
3869                 if simulate_broken_lnd {
3870                         // lnd has a long-standing bug where they send a channel_ready prior to a
3871                         // channel_reestablish if you reconnect prior to channel_ready time.
3872                         //
3873                         // Here we simulate that behavior, delivering a channel_ready immediately on
3874                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3875                         // in `reconnect_nodes` but we currently don't fail based on that.
3876                         //
3877                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3878                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3879                 }
3880                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3881                 // received on either side, both sides will need to resend them.
3882                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3883                 reconnect_args.send_channel_ready = (true, true);
3884                 reconnect_args.pending_htlc_adds.1 = 1;
3885                 reconnect_nodes(reconnect_args);
3886         } else if messages_delivered == 3 {
3887                 // nodes[0] still wants its RAA + commitment_signed
3888                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3889                 reconnect_args.pending_responding_commitment_signed.0 = true;
3890                 reconnect_args.pending_raa.0 = true;
3891                 reconnect_nodes(reconnect_args);
3892         } else if messages_delivered == 4 {
3893                 // nodes[0] still wants its commitment_signed
3894                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3895                 reconnect_args.pending_responding_commitment_signed.0 = true;
3896                 reconnect_nodes(reconnect_args);
3897         } else if messages_delivered == 5 {
3898                 // nodes[1] still wants its final RAA
3899                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3900                 reconnect_args.pending_raa.1 = true;
3901                 reconnect_nodes(reconnect_args);
3902         } else if messages_delivered == 6 {
3903                 // Everything was delivered...
3904                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3905         }
3906
3907         let events_1 = nodes[1].node.get_and_clear_pending_events();
3908         if messages_delivered == 0 {
3909                 assert_eq!(events_1.len(), 2);
3910                 match events_1[0] {
3911                         Event::ChannelReady { .. } => { },
3912                         _ => panic!("Unexpected event"),
3913                 };
3914                 match events_1[1] {
3915                         Event::PendingHTLCsForwardable { .. } => { },
3916                         _ => panic!("Unexpected event"),
3917                 };
3918         } else {
3919                 assert_eq!(events_1.len(), 1);
3920                 match events_1[0] {
3921                         Event::PendingHTLCsForwardable { .. } => { },
3922                         _ => panic!("Unexpected event"),
3923                 };
3924         }
3925
3926         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3927         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3928         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3929
3930         nodes[1].node.process_pending_htlc_forwards();
3931
3932         let events_2 = nodes[1].node.get_and_clear_pending_events();
3933         assert_eq!(events_2.len(), 1);
3934         match events_2[0] {
3935                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3936                         assert_eq!(payment_hash_1, *payment_hash);
3937                         assert_eq!(amount_msat, 1_000_000);
3938                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3939                         assert_eq!(via_channel_id, Some(channel_id));
3940                         match &purpose {
3941                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3942                                         assert!(payment_preimage.is_none());
3943                                         assert_eq!(payment_secret_1, *payment_secret);
3944                                 },
3945                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3946                         }
3947                 },
3948                 _ => panic!("Unexpected event"),
3949         }
3950
3951         nodes[1].node.claim_funds(payment_preimage_1);
3952         check_added_monitors!(nodes[1], 1);
3953         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3954
3955         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3956         assert_eq!(events_3.len(), 1);
3957         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3958                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3959                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3960                         assert!(updates.update_add_htlcs.is_empty());
3961                         assert!(updates.update_fail_htlcs.is_empty());
3962                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3963                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3964                         assert!(updates.update_fee.is_none());
3965                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3966                 },
3967                 _ => panic!("Unexpected event"),
3968         };
3969
3970         if messages_delivered >= 1 {
3971                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3972
3973                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3974                 assert_eq!(events_4.len(), 1);
3975                 match events_4[0] {
3976                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3977                                 assert_eq!(payment_preimage_1, *payment_preimage);
3978                                 assert_eq!(payment_hash_1, *payment_hash);
3979                         },
3980                         _ => panic!("Unexpected event"),
3981                 }
3982
3983                 if messages_delivered >= 2 {
3984                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3985                         check_added_monitors!(nodes[0], 1);
3986                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3987
3988                         if messages_delivered >= 3 {
3989                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3990                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3991                                 check_added_monitors!(nodes[1], 1);
3992
3993                                 if messages_delivered >= 4 {
3994                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3995                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3996                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3997                                         check_added_monitors!(nodes[1], 1);
3998
3999                                         if messages_delivered >= 5 {
4000                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4001                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4002                                                 check_added_monitors!(nodes[0], 1);
4003                                         }
4004                                 }
4005                         }
4006                 }
4007         }
4008
4009         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4010         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4011         if messages_delivered < 2 {
4012                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4013                 reconnect_args.pending_htlc_claims.0 = 1;
4014                 reconnect_nodes(reconnect_args);
4015                 if messages_delivered < 1 {
4016                         expect_payment_sent!(nodes[0], payment_preimage_1);
4017                 } else {
4018                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4019                 }
4020         } else if messages_delivered == 2 {
4021                 // nodes[0] still wants its RAA + commitment_signed
4022                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4023                 reconnect_args.pending_responding_commitment_signed.1 = true;
4024                 reconnect_args.pending_raa.1 = true;
4025                 reconnect_nodes(reconnect_args);
4026         } else if messages_delivered == 3 {
4027                 // nodes[0] still wants its commitment_signed
4028                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4029                 reconnect_args.pending_responding_commitment_signed.1 = true;
4030                 reconnect_nodes(reconnect_args);
4031         } else if messages_delivered == 4 {
4032                 // nodes[1] still wants its final RAA
4033                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4034                 reconnect_args.pending_raa.0 = true;
4035                 reconnect_nodes(reconnect_args);
4036         } else if messages_delivered == 5 {
4037                 // Everything was delivered...
4038                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4039         }
4040
4041         if messages_delivered == 1 || messages_delivered == 2 {
4042                 expect_payment_path_successful!(nodes[0]);
4043         }
4044         if messages_delivered <= 5 {
4045                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4046                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4047         }
4048         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4049
4050         if messages_delivered > 2 {
4051                 expect_payment_path_successful!(nodes[0]);
4052         }
4053
4054         // Channel should still work fine...
4055         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4056         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4057         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4058 }
4059
4060 #[test]
4061 fn test_drop_messages_peer_disconnect_a() {
4062         do_test_drop_messages_peer_disconnect(0, true);
4063         do_test_drop_messages_peer_disconnect(0, false);
4064         do_test_drop_messages_peer_disconnect(1, false);
4065         do_test_drop_messages_peer_disconnect(2, false);
4066 }
4067
4068 #[test]
4069 fn test_drop_messages_peer_disconnect_b() {
4070         do_test_drop_messages_peer_disconnect(3, false);
4071         do_test_drop_messages_peer_disconnect(4, false);
4072         do_test_drop_messages_peer_disconnect(5, false);
4073         do_test_drop_messages_peer_disconnect(6, false);
4074 }
4075
4076 #[test]
4077 fn test_channel_ready_without_best_block_updated() {
4078         // Previously, if we were offline when a funding transaction was locked in, and then we came
4079         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4080         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4081         // channel_ready immediately instead.
4082         let chanmon_cfgs = create_chanmon_cfgs(2);
4083         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4084         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4085         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4086         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4087
4088         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4089
4090         let conf_height = nodes[0].best_block_info().1 + 1;
4091         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4092         let block_txn = [funding_tx];
4093         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4094         let conf_block_header = nodes[0].get_block_header(conf_height);
4095         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4096
4097         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4098         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4099         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4100 }
4101
4102 #[test]
4103 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4104         let chanmon_cfgs = create_chanmon_cfgs(2);
4105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4107         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4108
4109         // Let channel_manager get ahead of chain_monitor by 1 block.
4110         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4111         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4112         let height_1 = nodes[0].best_block_info().1 + 1;
4113         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4114
4115         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4116         nodes[0].node.block_connected(&block_1, height_1);
4117
4118         // Create channel, and it gets added to chain_monitor in funding_created.
4119         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4120
4121         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4122         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4123         // was running ahead of chain_monitor at the time of funding_created.
4124         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4125         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4126         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4127         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4128
4129         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4130         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4131         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4132 }
4133
4134 #[test]
4135 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4136         let chanmon_cfgs = create_chanmon_cfgs(2);
4137         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4138         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4139         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4140
4141         // Let chain_monitor get ahead of channel_manager by 1 block.
4142         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4143         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4144         let height_1 = nodes[0].best_block_info().1 + 1;
4145         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4146
4147         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4148         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4149
4150         // Create channel, and it gets added to chain_monitor in funding_created.
4151         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4152
4153         // channel_manager can't really skip block_1, it should get it eventually.
4154         nodes[0].node.block_connected(&block_1, height_1);
4155
4156         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4157         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4158         // running behind at the time of funding_created.
4159         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4160         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4161         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4162         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4163
4164         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4165         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4166         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4167 }
4168
4169 #[test]
4170 fn test_drop_messages_peer_disconnect_dual_htlc() {
4171         // Test that we can handle reconnecting when both sides of a channel have pending
4172         // commitment_updates when we disconnect.
4173         let chanmon_cfgs = create_chanmon_cfgs(2);
4174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4176         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4177         create_announced_chan_between_nodes(&nodes, 0, 1);
4178
4179         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4180
4181         // Now try to send a second payment which will fail to send
4182         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4183         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4184                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4185         check_added_monitors!(nodes[0], 1);
4186
4187         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4188         assert_eq!(events_1.len(), 1);
4189         match events_1[0] {
4190                 MessageSendEvent::UpdateHTLCs { .. } => {},
4191                 _ => panic!("Unexpected event"),
4192         }
4193
4194         nodes[1].node.claim_funds(payment_preimage_1);
4195         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4196         check_added_monitors!(nodes[1], 1);
4197
4198         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4199         assert_eq!(events_2.len(), 1);
4200         match events_2[0] {
4201                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
4202                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4203                         assert!(update_add_htlcs.is_empty());
4204                         assert_eq!(update_fulfill_htlcs.len(), 1);
4205                         assert!(update_fail_htlcs.is_empty());
4206                         assert!(update_fail_malformed_htlcs.is_empty());
4207                         assert!(update_fee.is_none());
4208
4209                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4210                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4211                         assert_eq!(events_3.len(), 1);
4212                         match events_3[0] {
4213                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4214                                         assert_eq!(*payment_preimage, payment_preimage_1);
4215                                         assert_eq!(*payment_hash, payment_hash_1);
4216                                 },
4217                                 _ => panic!("Unexpected event"),
4218                         }
4219
4220                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4221                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4222                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4223                         check_added_monitors!(nodes[0], 1);
4224                 },
4225                 _ => panic!("Unexpected event"),
4226         }
4227
4228         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4229         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4230
4231         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4232                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4233         }, true).unwrap();
4234         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4235         assert_eq!(reestablish_1.len(), 1);
4236         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4237                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4238         }, false).unwrap();
4239         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4240         assert_eq!(reestablish_2.len(), 1);
4241
4242         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4243         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4244         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4245         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4246
4247         assert!(as_resp.0.is_none());
4248         assert!(bs_resp.0.is_none());
4249
4250         assert!(bs_resp.1.is_none());
4251         assert!(bs_resp.2.is_none());
4252
4253         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4254
4255         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4256         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4257         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4258         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4259         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4260         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4261         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4262         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4263         // No commitment_signed so get_event_msg's assert(len == 1) passes
4264         check_added_monitors!(nodes[1], 1);
4265
4266         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4267         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4268         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4269         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4270         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4271         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4272         assert!(bs_second_commitment_signed.update_fee.is_none());
4273         check_added_monitors!(nodes[1], 1);
4274
4275         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4276         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4277         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4278         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4279         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4280         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4281         assert!(as_commitment_signed.update_fee.is_none());
4282         check_added_monitors!(nodes[0], 1);
4283
4284         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4285         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4286         // No commitment_signed so get_event_msg's assert(len == 1) passes
4287         check_added_monitors!(nodes[0], 1);
4288
4289         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4290         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4291         // No commitment_signed so get_event_msg's assert(len == 1) passes
4292         check_added_monitors!(nodes[1], 1);
4293
4294         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4295         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4296         check_added_monitors!(nodes[1], 1);
4297
4298         expect_pending_htlcs_forwardable!(nodes[1]);
4299
4300         let events_5 = nodes[1].node.get_and_clear_pending_events();
4301         assert_eq!(events_5.len(), 1);
4302         match events_5[0] {
4303                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4304                         assert_eq!(payment_hash_2, *payment_hash);
4305                         match &purpose {
4306                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4307                                         assert!(payment_preimage.is_none());
4308                                         assert_eq!(payment_secret_2, *payment_secret);
4309                                 },
4310                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4311                         }
4312                 },
4313                 _ => panic!("Unexpected event"),
4314         }
4315
4316         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4317         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4318         check_added_monitors!(nodes[0], 1);
4319
4320         expect_payment_path_successful!(nodes[0]);
4321         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4322 }
4323
4324 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4325         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4326         // to avoid our counterparty failing the channel.
4327         let chanmon_cfgs = create_chanmon_cfgs(2);
4328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4330         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4331
4332         create_announced_chan_between_nodes(&nodes, 0, 1);
4333
4334         let our_payment_hash = if send_partial_mpp {
4335                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4336                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4337                 // indicates there are more HTLCs coming.
4338                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4339                 let payment_id = PaymentId([42; 32]);
4340                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4341                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4342                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4343                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4344                         &None, session_privs[0]).unwrap();
4345                 check_added_monitors!(nodes[0], 1);
4346                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4347                 assert_eq!(events.len(), 1);
4348                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4349                 // hop should *not* yet generate any PaymentClaimable event(s).
4350                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4351                 our_payment_hash
4352         } else {
4353                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4354         };
4355
4356         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4357         connect_block(&nodes[0], &block);
4358         connect_block(&nodes[1], &block);
4359         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4360         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4361                 block.header.prev_blockhash = block.block_hash();
4362                 connect_block(&nodes[0], &block);
4363                 connect_block(&nodes[1], &block);
4364         }
4365
4366         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4367
4368         check_added_monitors!(nodes[1], 1);
4369         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4370         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4371         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4372         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4373         assert!(htlc_timeout_updates.update_fee.is_none());
4374
4375         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4376         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4377         // 100_000 msat as u64, followed by the height at which we failed back above
4378         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4379         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4380         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4381 }
4382
4383 #[test]
4384 fn test_htlc_timeout() {
4385         do_test_htlc_timeout(true);
4386         do_test_htlc_timeout(false);
4387 }
4388
4389 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4390         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4391         let chanmon_cfgs = create_chanmon_cfgs(3);
4392         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4393         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4394         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4395         create_announced_chan_between_nodes(&nodes, 0, 1);
4396         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4397
4398         // Make sure all nodes are at the same starting height
4399         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4400         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4401         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4402
4403         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4404         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4405         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4406                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4407         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4408         check_added_monitors!(nodes[1], 1);
4409
4410         // Now attempt to route a second payment, which should be placed in the holding cell
4411         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4412         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4413         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4414                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4415         if forwarded_htlc {
4416                 check_added_monitors!(nodes[0], 1);
4417                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4418                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4419                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4420                 expect_pending_htlcs_forwardable!(nodes[1]);
4421         }
4422         check_added_monitors!(nodes[1], 0);
4423
4424         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4425         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4426         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4427         connect_blocks(&nodes[1], 1);
4428
4429         if forwarded_htlc {
4430                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4431                 check_added_monitors!(nodes[1], 1);
4432                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4433                 assert_eq!(fail_commit.len(), 1);
4434                 match fail_commit[0] {
4435                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4436                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4437                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4438                         },
4439                         _ => unreachable!(),
4440                 }
4441                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4442         } else {
4443                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4444         }
4445 }
4446
4447 #[test]
4448 fn test_holding_cell_htlc_add_timeouts() {
4449         do_test_holding_cell_htlc_add_timeouts(false);
4450         do_test_holding_cell_htlc_add_timeouts(true);
4451 }
4452
4453 macro_rules! check_spendable_outputs {
4454         ($node: expr, $keysinterface: expr) => {
4455                 {
4456                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4457                         let mut txn = Vec::new();
4458                         let mut all_outputs = Vec::new();
4459                         let secp_ctx = Secp256k1::new();
4460                         for event in events.drain(..) {
4461                                 match event {
4462                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4463                                                 for outp in outputs.drain(..) {
4464                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4465                                                         all_outputs.push(outp);
4466                                                 }
4467                                         },
4468                                         _ => panic!("Unexpected event"),
4469                                 };
4470                         }
4471                         if all_outputs.len() > 1 {
4472                                 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx) {
4473                                         txn.push(tx);
4474                                 }
4475                         }
4476                         txn
4477                 }
4478         }
4479 }
4480
4481 #[test]
4482 fn test_claim_sizeable_push_msat() {
4483         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4484         let chanmon_cfgs = create_chanmon_cfgs(2);
4485         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4486         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4487         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4488
4489         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4490         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4491         check_closed_broadcast!(nodes[1], true);
4492         check_added_monitors!(nodes[1], 1);
4493         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4494         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4495         assert_eq!(node_txn.len(), 1);
4496         check_spends!(node_txn[0], chan.3);
4497         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4498
4499         mine_transaction(&nodes[1], &node_txn[0]);
4500         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4501
4502         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4503         assert_eq!(spend_txn.len(), 1);
4504         assert_eq!(spend_txn[0].input.len(), 1);
4505         check_spends!(spend_txn[0], node_txn[0]);
4506         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4507 }
4508
4509 #[test]
4510 fn test_claim_on_remote_sizeable_push_msat() {
4511         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4512         // to_remote output is encumbered by a P2WPKH
4513         let chanmon_cfgs = create_chanmon_cfgs(2);
4514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4517
4518         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4519         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4520         check_closed_broadcast!(nodes[0], true);
4521         check_added_monitors!(nodes[0], 1);
4522         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4523
4524         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4525         assert_eq!(node_txn.len(), 1);
4526         check_spends!(node_txn[0], chan.3);
4527         assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4528
4529         mine_transaction(&nodes[1], &node_txn[0]);
4530         check_closed_broadcast!(nodes[1], true);
4531         check_added_monitors!(nodes[1], 1);
4532         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4533         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4534
4535         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4536         assert_eq!(spend_txn.len(), 1);
4537         check_spends!(spend_txn[0], node_txn[0]);
4538 }
4539
4540 #[test]
4541 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4542         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4543         // to_remote output is encumbered by a P2WPKH
4544
4545         let chanmon_cfgs = create_chanmon_cfgs(2);
4546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4548         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4549
4550         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4551         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4552         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4553         assert_eq!(revoked_local_txn[0].input.len(), 1);
4554         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4555
4556         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4557         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4558         check_closed_broadcast!(nodes[1], true);
4559         check_added_monitors!(nodes[1], 1);
4560         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4561
4562         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4563         mine_transaction(&nodes[1], &node_txn[0]);
4564         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4565
4566         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4567         assert_eq!(spend_txn.len(), 3);
4568         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4569         check_spends!(spend_txn[1], node_txn[0]);
4570         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4571 }
4572
4573 #[test]
4574 fn test_static_spendable_outputs_preimage_tx() {
4575         let chanmon_cfgs = create_chanmon_cfgs(2);
4576         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4577         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4578         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4579
4580         // Create some initial channels
4581         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4582
4583         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4584
4585         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4586         assert_eq!(commitment_tx[0].input.len(), 1);
4587         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4588
4589         // Settle A's commitment tx on B's chain
4590         nodes[1].node.claim_funds(payment_preimage);
4591         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4592         check_added_monitors!(nodes[1], 1);
4593         mine_transaction(&nodes[1], &commitment_tx[0]);
4594         check_added_monitors!(nodes[1], 1);
4595         let events = nodes[1].node.get_and_clear_pending_msg_events();
4596         match events[0] {
4597                 MessageSendEvent::UpdateHTLCs { .. } => {},
4598                 _ => panic!("Unexpected event"),
4599         }
4600         match events[1] {
4601                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4602                 _ => panic!("Unexepected event"),
4603         }
4604
4605         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4606         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4607         assert_eq!(node_txn.len(), 1);
4608         check_spends!(node_txn[0], commitment_tx[0]);
4609         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4610
4611         mine_transaction(&nodes[1], &node_txn[0]);
4612         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4613         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4614
4615         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4616         assert_eq!(spend_txn.len(), 1);
4617         check_spends!(spend_txn[0], node_txn[0]);
4618 }
4619
4620 #[test]
4621 fn test_static_spendable_outputs_timeout_tx() {
4622         let chanmon_cfgs = create_chanmon_cfgs(2);
4623         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4624         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4625         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4626
4627         // Create some initial channels
4628         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4629
4630         // Rebalance the network a bit by relaying one payment through all the channels ...
4631         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4632
4633         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4634
4635         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4636         assert_eq!(commitment_tx[0].input.len(), 1);
4637         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4638
4639         // Settle A's commitment tx on B' chain
4640         mine_transaction(&nodes[1], &commitment_tx[0]);
4641         check_added_monitors!(nodes[1], 1);
4642         let events = nodes[1].node.get_and_clear_pending_msg_events();
4643         match events[0] {
4644                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4645                 _ => panic!("Unexpected event"),
4646         }
4647         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4648
4649         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4650         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4651         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4652         check_spends!(node_txn[0],  commitment_tx[0].clone());
4653         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4654
4655         mine_transaction(&nodes[1], &node_txn[0]);
4656         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4657         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4658         expect_payment_failed!(nodes[1], our_payment_hash, false);
4659
4660         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4661         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4662         check_spends!(spend_txn[0], commitment_tx[0]);
4663         check_spends!(spend_txn[1], node_txn[0]);
4664         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4665 }
4666
4667 #[test]
4668 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4669         let chanmon_cfgs = create_chanmon_cfgs(2);
4670         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4671         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4672         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4673
4674         // Create some initial channels
4675         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4676
4677         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4678         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4679         assert_eq!(revoked_local_txn[0].input.len(), 1);
4680         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4681
4682         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4683
4684         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4685         check_closed_broadcast!(nodes[1], true);
4686         check_added_monitors!(nodes[1], 1);
4687         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4688
4689         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4690         assert_eq!(node_txn.len(), 1);
4691         assert_eq!(node_txn[0].input.len(), 2);
4692         check_spends!(node_txn[0], revoked_local_txn[0]);
4693
4694         mine_transaction(&nodes[1], &node_txn[0]);
4695         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4696
4697         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4698         assert_eq!(spend_txn.len(), 1);
4699         check_spends!(spend_txn[0], node_txn[0]);
4700 }
4701
4702 #[test]
4703 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4704         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4705         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4706         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4707         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4708         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4709
4710         // Create some initial channels
4711         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4712
4713         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4714         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4715         assert_eq!(revoked_local_txn[0].input.len(), 1);
4716         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4717
4718         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4719
4720         // A will generate HTLC-Timeout from revoked commitment tx
4721         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4722         check_closed_broadcast!(nodes[0], true);
4723         check_added_monitors!(nodes[0], 1);
4724         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4725         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4726
4727         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4728         assert_eq!(revoked_htlc_txn.len(), 1);
4729         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4730         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4731         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4732         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4733
4734         // B will generate justice tx from A's revoked commitment/HTLC tx
4735         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4736         check_closed_broadcast!(nodes[1], true);
4737         check_added_monitors!(nodes[1], 1);
4738         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4739
4740         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4741         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4742         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4743         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4744         // transactions next...
4745         assert_eq!(node_txn[0].input.len(), 3);
4746         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4747
4748         assert_eq!(node_txn[1].input.len(), 2);
4749         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4750         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4751                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4752         } else {
4753                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4754                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4755         }
4756
4757         mine_transaction(&nodes[1], &node_txn[1]);
4758         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4759
4760         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4761         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4762         assert_eq!(spend_txn.len(), 1);
4763         assert_eq!(spend_txn[0].input.len(), 1);
4764         check_spends!(spend_txn[0], node_txn[1]);
4765 }
4766
4767 #[test]
4768 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4769         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4770         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4771         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4772         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4773         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4774
4775         // Create some initial channels
4776         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4777
4778         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4779         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4780         assert_eq!(revoked_local_txn[0].input.len(), 1);
4781         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4782
4783         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4784         assert_eq!(revoked_local_txn[0].output.len(), 2);
4785
4786         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4787
4788         // B will generate HTLC-Success from revoked commitment tx
4789         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4790         check_closed_broadcast!(nodes[1], true);
4791         check_added_monitors!(nodes[1], 1);
4792         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4793         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4794
4795         assert_eq!(revoked_htlc_txn.len(), 1);
4796         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4797         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4798         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4799
4800         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4801         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4802         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4803
4804         // A will generate justice tx from B's revoked commitment/HTLC tx
4805         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4806         check_closed_broadcast!(nodes[0], true);
4807         check_added_monitors!(nodes[0], 1);
4808         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4809
4810         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4811         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4812
4813         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4814         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4815         // transactions next...
4816         assert_eq!(node_txn[0].input.len(), 2);
4817         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4818         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4819                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4820         } else {
4821                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4822                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4823         }
4824
4825         assert_eq!(node_txn[1].input.len(), 1);
4826         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4827
4828         mine_transaction(&nodes[0], &node_txn[1]);
4829         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4830
4831         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4832         // didn't try to generate any new transactions.
4833
4834         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4835         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4836         assert_eq!(spend_txn.len(), 3);
4837         assert_eq!(spend_txn[0].input.len(), 1);
4838         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4839         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4840         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4841         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4842 }
4843
4844 #[test]
4845 fn test_onchain_to_onchain_claim() {
4846         // Test that in case of channel closure, we detect the state of output and claim HTLC
4847         // on downstream peer's remote commitment tx.
4848         // First, have C claim an HTLC against its own latest commitment transaction.
4849         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4850         // channel.
4851         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4852         // gets broadcast.
4853
4854         let chanmon_cfgs = create_chanmon_cfgs(3);
4855         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4856         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4857         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4858
4859         // Create some initial channels
4860         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4861         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4862
4863         // Ensure all nodes are at the same height
4864         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4865         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4866         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4867         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4868
4869         // Rebalance the network a bit by relaying one payment through all the channels ...
4870         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4871         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4872
4873         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4874         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4875         check_spends!(commitment_tx[0], chan_2.3);
4876         nodes[2].node.claim_funds(payment_preimage);
4877         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4878         check_added_monitors!(nodes[2], 1);
4879         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4880         assert!(updates.update_add_htlcs.is_empty());
4881         assert!(updates.update_fail_htlcs.is_empty());
4882         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4883         assert!(updates.update_fail_malformed_htlcs.is_empty());
4884
4885         mine_transaction(&nodes[2], &commitment_tx[0]);
4886         check_closed_broadcast!(nodes[2], true);
4887         check_added_monitors!(nodes[2], 1);
4888         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4889
4890         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4891         assert_eq!(c_txn.len(), 1);
4892         check_spends!(c_txn[0], commitment_tx[0]);
4893         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4894         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4895         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4896
4897         // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
4898         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4899         check_added_monitors!(nodes[1], 1);
4900         let events = nodes[1].node.get_and_clear_pending_events();
4901         assert_eq!(events.len(), 2);
4902         match events[0] {
4903                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4904                 _ => panic!("Unexpected event"),
4905         }
4906         match events[1] {
4907                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4908                         assert_eq!(fee_earned_msat, Some(1000));
4909                         assert_eq!(prev_channel_id, Some(chan_1.2));
4910                         assert_eq!(claim_from_onchain_tx, true);
4911                         assert_eq!(next_channel_id, Some(chan_2.2));
4912                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4913                 },
4914                 _ => panic!("Unexpected event"),
4915         }
4916         check_added_monitors!(nodes[1], 1);
4917         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4918         assert_eq!(msg_events.len(), 3);
4919         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4920         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4921
4922         match nodes_2_event {
4923                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4924                 _ => panic!("Unexpected event"),
4925         }
4926
4927         match nodes_0_event {
4928                 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
4929                         assert!(update_add_htlcs.is_empty());
4930                         assert!(update_fail_htlcs.is_empty());
4931                         assert_eq!(update_fulfill_htlcs.len(), 1);
4932                         assert!(update_fail_malformed_htlcs.is_empty());
4933                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4934                 },
4935                 _ => panic!("Unexpected event"),
4936         };
4937
4938         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4939         match msg_events[0] {
4940                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4941                 _ => panic!("Unexpected event"),
4942         }
4943
4944         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4945         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4946         mine_transaction(&nodes[1], &commitment_tx[0]);
4947         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4948         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4949         // ChannelMonitor: HTLC-Success tx
4950         assert_eq!(b_txn.len(), 1);
4951         check_spends!(b_txn[0], commitment_tx[0]);
4952         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4953         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4954         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4955
4956         check_closed_broadcast!(nodes[1], true);
4957         check_added_monitors!(nodes[1], 1);
4958 }
4959
4960 #[test]
4961 fn test_duplicate_payment_hash_one_failure_one_success() {
4962         // Topology : A --> B --> C --> D
4963         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4964         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4965         // we forward one of the payments onwards to D.
4966         let chanmon_cfgs = create_chanmon_cfgs(4);
4967         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4968         // When this test was written, the default base fee floated based on the HTLC count.
4969         // It is now fixed, so we simply set the fee to the expected value here.
4970         let mut config = test_default_channel_config();
4971         config.channel_config.forwarding_fee_base_msat = 196;
4972         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4973                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4974         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4975
4976         create_announced_chan_between_nodes(&nodes, 0, 1);
4977         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4978         create_announced_chan_between_nodes(&nodes, 2, 3);
4979
4980         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4981         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4982         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4983         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4984         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4985
4986         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4987
4988         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4989         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4990         // script push size limit so that the below script length checks match
4991         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4992         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4993                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4994         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4995         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4996
4997         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4998         assert_eq!(commitment_txn[0].input.len(), 1);
4999         check_spends!(commitment_txn[0], chan_2.3);
5000
5001         mine_transaction(&nodes[1], &commitment_txn[0]);
5002         check_closed_broadcast!(nodes[1], true);
5003         check_added_monitors!(nodes[1], 1);
5004         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5005         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5006
5007         let htlc_timeout_tx;
5008         { // Extract one of the two HTLC-Timeout transaction
5009                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5010                 // ChannelMonitor: timeout tx * 2-or-3
5011                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5012
5013                 check_spends!(node_txn[0], commitment_txn[0]);
5014                 assert_eq!(node_txn[0].input.len(), 1);
5015                 assert_eq!(node_txn[0].output.len(), 1);
5016
5017                 if node_txn.len() > 2 {
5018                         check_spends!(node_txn[1], commitment_txn[0]);
5019                         assert_eq!(node_txn[1].input.len(), 1);
5020                         assert_eq!(node_txn[1].output.len(), 1);
5021                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5022
5023                         check_spends!(node_txn[2], commitment_txn[0]);
5024                         assert_eq!(node_txn[2].input.len(), 1);
5025                         assert_eq!(node_txn[2].output.len(), 1);
5026                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5027                 } else {
5028                         check_spends!(node_txn[1], commitment_txn[0]);
5029                         assert_eq!(node_txn[1].input.len(), 1);
5030                         assert_eq!(node_txn[1].output.len(), 1);
5031                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5032                 }
5033
5034                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5035                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5036                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5037                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5038                 if node_txn.len() > 2 {
5039                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5040                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5041                 } else {
5042                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5043                 }
5044         }
5045
5046         nodes[2].node.claim_funds(our_payment_preimage);
5047         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5048
5049         mine_transaction(&nodes[2], &commitment_txn[0]);
5050         check_added_monitors!(nodes[2], 2);
5051         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5052         let events = nodes[2].node.get_and_clear_pending_msg_events();
5053         match events[0] {
5054                 MessageSendEvent::UpdateHTLCs { .. } => {},
5055                 _ => panic!("Unexpected event"),
5056         }
5057         match events[1] {
5058                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5059                 _ => panic!("Unexepected event"),
5060         }
5061         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5062         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5063         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5064         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5065         assert_eq!(htlc_success_txn[0].input.len(), 1);
5066         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5067         assert_eq!(htlc_success_txn[1].input.len(), 1);
5068         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5069         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5070         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5071
5072         mine_transaction(&nodes[1], &htlc_timeout_tx);
5073         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5074         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
5075         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5076         assert!(htlc_updates.update_add_htlcs.is_empty());
5077         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5078         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5079         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5080         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5081         check_added_monitors!(nodes[1], 1);
5082
5083         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5084         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5085         {
5086                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5087         }
5088         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5089
5090         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5091         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5092         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5093         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5094         assert!(updates.update_add_htlcs.is_empty());
5095         assert!(updates.update_fail_htlcs.is_empty());
5096         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5097         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5098         assert!(updates.update_fail_malformed_htlcs.is_empty());
5099         check_added_monitors!(nodes[1], 1);
5100
5101         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5102         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5103         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5104 }
5105
5106 #[test]
5107 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5108         let chanmon_cfgs = create_chanmon_cfgs(2);
5109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5110         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5111         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5112
5113         // Create some initial channels
5114         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5115
5116         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5117         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5118         assert_eq!(local_txn.len(), 1);
5119         assert_eq!(local_txn[0].input.len(), 1);
5120         check_spends!(local_txn[0], chan_1.3);
5121
5122         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5123         nodes[1].node.claim_funds(payment_preimage);
5124         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5125         check_added_monitors!(nodes[1], 1);
5126
5127         mine_transaction(&nodes[1], &local_txn[0]);
5128         check_added_monitors!(nodes[1], 1);
5129         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5130         let events = nodes[1].node.get_and_clear_pending_msg_events();
5131         match events[0] {
5132                 MessageSendEvent::UpdateHTLCs { .. } => {},
5133                 _ => panic!("Unexpected event"),
5134         }
5135         match events[1] {
5136                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5137                 _ => panic!("Unexepected event"),
5138         }
5139         let node_tx = {
5140                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5141                 assert_eq!(node_txn.len(), 1);
5142                 assert_eq!(node_txn[0].input.len(), 1);
5143                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5144                 check_spends!(node_txn[0], local_txn[0]);
5145                 node_txn[0].clone()
5146         };
5147
5148         mine_transaction(&nodes[1], &node_tx);
5149         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5150
5151         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5152         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5153         assert_eq!(spend_txn.len(), 1);
5154         assert_eq!(spend_txn[0].input.len(), 1);
5155         check_spends!(spend_txn[0], node_tx);
5156         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5157 }
5158
5159 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5160         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5161         // unrevoked commitment transaction.
5162         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5163         // a remote RAA before they could be failed backwards (and combinations thereof).
5164         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5165         // use the same payment hashes.
5166         // Thus, we use a six-node network:
5167         //
5168         // A \         / E
5169         //    - C - D -
5170         // B /         \ F
5171         // And test where C fails back to A/B when D announces its latest commitment transaction
5172         let chanmon_cfgs = create_chanmon_cfgs(6);
5173         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5174         // When this test was written, the default base fee floated based on the HTLC count.
5175         // It is now fixed, so we simply set the fee to the expected value here.
5176         let mut config = test_default_channel_config();
5177         config.channel_config.forwarding_fee_base_msat = 196;
5178         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5179                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5180         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5181
5182         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5183         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5184         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5185         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5186         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5187
5188         // Rebalance and check output sanity...
5189         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5190         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5191         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5192
5193         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5194                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5195         // 0th HTLC:
5196         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5197         // 1st HTLC:
5198         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5199         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5200         // 2nd HTLC:
5201         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5202         // 3rd HTLC:
5203         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5204         // 4th HTLC:
5205         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5206         // 5th HTLC:
5207         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5208         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5209         // 6th HTLC:
5210         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
5211         // 7th HTLC:
5212         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
5213
5214         // 8th HTLC:
5215         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5216         // 9th HTLC:
5217         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5218         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5219
5220         // 10th HTLC:
5221         let (_, payment_hash_6, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5222         // 11th HTLC:
5223         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5224         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
5225
5226         // Double-check that six of the new HTLC were added
5227         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5228         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5229         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5230         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5231
5232         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5233         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5234         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5235         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5236         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5237         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5238         check_added_monitors!(nodes[4], 0);
5239
5240         let failed_destinations = vec![
5241                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5242                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5243                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5244                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5245         ];
5246         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5247         check_added_monitors!(nodes[4], 1);
5248
5249         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5250         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5251         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5252         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5253         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5254         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5255
5256         // Fail 3rd below-dust and 7th above-dust HTLCs
5257         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5258         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5259         check_added_monitors!(nodes[5], 0);
5260
5261         let failed_destinations_2 = vec![
5262                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5263                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5264         ];
5265         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5266         check_added_monitors!(nodes[5], 1);
5267
5268         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5269         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5270         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5271         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5272
5273         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5274
5275         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5276         let failed_destinations_3 = vec![
5277                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5278                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5279                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5280                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5281                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5282                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5283         ];
5284         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5285         check_added_monitors!(nodes[3], 1);
5286         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5287         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5288         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5289         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5290         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5291         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5292         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5293         if deliver_last_raa {
5294                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5295         } else {
5296                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5297         }
5298
5299         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5300         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5301         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5302         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5303         //
5304         // We now broadcast the latest commitment transaction, which *should* result in failures for
5305         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5306         // the non-broadcast above-dust HTLCs.
5307         //
5308         // Alternatively, we may broadcast the previous commitment transaction, which should only
5309         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5310         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5311
5312         if announce_latest {
5313                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5314         } else {
5315                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5316         }
5317         let events = nodes[2].node.get_and_clear_pending_events();
5318         let close_event = if deliver_last_raa {
5319                 assert_eq!(events.len(), 2 + 6);
5320                 events.last().clone().unwrap()
5321         } else {
5322                 assert_eq!(events.len(), 1);
5323                 events.last().clone().unwrap()
5324         };
5325         match close_event {
5326                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5327                 _ => panic!("Unexpected event"),
5328         }
5329
5330         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5331         check_closed_broadcast!(nodes[2], true);
5332         if deliver_last_raa {
5333                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5334
5335                 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5336                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5337         } else {
5338                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5339                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5340                 } else {
5341                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5342                 };
5343
5344                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5345         }
5346         check_added_monitors!(nodes[2], 3);
5347
5348         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5349         assert_eq!(cs_msgs.len(), 2);
5350         let mut a_done = false;
5351         for msg in cs_msgs {
5352                 match msg {
5353                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5354                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5355                                 // should be failed-backwards here.
5356                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5357                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5358                                         for htlc in &updates.update_fail_htlcs {
5359                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5360                                         }
5361                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5362                                         assert!(!a_done);
5363                                         a_done = true;
5364                                         &nodes[0]
5365                                 } else {
5366                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5367                                         for htlc in &updates.update_fail_htlcs {
5368                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5369                                         }
5370                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5371                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5372                                         &nodes[1]
5373                                 };
5374                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5375                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5376                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5377                                 if announce_latest {
5378                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5379                                         if *node_id == nodes[0].node.get_our_node_id() {
5380                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5381                                         }
5382                                 }
5383                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5384                         },
5385                         _ => panic!("Unexpected event"),
5386                 }
5387         }
5388
5389         let as_events = nodes[0].node.get_and_clear_pending_events();
5390         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5391         let mut as_failds = HashSet::new();
5392         let mut as_updates = 0;
5393         for event in as_events.iter() {
5394                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5395                         assert!(as_failds.insert(*payment_hash));
5396                         if *payment_hash != payment_hash_2 {
5397                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5398                         } else {
5399                                 assert!(!payment_failed_permanently);
5400                         }
5401                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5402                                 as_updates += 1;
5403                         }
5404                 } else if let &Event::PaymentFailed { .. } = event {
5405                 } else { panic!("Unexpected event"); }
5406         }
5407         assert!(as_failds.contains(&payment_hash_1));
5408         assert!(as_failds.contains(&payment_hash_2));
5409         if announce_latest {
5410                 assert!(as_failds.contains(&payment_hash_3));
5411                 assert!(as_failds.contains(&payment_hash_5));
5412         }
5413         assert!(as_failds.contains(&payment_hash_6));
5414
5415         let bs_events = nodes[1].node.get_and_clear_pending_events();
5416         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5417         let mut bs_failds = HashSet::new();
5418         let mut bs_updates = 0;
5419         for event in bs_events.iter() {
5420                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5421                         assert!(bs_failds.insert(*payment_hash));
5422                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5423                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5424                         } else {
5425                                 assert!(!payment_failed_permanently);
5426                         }
5427                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5428                                 bs_updates += 1;
5429                         }
5430                 } else if let &Event::PaymentFailed { .. } = event {
5431                 } else { panic!("Unexpected event"); }
5432         }
5433         assert!(bs_failds.contains(&payment_hash_1));
5434         assert!(bs_failds.contains(&payment_hash_2));
5435         if announce_latest {
5436                 assert!(bs_failds.contains(&payment_hash_4));
5437         }
5438         assert!(bs_failds.contains(&payment_hash_5));
5439
5440         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5441         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5442         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5443         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5444         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5445         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5446 }
5447
5448 #[test]
5449 fn test_fail_backwards_latest_remote_announce_a() {
5450         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5451 }
5452
5453 #[test]
5454 fn test_fail_backwards_latest_remote_announce_b() {
5455         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5456 }
5457
5458 #[test]
5459 fn test_fail_backwards_previous_remote_announce() {
5460         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5461         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5462         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5463 }
5464
5465 #[test]
5466 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5467         let chanmon_cfgs = create_chanmon_cfgs(2);
5468         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5469         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5470         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5471
5472         // Create some initial channels
5473         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5474
5475         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5476         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5477         assert_eq!(local_txn[0].input.len(), 1);
5478         check_spends!(local_txn[0], chan_1.3);
5479
5480         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5481         mine_transaction(&nodes[0], &local_txn[0]);
5482         check_closed_broadcast!(nodes[0], true);
5483         check_added_monitors!(nodes[0], 1);
5484         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5485         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5486
5487         let htlc_timeout = {
5488                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5489                 assert_eq!(node_txn.len(), 1);
5490                 assert_eq!(node_txn[0].input.len(), 1);
5491                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5492                 check_spends!(node_txn[0], local_txn[0]);
5493                 node_txn[0].clone()
5494         };
5495
5496         mine_transaction(&nodes[0], &htlc_timeout);
5497         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5498         expect_payment_failed!(nodes[0], our_payment_hash, false);
5499
5500         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5501         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5502         assert_eq!(spend_txn.len(), 3);
5503         check_spends!(spend_txn[0], local_txn[0]);
5504         assert_eq!(spend_txn[1].input.len(), 1);
5505         check_spends!(spend_txn[1], htlc_timeout);
5506         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5507         assert_eq!(spend_txn[2].input.len(), 2);
5508         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5509         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5510                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5511 }
5512
5513 #[test]
5514 fn test_key_derivation_params() {
5515         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5516         // manager rotation to test that `channel_keys_id` returned in
5517         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5518         // then derive a `delayed_payment_key`.
5519
5520         let chanmon_cfgs = create_chanmon_cfgs(3);
5521
5522         // We manually create the node configuration to backup the seed.
5523         let seed = [42; 32];
5524         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5525         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5526         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5527         let scorer = RwLock::new(test_utils::TestScorer::new());
5528         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5529         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5530         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5531         node_cfgs.remove(0);
5532         node_cfgs.insert(0, node);
5533
5534         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5535         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5536
5537         // Create some initial channels
5538         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5539         // for node 0
5540         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5541         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5542         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5543
5544         // Ensure all nodes are at the same height
5545         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5546         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5547         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5548         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5549
5550         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5551         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5552         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5553         assert_eq!(local_txn_1[0].input.len(), 1);
5554         check_spends!(local_txn_1[0], chan_1.3);
5555
5556         // We check funding pubkey are unique
5557         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5558         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5559         if from_0_funding_key_0 == from_1_funding_key_0
5560             || from_0_funding_key_0 == from_1_funding_key_1
5561             || from_0_funding_key_1 == from_1_funding_key_0
5562             || from_0_funding_key_1 == from_1_funding_key_1 {
5563                 panic!("Funding pubkeys aren't unique");
5564         }
5565
5566         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5567         mine_transaction(&nodes[0], &local_txn_1[0]);
5568         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5569         check_closed_broadcast!(nodes[0], true);
5570         check_added_monitors!(nodes[0], 1);
5571         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5572
5573         let htlc_timeout = {
5574                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5575                 assert_eq!(node_txn.len(), 1);
5576                 assert_eq!(node_txn[0].input.len(), 1);
5577                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5578                 check_spends!(node_txn[0], local_txn_1[0]);
5579                 node_txn[0].clone()
5580         };
5581
5582         mine_transaction(&nodes[0], &htlc_timeout);
5583         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5584         expect_payment_failed!(nodes[0], our_payment_hash, false);
5585
5586         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5587         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5588         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5589         assert_eq!(spend_txn.len(), 3);
5590         check_spends!(spend_txn[0], local_txn_1[0]);
5591         assert_eq!(spend_txn[1].input.len(), 1);
5592         check_spends!(spend_txn[1], htlc_timeout);
5593         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5594         assert_eq!(spend_txn[2].input.len(), 2);
5595         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5596         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5597                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5598 }
5599
5600 #[test]
5601 fn test_static_output_closing_tx() {
5602         let chanmon_cfgs = create_chanmon_cfgs(2);
5603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5606
5607         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5608
5609         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5610         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5611
5612         mine_transaction(&nodes[0], &closing_tx);
5613         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5614         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5615
5616         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5617         assert_eq!(spend_txn.len(), 1);
5618         check_spends!(spend_txn[0], closing_tx);
5619
5620         mine_transaction(&nodes[1], &closing_tx);
5621         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5622         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5623
5624         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5625         assert_eq!(spend_txn.len(), 1);
5626         check_spends!(spend_txn[0], closing_tx);
5627 }
5628
5629 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5630         let chanmon_cfgs = create_chanmon_cfgs(2);
5631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5634         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5635
5636         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5637
5638         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5639         // present in B's local commitment transaction, but none of A's commitment transactions.
5640         nodes[1].node.claim_funds(payment_preimage);
5641         check_added_monitors!(nodes[1], 1);
5642         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5643
5644         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5645         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5646         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5647
5648         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5649         check_added_monitors!(nodes[0], 1);
5650         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5651         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5652         check_added_monitors!(nodes[1], 1);
5653
5654         let starting_block = nodes[1].best_block_info();
5655         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5656         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5657                 connect_block(&nodes[1], &block);
5658                 block.header.prev_blockhash = block.block_hash();
5659         }
5660         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5661         check_closed_broadcast!(nodes[1], true);
5662         check_added_monitors!(nodes[1], 1);
5663         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5664 }
5665
5666 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5667         let chanmon_cfgs = create_chanmon_cfgs(2);
5668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5670         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5671         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5672
5673         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5674         nodes[0].node.send_payment_with_route(&route, payment_hash,
5675                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5676         check_added_monitors!(nodes[0], 1);
5677
5678         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5679
5680         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5681         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5682         // to "time out" the HTLC.
5683
5684         let starting_block = nodes[1].best_block_info();
5685         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5686
5687         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5688                 connect_block(&nodes[0], &block);
5689                 block.header.prev_blockhash = block.block_hash();
5690         }
5691         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5692         check_closed_broadcast!(nodes[0], true);
5693         check_added_monitors!(nodes[0], 1);
5694         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5695 }
5696
5697 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5698         let chanmon_cfgs = create_chanmon_cfgs(3);
5699         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5700         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5701         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5702         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5703
5704         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5705         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5706         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5707         // actually revoked.
5708         let htlc_value = if use_dust { 50000 } else { 3000000 };
5709         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5710         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5711         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5712         check_added_monitors!(nodes[1], 1);
5713
5714         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5715         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5716         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5717         check_added_monitors!(nodes[0], 1);
5718         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5719         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5720         check_added_monitors!(nodes[1], 1);
5721         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5722         check_added_monitors!(nodes[1], 1);
5723         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5724
5725         if check_revoke_no_close {
5726                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5727                 check_added_monitors!(nodes[0], 1);
5728         }
5729
5730         let starting_block = nodes[1].best_block_info();
5731         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5732         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5733                 connect_block(&nodes[0], &block);
5734                 block.header.prev_blockhash = block.block_hash();
5735         }
5736         if !check_revoke_no_close {
5737                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5738                 check_closed_broadcast!(nodes[0], true);
5739                 check_added_monitors!(nodes[0], 1);
5740                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5741         } else {
5742                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5743         }
5744 }
5745
5746 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5747 // There are only a few cases to test here:
5748 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5749 //    broadcastable commitment transactions result in channel closure,
5750 //  * its included in an unrevoked-but-previous remote commitment transaction,
5751 //  * its included in the latest remote or local commitment transactions.
5752 // We test each of the three possible commitment transactions individually and use both dust and
5753 // non-dust HTLCs.
5754 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5755 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5756 // tested for at least one of the cases in other tests.
5757 #[test]
5758 fn htlc_claim_single_commitment_only_a() {
5759         do_htlc_claim_local_commitment_only(true);
5760         do_htlc_claim_local_commitment_only(false);
5761
5762         do_htlc_claim_current_remote_commitment_only(true);
5763         do_htlc_claim_current_remote_commitment_only(false);
5764 }
5765
5766 #[test]
5767 fn htlc_claim_single_commitment_only_b() {
5768         do_htlc_claim_previous_remote_commitment_only(true, false);
5769         do_htlc_claim_previous_remote_commitment_only(false, false);
5770         do_htlc_claim_previous_remote_commitment_only(true, true);
5771         do_htlc_claim_previous_remote_commitment_only(false, true);
5772 }
5773
5774 #[test]
5775 #[should_panic]
5776 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5777         let chanmon_cfgs = create_chanmon_cfgs(2);
5778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5780         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5781         // Force duplicate randomness for every get-random call
5782         for node in nodes.iter() {
5783                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5784         }
5785
5786         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5787         let channel_value_satoshis=10000;
5788         let push_msat=10001;
5789         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5790         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5791         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5792         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5793
5794         // Create a second channel with the same random values. This used to panic due to a colliding
5795         // channel_id, but now panics due to a colliding outbound SCID alias.
5796         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5797 }
5798
5799 #[test]
5800 fn bolt2_open_channel_sending_node_checks_part2() {
5801         let chanmon_cfgs = create_chanmon_cfgs(2);
5802         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5803         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5804         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5805
5806         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5807         let channel_value_satoshis=2^24;
5808         let push_msat=10001;
5809         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5810
5811         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5812         let channel_value_satoshis=10000;
5813         // Test when push_msat is equal to 1000 * funding_satoshis.
5814         let push_msat=1000*channel_value_satoshis+1;
5815         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5816
5817         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5818         let channel_value_satoshis=10000;
5819         let push_msat=10001;
5820         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5821         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5822         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5823
5824         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5825         // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5826         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5827
5828         // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5829         assert!(BREAKDOWN_TIMEOUT>0);
5830         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5831
5832         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5833         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5834         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5835
5836         // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5837         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5838         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5839         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5840         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5841         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5842 }
5843
5844 #[test]
5845 fn bolt2_open_channel_sane_dust_limit() {
5846         let chanmon_cfgs = create_chanmon_cfgs(2);
5847         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5848         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5849         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5850
5851         let channel_value_satoshis=1000000;
5852         let push_msat=10001;
5853         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5854         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5855         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5856         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5857
5858         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5859         let events = nodes[1].node.get_and_clear_pending_msg_events();
5860         let err_msg = match events[0] {
5861                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5862                         msg.clone()
5863                 },
5864                 _ => panic!("Unexpected event"),
5865         };
5866         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5867 }
5868
5869 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5870 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5871 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5872 // is no longer affordable once it's freed.
5873 #[test]
5874 fn test_fail_holding_cell_htlc_upon_free() {
5875         let chanmon_cfgs = create_chanmon_cfgs(2);
5876         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5877         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5878         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5879         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5880
5881         // First nodes[0] generates an update_fee, setting the channel's
5882         // pending_update_fee.
5883         {
5884                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5885                 *feerate_lock += 20;
5886         }
5887         nodes[0].node.timer_tick_occurred();
5888         check_added_monitors!(nodes[0], 1);
5889
5890         let events = nodes[0].node.get_and_clear_pending_msg_events();
5891         assert_eq!(events.len(), 1);
5892         let (update_msg, commitment_signed) = match events[0] {
5893                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5894                         (update_fee.as_ref(), commitment_signed)
5895                 },
5896                 _ => panic!("Unexpected event"),
5897         };
5898
5899         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5900
5901         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5902         let channel_reserve = chan_stat.channel_reserve_msat;
5903         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5904         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5905
5906         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5907         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5908         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5909
5910         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5911         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5912                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5913         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5914         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5915
5916         // Flush the pending fee update.
5917         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5918         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5919         check_added_monitors!(nodes[1], 1);
5920         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5921         check_added_monitors!(nodes[0], 1);
5922
5923         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5924         // HTLC, but now that the fee has been raised the payment will now fail, causing
5925         // us to surface its failure to the user.
5926         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5927         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5928         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5929
5930         // Check that the payment failed to be sent out.
5931         let events = nodes[0].node.get_and_clear_pending_events();
5932         assert_eq!(events.len(), 2);
5933         match &events[0] {
5934                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5935                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5936                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5937                         assert_eq!(*payment_failed_permanently, false);
5938                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5939                 },
5940                 _ => panic!("Unexpected event"),
5941         }
5942         match &events[1] {
5943                 &Event::PaymentFailed { ref payment_hash, .. } => {
5944                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5945                 },
5946                 _ => panic!("Unexpected event"),
5947         }
5948 }
5949
5950 // Test that if multiple HTLCs are released from the holding cell and one is
5951 // valid but the other is no longer valid upon release, the valid HTLC can be
5952 // successfully completed while the other one fails as expected.
5953 #[test]
5954 fn test_free_and_fail_holding_cell_htlcs() {
5955         let chanmon_cfgs = create_chanmon_cfgs(2);
5956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5958         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5959         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5960
5961         // First nodes[0] generates an update_fee, setting the channel's
5962         // pending_update_fee.
5963         {
5964                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5965                 *feerate_lock += 200;
5966         }
5967         nodes[0].node.timer_tick_occurred();
5968         check_added_monitors!(nodes[0], 1);
5969
5970         let events = nodes[0].node.get_and_clear_pending_msg_events();
5971         assert_eq!(events.len(), 1);
5972         let (update_msg, commitment_signed) = match events[0] {
5973                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5974                         (update_fee.as_ref(), commitment_signed)
5975                 },
5976                 _ => panic!("Unexpected event"),
5977         };
5978
5979         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5980
5981         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5982         let channel_reserve = chan_stat.channel_reserve_msat;
5983         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5984         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5985
5986         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5987         let amt_1 = 20000;
5988         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5989         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5990         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5991
5992         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5993         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5994                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5995         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5996         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5997         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5998         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5999                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6000         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6001         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6002
6003         // Flush the pending fee update.
6004         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6005         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6006         check_added_monitors!(nodes[1], 1);
6007         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6008         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6009         check_added_monitors!(nodes[0], 2);
6010
6011         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6012         // but now that the fee has been raised the second payment will now fail, causing us
6013         // to surface its failure to the user. The first payment should succeed.
6014         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6015         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6016         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6017
6018         // Check that the second payment failed to be sent out.
6019         let events = nodes[0].node.get_and_clear_pending_events();
6020         assert_eq!(events.len(), 2);
6021         match &events[0] {
6022                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6023                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6024                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6025                         assert_eq!(*payment_failed_permanently, false);
6026                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6027                 },
6028                 _ => panic!("Unexpected event"),
6029         }
6030         match &events[1] {
6031                 &Event::PaymentFailed { ref payment_hash, .. } => {
6032                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6033                 },
6034                 _ => panic!("Unexpected event"),
6035         }
6036
6037         // Complete the first payment and the RAA from the fee update.
6038         let (payment_event, send_raa_event) = {
6039                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6040                 assert_eq!(msgs.len(), 2);
6041                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6042         };
6043         let raa = match send_raa_event {
6044                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6045                 _ => panic!("Unexpected event"),
6046         };
6047         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6048         check_added_monitors!(nodes[1], 1);
6049         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6050         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6051         let events = nodes[1].node.get_and_clear_pending_events();
6052         assert_eq!(events.len(), 1);
6053         match events[0] {
6054                 Event::PendingHTLCsForwardable { .. } => {},
6055                 _ => panic!("Unexpected event"),
6056         }
6057         nodes[1].node.process_pending_htlc_forwards();
6058         let events = nodes[1].node.get_and_clear_pending_events();
6059         assert_eq!(events.len(), 1);
6060         match events[0] {
6061                 Event::PaymentClaimable { .. } => {},
6062                 _ => panic!("Unexpected event"),
6063         }
6064         nodes[1].node.claim_funds(payment_preimage_1);
6065         check_added_monitors!(nodes[1], 1);
6066         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6067
6068         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6069         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6070         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6071         expect_payment_sent!(nodes[0], payment_preimage_1);
6072 }
6073
6074 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6075 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6076 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6077 // once it's freed.
6078 #[test]
6079 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6080         let chanmon_cfgs = create_chanmon_cfgs(3);
6081         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6082         // Avoid having to include routing fees in calculations
6083         let mut config = test_default_channel_config();
6084         config.channel_config.forwarding_fee_base_msat = 0;
6085         config.channel_config.forwarding_fee_proportional_millionths = 0;
6086         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6087         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6088         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6089         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6090
6091         // First nodes[1] generates an update_fee, setting the channel's
6092         // pending_update_fee.
6093         {
6094                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6095                 *feerate_lock += 20;
6096         }
6097         nodes[1].node.timer_tick_occurred();
6098         check_added_monitors!(nodes[1], 1);
6099
6100         let events = nodes[1].node.get_and_clear_pending_msg_events();
6101         assert_eq!(events.len(), 1);
6102         let (update_msg, commitment_signed) = match events[0] {
6103                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6104                         (update_fee.as_ref(), commitment_signed)
6105                 },
6106                 _ => panic!("Unexpected event"),
6107         };
6108
6109         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6110
6111         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6112         let channel_reserve = chan_stat.channel_reserve_msat;
6113         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6114         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6115
6116         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6117         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6118         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6119         let payment_event = {
6120                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6121                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6122                 check_added_monitors!(nodes[0], 1);
6123
6124                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6125                 assert_eq!(events.len(), 1);
6126
6127                 SendEvent::from_event(events.remove(0))
6128         };
6129         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6130         check_added_monitors!(nodes[1], 0);
6131         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6132         expect_pending_htlcs_forwardable!(nodes[1]);
6133
6134         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6135         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6136
6137         // Flush the pending fee update.
6138         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6139         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6140         check_added_monitors!(nodes[2], 1);
6141         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6142         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6143         check_added_monitors!(nodes[1], 2);
6144
6145         // A final RAA message is generated to finalize the fee update.
6146         let events = nodes[1].node.get_and_clear_pending_msg_events();
6147         assert_eq!(events.len(), 1);
6148
6149         let raa_msg = match &events[0] {
6150                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6151                         msg.clone()
6152                 },
6153                 _ => panic!("Unexpected event"),
6154         };
6155
6156         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6157         check_added_monitors!(nodes[2], 1);
6158         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6159
6160         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6161         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6162         assert_eq!(process_htlc_forwards_event.len(), 2);
6163         match &process_htlc_forwards_event[0] {
6164                 &Event::PendingHTLCsForwardable { .. } => {},
6165                 _ => panic!("Unexpected event"),
6166         }
6167
6168         // In response, we call ChannelManager's process_pending_htlc_forwards
6169         nodes[1].node.process_pending_htlc_forwards();
6170         check_added_monitors!(nodes[1], 1);
6171
6172         // This causes the HTLC to be failed backwards.
6173         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6174         assert_eq!(fail_event.len(), 1);
6175         let (fail_msg, commitment_signed) = match &fail_event[0] {
6176                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6177                         assert_eq!(updates.update_add_htlcs.len(), 0);
6178                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6179                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6180                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6181                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6182                 },
6183                 _ => panic!("Unexpected event"),
6184         };
6185
6186         // Pass the failure messages back to nodes[0].
6187         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6188         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6189
6190         // Complete the HTLC failure+removal process.
6191         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6192         check_added_monitors!(nodes[0], 1);
6193         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6194         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6195         check_added_monitors!(nodes[1], 2);
6196         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6197         assert_eq!(final_raa_event.len(), 1);
6198         let raa = match &final_raa_event[0] {
6199                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6200                 _ => panic!("Unexpected event"),
6201         };
6202         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6203         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6204         check_added_monitors!(nodes[0], 1);
6205 }
6206
6207 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6208 // 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.
6209 //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.
6210
6211 #[test]
6212 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6213         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6214         let chanmon_cfgs = create_chanmon_cfgs(2);
6215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6217         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6218         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6219
6220         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6221         route.paths[0].hops[0].fee_msat = 100;
6222
6223         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6224                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6225                 ), true, APIError::ChannelUnavailable { .. }, {});
6226         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6227 }
6228
6229 #[test]
6230 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6231         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6232         let chanmon_cfgs = create_chanmon_cfgs(2);
6233         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6234         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6235         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6236         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6237
6238         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6239         route.paths[0].hops[0].fee_msat = 0;
6240         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6241                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6242                 true, APIError::ChannelUnavailable { ref err },
6243                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6244
6245         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6246         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6247 }
6248
6249 #[test]
6250 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6251         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6252         let chanmon_cfgs = create_chanmon_cfgs(2);
6253         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6254         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6255         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6256         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6257
6258         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6259         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6260                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6261         check_added_monitors!(nodes[0], 1);
6262         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6263         updates.update_add_htlcs[0].amount_msat = 0;
6264
6265         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6266         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6267         check_closed_broadcast!(nodes[1], true).unwrap();
6268         check_added_monitors!(nodes[1], 1);
6269         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6270                 [nodes[0].node.get_our_node_id()], 100000);
6271 }
6272
6273 #[test]
6274 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6275         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6276         //It is enforced when constructing a route.
6277         let chanmon_cfgs = create_chanmon_cfgs(2);
6278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6280         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6281         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6282
6283         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6284                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6285         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6286         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6287         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6288                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6289                 ), true, APIError::InvalidRoute { ref err },
6290                 assert_eq!(err, &"Channel CLTV overflowed?"));
6291 }
6292
6293 #[test]
6294 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6295         //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.
6296         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6297         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6298         let chanmon_cfgs = create_chanmon_cfgs(2);
6299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6301         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6302         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6303         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6304                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6305
6306         // Fetch a route in advance as we will be unable to once we're unable to send.
6307         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6308         for i in 0..max_accepted_htlcs {
6309                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6310                 let payment_event = {
6311                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6312                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6313                         check_added_monitors!(nodes[0], 1);
6314
6315                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6316                         assert_eq!(events.len(), 1);
6317                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6318                                 assert_eq!(htlcs[0].htlc_id, i);
6319                         } else {
6320                                 assert!(false);
6321                         }
6322                         SendEvent::from_event(events.remove(0))
6323                 };
6324                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6325                 check_added_monitors!(nodes[1], 0);
6326                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6327
6328                 expect_pending_htlcs_forwardable!(nodes[1]);
6329                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6330         }
6331         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6332                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6333                 ), true, APIError::ChannelUnavailable { .. }, {});
6334
6335         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6336 }
6337
6338 #[test]
6339 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6340         //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.
6341         let chanmon_cfgs = create_chanmon_cfgs(2);
6342         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6343         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6344         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6345         let channel_value = 100000;
6346         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6347         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6348
6349         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6350
6351         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6352         // Manually create a route over our max in flight (which our router normally automatically
6353         // limits us to.
6354         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6355         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6356                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6357                 ), true, APIError::ChannelUnavailable { .. }, {});
6358         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6359
6360         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6361 }
6362
6363 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6364 #[test]
6365 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6366         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6367         let chanmon_cfgs = create_chanmon_cfgs(2);
6368         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6369         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6370         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6371         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6372         let htlc_minimum_msat: u64;
6373         {
6374                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6375                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6376                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6377                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6378         }
6379
6380         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6381         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6382                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6383         check_added_monitors!(nodes[0], 1);
6384         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6385         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6386         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6387         assert!(nodes[1].node.list_channels().is_empty());
6388         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6389         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()));
6390         check_added_monitors!(nodes[1], 1);
6391         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6392 }
6393
6394 #[test]
6395 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6396         //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
6397         let chanmon_cfgs = create_chanmon_cfgs(2);
6398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6400         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6401         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6402
6403         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6404         let channel_reserve = chan_stat.channel_reserve_msat;
6405         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6406         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6407         // The 2* and +1 are for the fee spike reserve.
6408         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6409
6410         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6411         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6412         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6413                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6414         check_added_monitors!(nodes[0], 1);
6415         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6416
6417         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6418         // at this time channel-initiatee receivers are not required to enforce that senders
6419         // respect the fee_spike_reserve.
6420         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6421         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6422
6423         assert!(nodes[1].node.list_channels().is_empty());
6424         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6425         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6426         check_added_monitors!(nodes[1], 1);
6427         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6428 }
6429
6430 #[test]
6431 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6432         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6433         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6434         let chanmon_cfgs = create_chanmon_cfgs(2);
6435         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6436         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6437         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6438         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6439
6440         let send_amt = 3999999;
6441         let (mut route, our_payment_hash, _, our_payment_secret) =
6442                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6443         route.paths[0].hops[0].fee_msat = send_amt;
6444         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6445         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6446         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6447         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6448                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6449         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6450
6451         let mut msg = msgs::UpdateAddHTLC {
6452                 channel_id: chan.2,
6453                 htlc_id: 0,
6454                 amount_msat: 1000,
6455                 payment_hash: our_payment_hash,
6456                 cltv_expiry: htlc_cltv,
6457                 onion_routing_packet: onion_packet.clone(),
6458                 skimmed_fee_msat: None,
6459         };
6460
6461         for i in 0..50 {
6462                 msg.htlc_id = i as u64;
6463                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6464         }
6465         msg.htlc_id = (50) as u64;
6466         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6467
6468         assert!(nodes[1].node.list_channels().is_empty());
6469         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6470         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6471         check_added_monitors!(nodes[1], 1);
6472         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6473 }
6474
6475 #[test]
6476 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6477         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6478         let chanmon_cfgs = create_chanmon_cfgs(2);
6479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6481         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6482         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6483
6484         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6485         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6486                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6487         check_added_monitors!(nodes[0], 1);
6488         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6489         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;
6490         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6491
6492         assert!(nodes[1].node.list_channels().is_empty());
6493         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6494         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6495         check_added_monitors!(nodes[1], 1);
6496         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6497 }
6498
6499 #[test]
6500 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6501         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6502         let chanmon_cfgs = create_chanmon_cfgs(2);
6503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6505         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6506
6507         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6508         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6509         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6510                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6511         check_added_monitors!(nodes[0], 1);
6512         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6513         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6514         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6515
6516         assert!(nodes[1].node.list_channels().is_empty());
6517         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6518         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6519         check_added_monitors!(nodes[1], 1);
6520         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6521 }
6522
6523 #[test]
6524 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6525         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6526         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6527         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6528         let chanmon_cfgs = create_chanmon_cfgs(2);
6529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6531         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6532
6533         create_announced_chan_between_nodes(&nodes, 0, 1);
6534         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6535         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6536                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6537         check_added_monitors!(nodes[0], 1);
6538         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6539         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6540
6541         //Disconnect and Reconnect
6542         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6543         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6544         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6545                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6546         }, true).unwrap();
6547         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6548         assert_eq!(reestablish_1.len(), 1);
6549         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6550                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6551         }, false).unwrap();
6552         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6553         assert_eq!(reestablish_2.len(), 1);
6554         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6555         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6556         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6557         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6558
6559         //Resend HTLC
6560         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6561         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6562         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6563         check_added_monitors!(nodes[1], 1);
6564         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6565
6566         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6567
6568         assert!(nodes[1].node.list_channels().is_empty());
6569         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6570         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6571         check_added_monitors!(nodes[1], 1);
6572         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6573 }
6574
6575 #[test]
6576 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6577         //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.
6578
6579         let chanmon_cfgs = create_chanmon_cfgs(2);
6580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6582         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6583         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6584         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6585         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6586                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6587
6588         check_added_monitors!(nodes[0], 1);
6589         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6590         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6591
6592         let update_msg = msgs::UpdateFulfillHTLC{
6593                 channel_id: chan.2,
6594                 htlc_id: 0,
6595                 payment_preimage: our_payment_preimage,
6596         };
6597
6598         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6599
6600         assert!(nodes[0].node.list_channels().is_empty());
6601         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6602         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()));
6603         check_added_monitors!(nodes[0], 1);
6604         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6605 }
6606
6607 #[test]
6608 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6609         //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.
6610
6611         let chanmon_cfgs = create_chanmon_cfgs(2);
6612         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6613         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6614         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6615         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6616
6617         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6618         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6619                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6620         check_added_monitors!(nodes[0], 1);
6621         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6622         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6623
6624         let update_msg = msgs::UpdateFailHTLC{
6625                 channel_id: chan.2,
6626                 htlc_id: 0,
6627                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6628         };
6629
6630         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6631
6632         assert!(nodes[0].node.list_channels().is_empty());
6633         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6634         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()));
6635         check_added_monitors!(nodes[0], 1);
6636         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6637 }
6638
6639 #[test]
6640 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6641         //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.
6642
6643         let chanmon_cfgs = create_chanmon_cfgs(2);
6644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6647         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6648
6649         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6650         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6651                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6652         check_added_monitors!(nodes[0], 1);
6653         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6654         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6655         let update_msg = msgs::UpdateFailMalformedHTLC{
6656                 channel_id: chan.2,
6657                 htlc_id: 0,
6658                 sha256_of_onion: [1; 32],
6659                 failure_code: 0x8000,
6660         };
6661
6662         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6663
6664         assert!(nodes[0].node.list_channels().is_empty());
6665         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6666         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()));
6667         check_added_monitors!(nodes[0], 1);
6668         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6669 }
6670
6671 #[test]
6672 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6673         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6674
6675         let chanmon_cfgs = create_chanmon_cfgs(2);
6676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6678         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6679         create_announced_chan_between_nodes(&nodes, 0, 1);
6680
6681         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6682
6683         nodes[1].node.claim_funds(our_payment_preimage);
6684         check_added_monitors!(nodes[1], 1);
6685         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6686
6687         let events = nodes[1].node.get_and_clear_pending_msg_events();
6688         assert_eq!(events.len(), 1);
6689         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6690                 match events[0] {
6691                         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, .. } } => {
6692                                 assert!(update_add_htlcs.is_empty());
6693                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6694                                 assert!(update_fail_htlcs.is_empty());
6695                                 assert!(update_fail_malformed_htlcs.is_empty());
6696                                 assert!(update_fee.is_none());
6697                                 update_fulfill_htlcs[0].clone()
6698                         },
6699                         _ => panic!("Unexpected event"),
6700                 }
6701         };
6702
6703         update_fulfill_msg.htlc_id = 1;
6704
6705         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6706
6707         assert!(nodes[0].node.list_channels().is_empty());
6708         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6709         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6710         check_added_monitors!(nodes[0], 1);
6711         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6712 }
6713
6714 #[test]
6715 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6716         //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.
6717
6718         let chanmon_cfgs = create_chanmon_cfgs(2);
6719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6722         create_announced_chan_between_nodes(&nodes, 0, 1);
6723
6724         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6725
6726         nodes[1].node.claim_funds(our_payment_preimage);
6727         check_added_monitors!(nodes[1], 1);
6728         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6729
6730         let events = nodes[1].node.get_and_clear_pending_msg_events();
6731         assert_eq!(events.len(), 1);
6732         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6733                 match events[0] {
6734                         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, .. } } => {
6735                                 assert!(update_add_htlcs.is_empty());
6736                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6737                                 assert!(update_fail_htlcs.is_empty());
6738                                 assert!(update_fail_malformed_htlcs.is_empty());
6739                                 assert!(update_fee.is_none());
6740                                 update_fulfill_htlcs[0].clone()
6741                         },
6742                         _ => panic!("Unexpected event"),
6743                 }
6744         };
6745
6746         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6747
6748         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6749
6750         assert!(nodes[0].node.list_channels().is_empty());
6751         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6752         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6753         check_added_monitors!(nodes[0], 1);
6754         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6755 }
6756
6757 #[test]
6758 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6759         //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.
6760
6761         let chanmon_cfgs = create_chanmon_cfgs(2);
6762         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6763         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6764         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6765         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6766
6767         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6768         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6769                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6770         check_added_monitors!(nodes[0], 1);
6771
6772         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6773         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6774
6775         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6776         check_added_monitors!(nodes[1], 0);
6777         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6778
6779         let events = nodes[1].node.get_and_clear_pending_msg_events();
6780
6781         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6782                 match events[0] {
6783                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6784                                 assert!(update_add_htlcs.is_empty());
6785                                 assert!(update_fulfill_htlcs.is_empty());
6786                                 assert!(update_fail_htlcs.is_empty());
6787                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6788                                 assert!(update_fee.is_none());
6789                                 update_fail_malformed_htlcs[0].clone()
6790                         },
6791                         _ => panic!("Unexpected event"),
6792                 }
6793         };
6794         update_msg.failure_code &= !0x8000;
6795         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6796
6797         assert!(nodes[0].node.list_channels().is_empty());
6798         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6799         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6800         check_added_monitors!(nodes[0], 1);
6801         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6802 }
6803
6804 #[test]
6805 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6806         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6807         //    * 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.
6808
6809         let chanmon_cfgs = create_chanmon_cfgs(3);
6810         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6811         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6812         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6813         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6814         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6815
6816         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6817
6818         //First hop
6819         let mut payment_event = {
6820                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6821                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6822                 check_added_monitors!(nodes[0], 1);
6823                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6824                 assert_eq!(events.len(), 1);
6825                 SendEvent::from_event(events.remove(0))
6826         };
6827         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6828         check_added_monitors!(nodes[1], 0);
6829         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6830         expect_pending_htlcs_forwardable!(nodes[1]);
6831         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6832         assert_eq!(events_2.len(), 1);
6833         check_added_monitors!(nodes[1], 1);
6834         payment_event = SendEvent::from_event(events_2.remove(0));
6835         assert_eq!(payment_event.msgs.len(), 1);
6836
6837         //Second Hop
6838         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6839         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6840         check_added_monitors!(nodes[2], 0);
6841         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6842
6843         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6844         assert_eq!(events_3.len(), 1);
6845         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6846                 match events_3[0] {
6847                         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 } } => {
6848                                 assert!(update_add_htlcs.is_empty());
6849                                 assert!(update_fulfill_htlcs.is_empty());
6850                                 assert!(update_fail_htlcs.is_empty());
6851                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6852                                 assert!(update_fee.is_none());
6853                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6854                         },
6855                         _ => panic!("Unexpected event"),
6856                 }
6857         };
6858
6859         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6860
6861         check_added_monitors!(nodes[1], 0);
6862         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6863         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 }]);
6864         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6865         assert_eq!(events_4.len(), 1);
6866
6867         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6868         match events_4[0] {
6869                 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, .. } } => {
6870                         assert!(update_add_htlcs.is_empty());
6871                         assert!(update_fulfill_htlcs.is_empty());
6872                         assert_eq!(update_fail_htlcs.len(), 1);
6873                         assert!(update_fail_malformed_htlcs.is_empty());
6874                         assert!(update_fee.is_none());
6875                 },
6876                 _ => panic!("Unexpected event"),
6877         };
6878
6879         check_added_monitors!(nodes[1], 1);
6880 }
6881
6882 #[test]
6883 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6884         let chanmon_cfgs = create_chanmon_cfgs(3);
6885         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6886         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6887         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6888         create_announced_chan_between_nodes(&nodes, 0, 1);
6889         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6890
6891         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6892
6893         // First hop
6894         let mut payment_event = {
6895                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6896                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6897                 check_added_monitors!(nodes[0], 1);
6898                 SendEvent::from_node(&nodes[0])
6899         };
6900
6901         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6902         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6903         expect_pending_htlcs_forwardable!(nodes[1]);
6904         check_added_monitors!(nodes[1], 1);
6905         payment_event = SendEvent::from_node(&nodes[1]);
6906         assert_eq!(payment_event.msgs.len(), 1);
6907
6908         // Second Hop
6909         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6910         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6911         check_added_monitors!(nodes[2], 0);
6912         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6913
6914         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6915         assert_eq!(events_3.len(), 1);
6916         match events_3[0] {
6917                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6918                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6919                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6920                         update_msg.failure_code |= 0x2000;
6921
6922                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6923                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6924                 },
6925                 _ => panic!("Unexpected event"),
6926         }
6927
6928         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6929                 vec![HTLCDestination::NextHopChannel {
6930                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6931         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6932         assert_eq!(events_4.len(), 1);
6933         check_added_monitors!(nodes[1], 1);
6934
6935         match events_4[0] {
6936                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6937                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6938                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6939                 },
6940                 _ => panic!("Unexpected event"),
6941         }
6942
6943         let events_5 = nodes[0].node.get_and_clear_pending_events();
6944         assert_eq!(events_5.len(), 2);
6945
6946         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6947         // the node originating the error to its next hop.
6948         match events_5[0] {
6949                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6950                 } => {
6951                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6952                         assert!(is_permanent);
6953                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6954                 },
6955                 _ => panic!("Unexpected event"),
6956         }
6957         match events_5[1] {
6958                 Event::PaymentFailed { payment_hash, .. } => {
6959                         assert_eq!(payment_hash, our_payment_hash);
6960                 },
6961                 _ => panic!("Unexpected event"),
6962         }
6963
6964         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6965 }
6966
6967 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6968         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6969         // 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
6970         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6971
6972         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6973         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6974         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6975         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6976         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6977         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6978
6979         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6980                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
6981
6982         // We route 2 dust-HTLCs between A and B
6983         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6984         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6985         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6986
6987         // Cache one local commitment tx as previous
6988         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6989
6990         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6991         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6992         check_added_monitors!(nodes[1], 0);
6993         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6994         check_added_monitors!(nodes[1], 1);
6995
6996         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6997         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6998         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6999         check_added_monitors!(nodes[0], 1);
7000
7001         // Cache one local commitment tx as lastest
7002         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7003
7004         let events = nodes[0].node.get_and_clear_pending_msg_events();
7005         match events[0] {
7006                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7007                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7008                 },
7009                 _ => panic!("Unexpected event"),
7010         }
7011         match events[1] {
7012                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7013                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7014                 },
7015                 _ => panic!("Unexpected event"),
7016         }
7017
7018         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7019         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7020         if announce_latest {
7021                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7022         } else {
7023                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7024         }
7025
7026         check_closed_broadcast!(nodes[0], true);
7027         check_added_monitors!(nodes[0], 1);
7028         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7029
7030         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7031         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7032         let events = nodes[0].node.get_and_clear_pending_events();
7033         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7034         assert_eq!(events.len(), 4);
7035         let mut first_failed = false;
7036         for event in events {
7037                 match event {
7038                         Event::PaymentPathFailed { payment_hash, .. } => {
7039                                 if payment_hash == payment_hash_1 {
7040                                         assert!(!first_failed);
7041                                         first_failed = true;
7042                                 } else {
7043                                         assert_eq!(payment_hash, payment_hash_2);
7044                                 }
7045                         },
7046                         Event::PaymentFailed { .. } => {}
7047                         _ => panic!("Unexpected event"),
7048                 }
7049         }
7050 }
7051
7052 #[test]
7053 fn test_failure_delay_dust_htlc_local_commitment() {
7054         do_test_failure_delay_dust_htlc_local_commitment(true);
7055         do_test_failure_delay_dust_htlc_local_commitment(false);
7056 }
7057
7058 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7059         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7060         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7061         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7062         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7063         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7064         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7065
7066         let chanmon_cfgs = create_chanmon_cfgs(3);
7067         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7068         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7069         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7070         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7071
7072         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7073                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7074
7075         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7076         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7077
7078         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7079         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7080
7081         // We revoked bs_commitment_tx
7082         if revoked {
7083                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7084                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7085         }
7086
7087         let mut timeout_tx = Vec::new();
7088         if local {
7089                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7090                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7091                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7092                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7093                 expect_payment_failed!(nodes[0], dust_hash, false);
7094
7095                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7096                 check_closed_broadcast!(nodes[0], true);
7097                 check_added_monitors!(nodes[0], 1);
7098                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7099                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7100                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7101                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7102                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7103                 mine_transaction(&nodes[0], &timeout_tx[0]);
7104                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7105                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7106         } else {
7107                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7108                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7109                 check_closed_broadcast!(nodes[0], true);
7110                 check_added_monitors!(nodes[0], 1);
7111                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7112                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7113
7114                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7115                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7116                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7117                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7118                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7119                 // dust HTLC should have been failed.
7120                 expect_payment_failed!(nodes[0], dust_hash, false);
7121
7122                 if !revoked {
7123                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7124                 } else {
7125                         assert_eq!(timeout_tx[0].lock_time.0, 11);
7126                 }
7127                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7128                 mine_transaction(&nodes[0], &timeout_tx[0]);
7129                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7130                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7131                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7132         }
7133 }
7134
7135 #[test]
7136 fn test_sweep_outbound_htlc_failure_update() {
7137         do_test_sweep_outbound_htlc_failure_update(false, true);
7138         do_test_sweep_outbound_htlc_failure_update(false, false);
7139         do_test_sweep_outbound_htlc_failure_update(true, false);
7140 }
7141
7142 #[test]
7143 fn test_user_configurable_csv_delay() {
7144         // We test our channel constructors yield errors when we pass them absurd csv delay
7145
7146         let mut low_our_to_self_config = UserConfig::default();
7147         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7148         let mut high_their_to_self_config = UserConfig::default();
7149         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7150         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7151         let chanmon_cfgs = create_chanmon_cfgs(2);
7152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7155
7156         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7157         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7158                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7159                 &low_our_to_self_config, 0, 42)
7160         {
7161                 match error {
7162                         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())); },
7163                         _ => panic!("Unexpected event"),
7164                 }
7165         } else { assert!(false) }
7166
7167         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7168         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7169         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7170         open_channel.to_self_delay = 200;
7171         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7172                 &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,
7173                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7174         {
7175                 match error {
7176                         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()));  },
7177                         _ => panic!("Unexpected event"),
7178                 }
7179         } else { assert!(false); }
7180
7181         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7182         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7183         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()));
7184         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7185         accept_channel.to_self_delay = 200;
7186         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7187         let reason_msg;
7188         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7189                 match action {
7190                         &ErrorAction::SendErrorMessage { ref msg } => {
7191                                 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()));
7192                                 reason_msg = msg.data.clone();
7193                         },
7194                         _ => { panic!(); }
7195                 }
7196         } else { panic!(); }
7197         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7198
7199         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7200         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7201         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7202         open_channel.to_self_delay = 200;
7203         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7204                 &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,
7205                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7206         {
7207                 match error {
7208                         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())); },
7209                         _ => panic!("Unexpected event"),
7210                 }
7211         } else { assert!(false); }
7212 }
7213
7214 #[test]
7215 fn test_check_htlc_underpaying() {
7216         // Send payment through A -> B but A is maliciously
7217         // sending a probe payment (i.e less than expected value0
7218         // to B, B should refuse payment.
7219
7220         let chanmon_cfgs = create_chanmon_cfgs(2);
7221         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7222         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7223         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7224
7225         // Create some initial channels
7226         create_announced_chan_between_nodes(&nodes, 0, 1);
7227
7228         let scorer = test_utils::TestScorer::new();
7229         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7230         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7231                 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7232         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7233         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7234                 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7235         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7236         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7237         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7238                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7239         check_added_monitors!(nodes[0], 1);
7240
7241         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7242         assert_eq!(events.len(), 1);
7243         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7244         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7245         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7246
7247         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7248         // and then will wait a second random delay before failing the HTLC back:
7249         expect_pending_htlcs_forwardable!(nodes[1]);
7250         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7251
7252         // Node 3 is expecting payment of 100_000 but received 10_000,
7253         // it should fail htlc like we didn't know the preimage.
7254         nodes[1].node.process_pending_htlc_forwards();
7255
7256         let events = nodes[1].node.get_and_clear_pending_msg_events();
7257         assert_eq!(events.len(), 1);
7258         let (update_fail_htlc, commitment_signed) = match events[0] {
7259                 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 } } => {
7260                         assert!(update_add_htlcs.is_empty());
7261                         assert!(update_fulfill_htlcs.is_empty());
7262                         assert_eq!(update_fail_htlcs.len(), 1);
7263                         assert!(update_fail_malformed_htlcs.is_empty());
7264                         assert!(update_fee.is_none());
7265                         (update_fail_htlcs[0].clone(), commitment_signed)
7266                 },
7267                 _ => panic!("Unexpected event"),
7268         };
7269         check_added_monitors!(nodes[1], 1);
7270
7271         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7272         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7273
7274         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7275         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7276         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7277         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7278 }
7279
7280 #[test]
7281 fn test_announce_disable_channels() {
7282         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7283         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7284
7285         let chanmon_cfgs = create_chanmon_cfgs(2);
7286         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7287         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7288         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7289
7290         create_announced_chan_between_nodes(&nodes, 0, 1);
7291         create_announced_chan_between_nodes(&nodes, 1, 0);
7292         create_announced_chan_between_nodes(&nodes, 0, 1);
7293
7294         // Disconnect peers
7295         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7296         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7297
7298         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7299                 nodes[0].node.timer_tick_occurred();
7300         }
7301         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7302         assert_eq!(msg_events.len(), 3);
7303         let mut chans_disabled = HashMap::new();
7304         for e in msg_events {
7305                 match e {
7306                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7307                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7308                                 // Check that each channel gets updated exactly once
7309                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7310                                         panic!("Generated ChannelUpdate for wrong chan!");
7311                                 }
7312                         },
7313                         _ => panic!("Unexpected event"),
7314                 }
7315         }
7316         // Reconnect peers
7317         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7318                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7319         }, true).unwrap();
7320         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7321         assert_eq!(reestablish_1.len(), 3);
7322         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7323                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7324         }, false).unwrap();
7325         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7326         assert_eq!(reestablish_2.len(), 3);
7327
7328         // Reestablish chan_1
7329         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7330         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7331         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7332         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7333         // Reestablish chan_2
7334         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7335         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7336         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7337         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7338         // Reestablish chan_3
7339         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7340         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7341         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7342         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7343
7344         for _ in 0..ENABLE_GOSSIP_TICKS {
7345                 nodes[0].node.timer_tick_occurred();
7346         }
7347         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7348         nodes[0].node.timer_tick_occurred();
7349         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7350         assert_eq!(msg_events.len(), 3);
7351         for e in msg_events {
7352                 match e {
7353                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7354                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7355                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7356                                         // Each update should have a higher timestamp than the previous one, replacing
7357                                         // the old one.
7358                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7359                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7360                                 }
7361                         },
7362                         _ => panic!("Unexpected event"),
7363                 }
7364         }
7365         // Check that each channel gets updated exactly once
7366         assert!(chans_disabled.is_empty());
7367 }
7368
7369 #[test]
7370 fn test_bump_penalty_txn_on_revoked_commitment() {
7371         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7372         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7373
7374         let chanmon_cfgs = create_chanmon_cfgs(2);
7375         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7376         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7377         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7378
7379         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7380
7381         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7382         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7383                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7384         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7385         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7386
7387         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7388         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7389         assert_eq!(revoked_txn[0].output.len(), 4);
7390         assert_eq!(revoked_txn[0].input.len(), 1);
7391         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7392         let revoked_txid = revoked_txn[0].txid();
7393
7394         let mut penalty_sum = 0;
7395         for outp in revoked_txn[0].output.iter() {
7396                 if outp.script_pubkey.is_v0_p2wsh() {
7397                         penalty_sum += outp.value;
7398                 }
7399         }
7400
7401         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7402         let header_114 = connect_blocks(&nodes[1], 14);
7403
7404         // Actually revoke tx by claiming a HTLC
7405         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7406         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7407         check_added_monitors!(nodes[1], 1);
7408
7409         // One or more justice tx should have been broadcast, check it
7410         let penalty_1;
7411         let feerate_1;
7412         {
7413                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7414                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7415                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7416                 assert_eq!(node_txn[0].output.len(), 1);
7417                 check_spends!(node_txn[0], revoked_txn[0]);
7418                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7419                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7420                 penalty_1 = node_txn[0].txid();
7421                 node_txn.clear();
7422         };
7423
7424         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7425         connect_blocks(&nodes[1], 15);
7426         let mut penalty_2 = penalty_1;
7427         let mut feerate_2 = 0;
7428         {
7429                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7430                 assert_eq!(node_txn.len(), 1);
7431                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7432                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7433                         assert_eq!(node_txn[0].output.len(), 1);
7434                         check_spends!(node_txn[0], revoked_txn[0]);
7435                         penalty_2 = node_txn[0].txid();
7436                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7437                         assert_ne!(penalty_2, penalty_1);
7438                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7439                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7440                         // Verify 25% bump heuristic
7441                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7442                         node_txn.clear();
7443                 }
7444         }
7445         assert_ne!(feerate_2, 0);
7446
7447         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7448         connect_blocks(&nodes[1], 1);
7449         let penalty_3;
7450         let mut feerate_3 = 0;
7451         {
7452                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7453                 assert_eq!(node_txn.len(), 1);
7454                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7455                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7456                         assert_eq!(node_txn[0].output.len(), 1);
7457                         check_spends!(node_txn[0], revoked_txn[0]);
7458                         penalty_3 = node_txn[0].txid();
7459                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7460                         assert_ne!(penalty_3, penalty_2);
7461                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7462                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7463                         // Verify 25% bump heuristic
7464                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7465                         node_txn.clear();
7466                 }
7467         }
7468         assert_ne!(feerate_3, 0);
7469
7470         nodes[1].node.get_and_clear_pending_events();
7471         nodes[1].node.get_and_clear_pending_msg_events();
7472 }
7473
7474 #[test]
7475 fn test_bump_penalty_txn_on_revoked_htlcs() {
7476         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7477         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7478
7479         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7480         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7484
7485         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7486         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7487         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7488         let scorer = test_utils::TestScorer::new();
7489         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7490         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7491         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7492                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7493         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7494         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7495         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7496         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7497                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7498         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7499
7500         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7501         assert_eq!(revoked_local_txn[0].input.len(), 1);
7502         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7503
7504         // Revoke local commitment tx
7505         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7506
7507         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7508         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7509         check_closed_broadcast!(nodes[1], true);
7510         check_added_monitors!(nodes[1], 1);
7511         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7512         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7513
7514         let revoked_htlc_txn = {
7515                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7516                 assert_eq!(txn.len(), 2);
7517
7518                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7519                 assert_eq!(txn[0].input.len(), 1);
7520                 check_spends!(txn[0], revoked_local_txn[0]);
7521
7522                 assert_eq!(txn[1].input.len(), 1);
7523                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7524                 assert_eq!(txn[1].output.len(), 1);
7525                 check_spends!(txn[1], revoked_local_txn[0]);
7526
7527                 txn
7528         };
7529
7530         // Broadcast set of revoked txn on A
7531         let hash_128 = connect_blocks(&nodes[0], 40);
7532         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7533         connect_block(&nodes[0], &block_11);
7534         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7535         connect_block(&nodes[0], &block_129);
7536         let events = nodes[0].node.get_and_clear_pending_events();
7537         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7538         match events.last().unwrap() {
7539                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7540                 _ => panic!("Unexpected event"),
7541         }
7542         let first;
7543         let feerate_1;
7544         let penalty_txn;
7545         {
7546                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7547                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7548                 // Verify claim tx are spending revoked HTLC txn
7549
7550                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7551                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7552                 // which are included in the same block (they are broadcasted because we scan the
7553                 // transactions linearly and generate claims as we go, they likely should be removed in the
7554                 // future).
7555                 assert_eq!(node_txn[0].input.len(), 1);
7556                 check_spends!(node_txn[0], revoked_local_txn[0]);
7557                 assert_eq!(node_txn[1].input.len(), 1);
7558                 check_spends!(node_txn[1], revoked_local_txn[0]);
7559                 assert_eq!(node_txn[2].input.len(), 1);
7560                 check_spends!(node_txn[2], revoked_local_txn[0]);
7561
7562                 // Each of the three justice transactions claim a separate (single) output of the three
7563                 // available, which we check here:
7564                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7565                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7566                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7567
7568                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7569                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7570
7571                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7572                 // output, checked above).
7573                 assert_eq!(node_txn[3].input.len(), 2);
7574                 assert_eq!(node_txn[3].output.len(), 1);
7575                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7576
7577                 first = node_txn[3].txid();
7578                 // Store both feerates for later comparison
7579                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7580                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7581                 penalty_txn = vec![node_txn[2].clone()];
7582                 node_txn.clear();
7583         }
7584
7585         // Connect one more block to see if bumped penalty are issued for HTLC txn
7586         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7587         connect_block(&nodes[0], &block_130);
7588         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7589         connect_block(&nodes[0], &block_131);
7590
7591         // Few more blocks to confirm penalty txn
7592         connect_blocks(&nodes[0], 4);
7593         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7594         let header_144 = connect_blocks(&nodes[0], 9);
7595         let node_txn = {
7596                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7597                 assert_eq!(node_txn.len(), 1);
7598
7599                 assert_eq!(node_txn[0].input.len(), 2);
7600                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7601                 // Verify bumped tx is different and 25% bump heuristic
7602                 assert_ne!(first, node_txn[0].txid());
7603                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7604                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7605                 assert!(feerate_2 * 100 > feerate_1 * 125);
7606                 let txn = vec![node_txn[0].clone()];
7607                 node_txn.clear();
7608                 txn
7609         };
7610         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7611         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7612         connect_blocks(&nodes[0], 20);
7613         {
7614                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7615                 // We verify than no new transaction has been broadcast because previously
7616                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7617                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7618                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7619                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7620                 // up bumped justice generation.
7621                 assert_eq!(node_txn.len(), 0);
7622                 node_txn.clear();
7623         }
7624         check_closed_broadcast!(nodes[0], true);
7625         check_added_monitors!(nodes[0], 1);
7626 }
7627
7628 #[test]
7629 fn test_bump_penalty_txn_on_remote_commitment() {
7630         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7631         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7632
7633         // Create 2 HTLCs
7634         // Provide preimage for one
7635         // Check aggregation
7636
7637         let chanmon_cfgs = create_chanmon_cfgs(2);
7638         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7639         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7640         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7641
7642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7643         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7644         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7645
7646         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7647         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7648         assert_eq!(remote_txn[0].output.len(), 4);
7649         assert_eq!(remote_txn[0].input.len(), 1);
7650         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7651
7652         // Claim a HTLC without revocation (provide B monitor with preimage)
7653         nodes[1].node.claim_funds(payment_preimage);
7654         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7655         mine_transaction(&nodes[1], &remote_txn[0]);
7656         check_added_monitors!(nodes[1], 2);
7657         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7658
7659         // One or more claim tx should have been broadcast, check it
7660         let timeout;
7661         let preimage;
7662         let preimage_bump;
7663         let feerate_timeout;
7664         let feerate_preimage;
7665         {
7666                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7667                 // 3 transactions including:
7668                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7669                 assert_eq!(node_txn.len(), 3);
7670                 assert_eq!(node_txn[0].input.len(), 1);
7671                 assert_eq!(node_txn[1].input.len(), 1);
7672                 assert_eq!(node_txn[2].input.len(), 1);
7673                 check_spends!(node_txn[0], remote_txn[0]);
7674                 check_spends!(node_txn[1], remote_txn[0]);
7675                 check_spends!(node_txn[2], remote_txn[0]);
7676
7677                 preimage = node_txn[0].txid();
7678                 let index = node_txn[0].input[0].previous_output.vout;
7679                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7680                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7681
7682                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7683                         (node_txn[2].clone(), node_txn[1].clone())
7684                 } else {
7685                         (node_txn[1].clone(), node_txn[2].clone())
7686                 };
7687
7688                 preimage_bump = preimage_bump_tx;
7689                 check_spends!(preimage_bump, remote_txn[0]);
7690                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7691
7692                 timeout = timeout_tx.txid();
7693                 let index = timeout_tx.input[0].previous_output.vout;
7694                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7695                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7696
7697                 node_txn.clear();
7698         };
7699         assert_ne!(feerate_timeout, 0);
7700         assert_ne!(feerate_preimage, 0);
7701
7702         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7703         connect_blocks(&nodes[1], 1);
7704         {
7705                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7706                 assert_eq!(node_txn.len(), 1);
7707                 assert_eq!(node_txn[0].input.len(), 1);
7708                 assert_eq!(preimage_bump.input.len(), 1);
7709                 check_spends!(node_txn[0], remote_txn[0]);
7710                 check_spends!(preimage_bump, remote_txn[0]);
7711
7712                 let index = preimage_bump.input[0].previous_output.vout;
7713                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7714                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7715                 assert!(new_feerate * 100 > feerate_timeout * 125);
7716                 assert_ne!(timeout, preimage_bump.txid());
7717
7718                 let index = node_txn[0].input[0].previous_output.vout;
7719                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7720                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7721                 assert!(new_feerate * 100 > feerate_preimage * 125);
7722                 assert_ne!(preimage, node_txn[0].txid());
7723
7724                 node_txn.clear();
7725         }
7726
7727         nodes[1].node.get_and_clear_pending_events();
7728         nodes[1].node.get_and_clear_pending_msg_events();
7729 }
7730
7731 #[test]
7732 fn test_counterparty_raa_skip_no_crash() {
7733         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7734         // commitment transaction, we would have happily carried on and provided them the next
7735         // commitment transaction based on one RAA forward. This would probably eventually have led to
7736         // channel closure, but it would not have resulted in funds loss. Still, our
7737         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7738         // check simply that the channel is closed in response to such an RAA, but don't check whether
7739         // we decide to punish our counterparty for revoking their funds (as we don't currently
7740         // implement that).
7741         let chanmon_cfgs = create_chanmon_cfgs(2);
7742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7746
7747         let per_commitment_secret;
7748         let next_per_commitment_point;
7749         {
7750                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7751                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7752                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7753                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7754                 ).flatten().unwrap().get_signer();
7755
7756                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7757
7758                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7759                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7760                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7761
7762                 // Must revoke without gaps
7763                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7764                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7765
7766                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7767                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7768                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7769         }
7770
7771         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7772                 &msgs::RevokeAndACK {
7773                         channel_id,
7774                         per_commitment_secret,
7775                         next_per_commitment_point,
7776                         #[cfg(taproot)]
7777                         next_local_nonce: None,
7778                 });
7779         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7780         check_added_monitors!(nodes[1], 1);
7781         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7782                 , [nodes[0].node.get_our_node_id()], 100000);
7783 }
7784
7785 #[test]
7786 fn test_bump_txn_sanitize_tracking_maps() {
7787         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7788         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7789
7790         let chanmon_cfgs = create_chanmon_cfgs(2);
7791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7794
7795         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7796         // Lock HTLC in both directions
7797         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7798         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7799
7800         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7801         assert_eq!(revoked_local_txn[0].input.len(), 1);
7802         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7803
7804         // Revoke local commitment tx
7805         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7806
7807         // Broadcast set of revoked txn on A
7808         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7809         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7810         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7811
7812         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7813         check_closed_broadcast!(nodes[0], true);
7814         check_added_monitors!(nodes[0], 1);
7815         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7816         let penalty_txn = {
7817                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7818                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7819                 check_spends!(node_txn[0], revoked_local_txn[0]);
7820                 check_spends!(node_txn[1], revoked_local_txn[0]);
7821                 check_spends!(node_txn[2], revoked_local_txn[0]);
7822                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7823                 node_txn.clear();
7824                 penalty_txn
7825         };
7826         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7827         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7828         {
7829                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7830                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7831                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7832         }
7833 }
7834
7835 #[test]
7836 fn test_channel_conf_timeout() {
7837         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7838         // confirm within 2016 blocks, as recommended by BOLT 2.
7839         let chanmon_cfgs = create_chanmon_cfgs(2);
7840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7842         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7843
7844         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7845
7846         // The outbound node should wait forever for confirmation:
7847         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7848         // copied here instead of directly referencing the constant.
7849         connect_blocks(&nodes[0], 2016);
7850         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7851
7852         // The inbound node should fail the channel after exactly 2016 blocks
7853         connect_blocks(&nodes[1], 2015);
7854         check_added_monitors!(nodes[1], 0);
7855         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7856
7857         connect_blocks(&nodes[1], 1);
7858         check_added_monitors!(nodes[1], 1);
7859         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7860         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7861         assert_eq!(close_ev.len(), 1);
7862         match close_ev[0] {
7863                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7864                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7865                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7866                 },
7867                 _ => panic!("Unexpected event"),
7868         }
7869 }
7870
7871 #[test]
7872 fn test_override_channel_config() {
7873         let chanmon_cfgs = create_chanmon_cfgs(2);
7874         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7875         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7876         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7877
7878         // Node0 initiates a channel to node1 using the override config.
7879         let mut override_config = UserConfig::default();
7880         override_config.channel_handshake_config.our_to_self_delay = 200;
7881
7882         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7883
7884         // Assert the channel created by node0 is using the override config.
7885         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7886         assert_eq!(res.channel_flags, 0);
7887         assert_eq!(res.to_self_delay, 200);
7888 }
7889
7890 #[test]
7891 fn test_override_0msat_htlc_minimum() {
7892         let mut zero_config = UserConfig::default();
7893         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7894         let chanmon_cfgs = create_chanmon_cfgs(2);
7895         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7896         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7897         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7898
7899         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7900         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7901         assert_eq!(res.htlc_minimum_msat, 1);
7902
7903         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7904         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7905         assert_eq!(res.htlc_minimum_msat, 1);
7906 }
7907
7908 #[test]
7909 fn test_channel_update_has_correct_htlc_maximum_msat() {
7910         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7911         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7912         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7913         // 90% of the `channel_value`.
7914         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7915
7916         let mut config_30_percent = UserConfig::default();
7917         config_30_percent.channel_handshake_config.announced_channel = true;
7918         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7919         let mut config_50_percent = UserConfig::default();
7920         config_50_percent.channel_handshake_config.announced_channel = true;
7921         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7922         let mut config_95_percent = UserConfig::default();
7923         config_95_percent.channel_handshake_config.announced_channel = true;
7924         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7925         let mut config_100_percent = UserConfig::default();
7926         config_100_percent.channel_handshake_config.announced_channel = true;
7927         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7928
7929         let chanmon_cfgs = create_chanmon_cfgs(4);
7930         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7931         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)]);
7932         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7933
7934         let channel_value_satoshis = 100000;
7935         let channel_value_msat = channel_value_satoshis * 1000;
7936         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7937         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7938         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7939
7940         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7941         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7942
7943         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7944         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7945         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7946         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7947         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7948         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7949
7950         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7951         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7952         // `channel_value`.
7953         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7954         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7955         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7956         // `channel_value`.
7957         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7958 }
7959
7960 #[test]
7961 fn test_manually_accept_inbound_channel_request() {
7962         let mut manually_accept_conf = UserConfig::default();
7963         manually_accept_conf.manually_accept_inbound_channels = true;
7964         let chanmon_cfgs = create_chanmon_cfgs(2);
7965         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7966         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7967         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7968
7969         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7970         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7971
7972         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7973
7974         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7975         // accepting the inbound channel request.
7976         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7977
7978         let events = nodes[1].node.get_and_clear_pending_events();
7979         match events[0] {
7980                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7981                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7982                 }
7983                 _ => panic!("Unexpected event"),
7984         }
7985
7986         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7987         assert_eq!(accept_msg_ev.len(), 1);
7988
7989         match accept_msg_ev[0] {
7990                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7991                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7992                 }
7993                 _ => panic!("Unexpected event"),
7994         }
7995
7996         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7997
7998         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7999         assert_eq!(close_msg_ev.len(), 1);
8000
8001         let events = nodes[1].node.get_and_clear_pending_events();
8002         match events[0] {
8003                 Event::ChannelClosed { user_channel_id, .. } => {
8004                         assert_eq!(user_channel_id, 23);
8005                 }
8006                 _ => panic!("Unexpected event"),
8007         }
8008 }
8009
8010 #[test]
8011 fn test_manually_reject_inbound_channel_request() {
8012         let mut manually_accept_conf = UserConfig::default();
8013         manually_accept_conf.manually_accept_inbound_channels = true;
8014         let chanmon_cfgs = create_chanmon_cfgs(2);
8015         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8016         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8017         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8018
8019         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8020         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8021
8022         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8023
8024         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8025         // rejecting the inbound channel request.
8026         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8027
8028         let events = nodes[1].node.get_and_clear_pending_events();
8029         match events[0] {
8030                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8031                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8032                 }
8033                 _ => panic!("Unexpected event"),
8034         }
8035
8036         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8037         assert_eq!(close_msg_ev.len(), 1);
8038
8039         match close_msg_ev[0] {
8040                 MessageSendEvent::HandleError { ref node_id, .. } => {
8041                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8042                 }
8043                 _ => panic!("Unexpected event"),
8044         }
8045
8046         // There should be no more events to process, as the channel was never opened.
8047         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8048 }
8049
8050 #[test]
8051 fn test_can_not_accept_inbound_channel_twice() {
8052         let mut manually_accept_conf = UserConfig::default();
8053         manually_accept_conf.manually_accept_inbound_channels = true;
8054         let chanmon_cfgs = create_chanmon_cfgs(2);
8055         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8056         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8057         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8058
8059         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8060         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8061
8062         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8063
8064         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8065         // accepting the inbound channel request.
8066         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8067
8068         let events = nodes[1].node.get_and_clear_pending_events();
8069         match events[0] {
8070                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8071                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8072                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8073                         match api_res {
8074                                 Err(APIError::APIMisuseError { err }) => {
8075                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8076                                 },
8077                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8078                                 Err(e) => panic!("Unexpected Error {:?}", e),
8079                         }
8080                 }
8081                 _ => panic!("Unexpected event"),
8082         }
8083
8084         // Ensure that the channel wasn't closed after attempting to accept it twice.
8085         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8086         assert_eq!(accept_msg_ev.len(), 1);
8087
8088         match accept_msg_ev[0] {
8089                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8090                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8091                 }
8092                 _ => panic!("Unexpected event"),
8093         }
8094 }
8095
8096 #[test]
8097 fn test_can_not_accept_unknown_inbound_channel() {
8098         let chanmon_cfg = create_chanmon_cfgs(2);
8099         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8100         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8101         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8102
8103         let unknown_channel_id = ChannelId::new_zero();
8104         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8105         match api_res {
8106                 Err(APIError::APIMisuseError { err }) => {
8107                         assert_eq!(err, "No such channel awaiting to be accepted.");
8108                 },
8109                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8110                 Err(e) => panic!("Unexpected Error: {:?}", e),
8111         }
8112 }
8113
8114 #[test]
8115 fn test_onion_value_mpp_set_calculation() {
8116         // Test that we use the onion value `amt_to_forward` when
8117         // calculating whether we've reached the `total_msat` of an MPP
8118         // by having a routing node forward more than `amt_to_forward`
8119         // and checking that the receiving node doesn't generate
8120         // a PaymentClaimable event too early
8121         let node_count = 4;
8122         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8123         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8124         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8125         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8126
8127         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8128         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8129         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8130         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8131
8132         let total_msat = 100_000;
8133         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8134         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8135         let sample_path = route.paths.pop().unwrap();
8136
8137         let mut path_1 = sample_path.clone();
8138         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8139         path_1.hops[0].short_channel_id = chan_1_id;
8140         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8141         path_1.hops[1].short_channel_id = chan_3_id;
8142         path_1.hops[1].fee_msat = 100_000;
8143         route.paths.push(path_1);
8144
8145         let mut path_2 = sample_path.clone();
8146         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8147         path_2.hops[0].short_channel_id = chan_2_id;
8148         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8149         path_2.hops[1].short_channel_id = chan_4_id;
8150         path_2.hops[1].fee_msat = 1_000;
8151         route.paths.push(path_2);
8152
8153         // Send payment
8154         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8155         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8156                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8157         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8158                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8159         check_added_monitors!(nodes[0], expected_paths.len());
8160
8161         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8162         assert_eq!(events.len(), expected_paths.len());
8163
8164         // First path
8165         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8166         let mut payment_event = SendEvent::from_event(ev);
8167         let mut prev_node = &nodes[0];
8168
8169         for (idx, &node) in expected_paths[0].iter().enumerate() {
8170                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8171
8172                 if idx == 0 { // routing node
8173                         let session_priv = [3; 32];
8174                         let height = nodes[0].best_block_info().1;
8175                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8176                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8177                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8178                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8179                         // Edit amt_to_forward to simulate the sender having set
8180                         // the final amount and the routing node taking less fee
8181                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8182                                 *amt_msat = 99_000;
8183                         } else { panic!() }
8184                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8185                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8186                 }
8187
8188                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8189                 check_added_monitors!(node, 0);
8190                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8191                 expect_pending_htlcs_forwardable!(node);
8192
8193                 if idx == 0 {
8194                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8195                         assert_eq!(events_2.len(), 1);
8196                         check_added_monitors!(node, 1);
8197                         payment_event = SendEvent::from_event(events_2.remove(0));
8198                         assert_eq!(payment_event.msgs.len(), 1);
8199                 } else {
8200                         let events_2 = node.node.get_and_clear_pending_events();
8201                         assert!(events_2.is_empty());
8202                 }
8203
8204                 prev_node = node;
8205         }
8206
8207         // Second path
8208         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8209         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8210
8211         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8212 }
8213
8214 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8215
8216         let routing_node_count = msat_amounts.len();
8217         let node_count = routing_node_count + 2;
8218
8219         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8220         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8221         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8222         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8223
8224         let src_idx = 0;
8225         let dst_idx = 1;
8226
8227         // Create channels for each amount
8228         let mut expected_paths = Vec::with_capacity(routing_node_count);
8229         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8230         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8231         for i in 0..routing_node_count {
8232                 let routing_node = 2 + i;
8233                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8234                 src_chan_ids.push(src_chan_id);
8235                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8236                 dst_chan_ids.push(dst_chan_id);
8237                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8238                 expected_paths.push(path);
8239         }
8240         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8241
8242         // Create a route for each amount
8243         let example_amount = 100000;
8244         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);
8245         let sample_path = route.paths.pop().unwrap();
8246         for i in 0..routing_node_count {
8247                 let routing_node = 2 + i;
8248                 let mut path = sample_path.clone();
8249                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8250                 path.hops[0].short_channel_id = src_chan_ids[i];
8251                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8252                 path.hops[1].short_channel_id = dst_chan_ids[i];
8253                 path.hops[1].fee_msat = msat_amounts[i];
8254                 route.paths.push(path);
8255         }
8256
8257         // Send payment with manually set total_msat
8258         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8259         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8260                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8261         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8262                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8263         check_added_monitors!(nodes[src_idx], expected_paths.len());
8264
8265         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8266         assert_eq!(events.len(), expected_paths.len());
8267         let mut amount_received = 0;
8268         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8269                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8270
8271                 let current_path_amount = msat_amounts[path_idx];
8272                 amount_received += current_path_amount;
8273                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8274                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8275         }
8276
8277         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8278 }
8279
8280 #[test]
8281 fn test_overshoot_mpp() {
8282         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8283         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8284 }
8285
8286 #[test]
8287 fn test_simple_mpp() {
8288         // Simple test of sending a multi-path payment.
8289         let chanmon_cfgs = create_chanmon_cfgs(4);
8290         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8291         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8292         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8293
8294         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8295         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8296         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8297         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8298
8299         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8300         let path = route.paths[0].clone();
8301         route.paths.push(path);
8302         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8303         route.paths[0].hops[0].short_channel_id = chan_1_id;
8304         route.paths[0].hops[1].short_channel_id = chan_3_id;
8305         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8306         route.paths[1].hops[0].short_channel_id = chan_2_id;
8307         route.paths[1].hops[1].short_channel_id = chan_4_id;
8308         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8309         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8310 }
8311
8312 #[test]
8313 fn test_preimage_storage() {
8314         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8315         let chanmon_cfgs = create_chanmon_cfgs(2);
8316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8318         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8319
8320         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8321
8322         {
8323                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8324                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8325                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8326                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8327                 check_added_monitors!(nodes[0], 1);
8328                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8329                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8330                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8331                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8332         }
8333         // Note that after leaving the above scope we have no knowledge of any arguments or return
8334         // values from previous calls.
8335         expect_pending_htlcs_forwardable!(nodes[1]);
8336         let events = nodes[1].node.get_and_clear_pending_events();
8337         assert_eq!(events.len(), 1);
8338         match events[0] {
8339                 Event::PaymentClaimable { ref purpose, .. } => {
8340                         match &purpose {
8341                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8342                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8343                                 },
8344                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8345                         }
8346                 },
8347                 _ => panic!("Unexpected event"),
8348         }
8349 }
8350
8351 #[test]
8352 fn test_bad_secret_hash() {
8353         // Simple test of unregistered payment hash/invalid payment secret handling
8354         let chanmon_cfgs = create_chanmon_cfgs(2);
8355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8357         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8358
8359         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8360
8361         let random_payment_hash = PaymentHash([42; 32]);
8362         let random_payment_secret = PaymentSecret([43; 32]);
8363         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8364         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8365
8366         // All the below cases should end up being handled exactly identically, so we macro the
8367         // resulting events.
8368         macro_rules! handle_unknown_invalid_payment_data {
8369                 ($payment_hash: expr) => {
8370                         check_added_monitors!(nodes[0], 1);
8371                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8372                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8373                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8374                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8375
8376                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8377                         // again to process the pending backwards-failure of the HTLC
8378                         expect_pending_htlcs_forwardable!(nodes[1]);
8379                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8380                         check_added_monitors!(nodes[1], 1);
8381
8382                         // We should fail the payment back
8383                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8384                         match events.pop().unwrap() {
8385                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8386                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8387                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8388                                 },
8389                                 _ => panic!("Unexpected event"),
8390                         }
8391                 }
8392         }
8393
8394         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8395         // Error data is the HTLC value (100,000) and current block height
8396         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8397
8398         // Send a payment with the right payment hash but the wrong payment secret
8399         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8400                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8401         handle_unknown_invalid_payment_data!(our_payment_hash);
8402         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8403
8404         // Send a payment with a random payment hash, but the right payment secret
8405         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8406                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8407         handle_unknown_invalid_payment_data!(random_payment_hash);
8408         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8409
8410         // Send a payment with a random payment hash and random payment secret
8411         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8412                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8413         handle_unknown_invalid_payment_data!(random_payment_hash);
8414         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8415 }
8416
8417 #[test]
8418 fn test_update_err_monitor_lockdown() {
8419         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8420         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8421         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8422         // error.
8423         //
8424         // This scenario may happen in a watchtower setup, where watchtower process a block height
8425         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8426         // commitment at same time.
8427
8428         let chanmon_cfgs = create_chanmon_cfgs(2);
8429         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8430         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8431         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8432
8433         // Create some initial channel
8434         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8435         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8436
8437         // Rebalance the network to generate htlc in the two directions
8438         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8439
8440         // Route a HTLC from node 0 to node 1 (but don't settle)
8441         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8442
8443         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8444         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8445         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8446         let persister = test_utils::TestPersister::new();
8447         let watchtower = {
8448                 let new_monitor = {
8449                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8450                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8451                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8452                         assert!(new_monitor == *monitor);
8453                         new_monitor
8454                 };
8455                 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);
8456                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8457                 watchtower
8458         };
8459         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8460         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8461         // transaction lock time requirements here.
8462         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8463         watchtower.chain_monitor.block_connected(&block, 200);
8464
8465         // Try to update ChannelMonitor
8466         nodes[1].node.claim_funds(preimage);
8467         check_added_monitors!(nodes[1], 1);
8468         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8469
8470         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8471         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8472         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8473         {
8474                 let mut node_0_per_peer_lock;
8475                 let mut node_0_peer_state_lock;
8476                 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) {
8477                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8478                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8479                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8480                         } else { assert!(false); }
8481                 } else {
8482                         assert!(false);
8483                 }
8484         }
8485         // Our local monitor is in-sync and hasn't processed yet timeout
8486         check_added_monitors!(nodes[0], 1);
8487         let events = nodes[0].node.get_and_clear_pending_events();
8488         assert_eq!(events.len(), 1);
8489 }
8490
8491 #[test]
8492 fn test_concurrent_monitor_claim() {
8493         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8494         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8495         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8496         // state N+1 confirms. Alice claims output from state N+1.
8497
8498         let chanmon_cfgs = create_chanmon_cfgs(2);
8499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8501         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8502
8503         // Create some initial channel
8504         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8505         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8506
8507         // Rebalance the network to generate htlc in the two directions
8508         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8509
8510         // Route a HTLC from node 0 to node 1 (but don't settle)
8511         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8512
8513         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8514         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8515         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8516         let persister = test_utils::TestPersister::new();
8517         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8518                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8519         );
8520         let watchtower_alice = {
8521                 let new_monitor = {
8522                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8523                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8524                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8525                         assert!(new_monitor == *monitor);
8526                         new_monitor
8527                 };
8528                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8529                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8530                 watchtower
8531         };
8532         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8533         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8534         // requirements here.
8535         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8536         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8537         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8538
8539         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8540         let alice_state = {
8541                 let mut txn = alice_broadcaster.txn_broadcast();
8542                 assert_eq!(txn.len(), 2);
8543                 txn.remove(0)
8544         };
8545
8546         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8547         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8548         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8549         let persister = test_utils::TestPersister::new();
8550         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8551         let watchtower_bob = {
8552                 let new_monitor = {
8553                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8554                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8555                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8556                         assert!(new_monitor == *monitor);
8557                         new_monitor
8558                 };
8559                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8560                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8561                 watchtower
8562         };
8563         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8564
8565         // Route another payment to generate another update with still previous HTLC pending
8566         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8567         nodes[1].node.send_payment_with_route(&route, payment_hash,
8568                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8569         check_added_monitors!(nodes[1], 1);
8570
8571         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8572         assert_eq!(updates.update_add_htlcs.len(), 1);
8573         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8574         {
8575                 let mut node_0_per_peer_lock;
8576                 let mut node_0_peer_state_lock;
8577                 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) {
8578                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8579                                 // Watchtower Alice should already have seen the block and reject the update
8580                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8581                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8582                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8583                         } else { assert!(false); }
8584                 } else {
8585                         assert!(false);
8586                 }
8587         }
8588         // Our local monitor is in-sync and hasn't processed yet timeout
8589         check_added_monitors!(nodes[0], 1);
8590
8591         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8592         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8593
8594         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8595         let bob_state_y;
8596         {
8597                 let mut txn = bob_broadcaster.txn_broadcast();
8598                 assert_eq!(txn.len(), 2);
8599                 bob_state_y = txn.remove(0);
8600         };
8601
8602         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8603         let height = HTLC_TIMEOUT_BROADCAST + 1;
8604         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8605         check_closed_broadcast(&nodes[0], 1, true);
8606         check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8607                 [nodes[1].node.get_our_node_id()], 100000);
8608         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8609         check_added_monitors(&nodes[0], 1);
8610         {
8611                 let htlc_txn = alice_broadcaster.txn_broadcast();
8612                 assert_eq!(htlc_txn.len(), 2);
8613                 check_spends!(htlc_txn[0], bob_state_y);
8614                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8615                 // it. However, she should, because it now has an invalid parent.
8616                 check_spends!(htlc_txn[1], alice_state);
8617         }
8618 }
8619
8620 #[test]
8621 fn test_pre_lockin_no_chan_closed_update() {
8622         // Test that if a peer closes a channel in response to a funding_created message we don't
8623         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8624         // message).
8625         //
8626         // Doing so would imply a channel monitor update before the initial channel monitor
8627         // registration, violating our API guarantees.
8628         //
8629         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8630         // then opening a second channel with the same funding output as the first (which is not
8631         // rejected because the first channel does not exist in the ChannelManager) and closing it
8632         // before receiving funding_signed.
8633         let chanmon_cfgs = create_chanmon_cfgs(2);
8634         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8635         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8636         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8637
8638         // Create an initial channel
8639         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8640         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8641         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8642         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8643         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8644
8645         // Move the first channel through the funding flow...
8646         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8647
8648         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8649         check_added_monitors!(nodes[0], 0);
8650
8651         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8652         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8653         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8654         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8655         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8656                 [nodes[1].node.get_our_node_id(); 2], 100000);
8657 }
8658
8659 #[test]
8660 fn test_htlc_no_detection() {
8661         // This test is a mutation to underscore the detection logic bug we had
8662         // before #653. HTLC value routed is above the remaining balance, thus
8663         // inverting HTLC and `to_remote` output. HTLC will come second and
8664         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8665         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8666         // outputs order detection for correct spending children filtring.
8667
8668         let chanmon_cfgs = create_chanmon_cfgs(2);
8669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8672
8673         // Create some initial channels
8674         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8675
8676         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8677         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8678         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8679         assert_eq!(local_txn[0].input.len(), 1);
8680         assert_eq!(local_txn[0].output.len(), 3);
8681         check_spends!(local_txn[0], chan_1.3);
8682
8683         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8684         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8685         connect_block(&nodes[0], &block);
8686         // We deliberately connect the local tx twice as this should provoke a failure calling
8687         // this test before #653 fix.
8688         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8689         check_closed_broadcast!(nodes[0], true);
8690         check_added_monitors!(nodes[0], 1);
8691         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8692         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8693
8694         let htlc_timeout = {
8695                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8696                 assert_eq!(node_txn.len(), 1);
8697                 assert_eq!(node_txn[0].input.len(), 1);
8698                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8699                 check_spends!(node_txn[0], local_txn[0]);
8700                 node_txn[0].clone()
8701         };
8702
8703         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8704         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8705         expect_payment_failed!(nodes[0], our_payment_hash, false);
8706 }
8707
8708 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8709         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8710         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8711         // Carol, Alice would be the upstream node, and Carol the downstream.)
8712         //
8713         // Steps of the test:
8714         // 1) Alice sends a HTLC to Carol through Bob.
8715         // 2) Carol doesn't settle the HTLC.
8716         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8717         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8718         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8719         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8720         // 5) Carol release the preimage to Bob off-chain.
8721         // 6) Bob claims the offered output on the broadcasted commitment.
8722         let chanmon_cfgs = create_chanmon_cfgs(3);
8723         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8724         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8725         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8726
8727         // Create some initial channels
8728         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8729         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8730
8731         // Steps (1) and (2):
8732         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8733         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8734
8735         // Check that Alice's commitment transaction now contains an output for this HTLC.
8736         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8737         check_spends!(alice_txn[0], chan_ab.3);
8738         assert_eq!(alice_txn[0].output.len(), 2);
8739         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8740         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8741         assert_eq!(alice_txn.len(), 2);
8742
8743         // Steps (3) and (4):
8744         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8745         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8746         let mut force_closing_node = 0; // Alice force-closes
8747         let mut counterparty_node = 1; // Bob if Alice force-closes
8748
8749         // Bob force-closes
8750         if !broadcast_alice {
8751                 force_closing_node = 1;
8752                 counterparty_node = 0;
8753         }
8754         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8755         check_closed_broadcast!(nodes[force_closing_node], true);
8756         check_added_monitors!(nodes[force_closing_node], 1);
8757         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8758         if go_onchain_before_fulfill {
8759                 let txn_to_broadcast = match broadcast_alice {
8760                         true => alice_txn.clone(),
8761                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8762                 };
8763                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8764                 if broadcast_alice {
8765                         check_closed_broadcast!(nodes[1], true);
8766                         check_added_monitors!(nodes[1], 1);
8767                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8768                 }
8769         }
8770
8771         // Step (5):
8772         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8773         // process of removing the HTLC from their commitment transactions.
8774         nodes[2].node.claim_funds(payment_preimage);
8775         check_added_monitors!(nodes[2], 1);
8776         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8777
8778         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8779         assert!(carol_updates.update_add_htlcs.is_empty());
8780         assert!(carol_updates.update_fail_htlcs.is_empty());
8781         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8782         assert!(carol_updates.update_fee.is_none());
8783         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8784
8785         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8786         let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8787         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8788         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8789         if !go_onchain_before_fulfill && broadcast_alice {
8790                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8791                 assert_eq!(events.len(), 1);
8792                 match events[0] {
8793                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8794                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8795                         },
8796                         _ => panic!("Unexpected event"),
8797                 };
8798         }
8799         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8800         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8801         // Carol<->Bob's updated commitment transaction info.
8802         check_added_monitors!(nodes[1], 2);
8803
8804         let events = nodes[1].node.get_and_clear_pending_msg_events();
8805         assert_eq!(events.len(), 2);
8806         let bob_revocation = match events[0] {
8807                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8808                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8809                         (*msg).clone()
8810                 },
8811                 _ => panic!("Unexpected event"),
8812         };
8813         let bob_updates = match events[1] {
8814                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8815                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8816                         (*updates).clone()
8817                 },
8818                 _ => panic!("Unexpected event"),
8819         };
8820
8821         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8822         check_added_monitors!(nodes[2], 1);
8823         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8824         check_added_monitors!(nodes[2], 1);
8825
8826         let events = nodes[2].node.get_and_clear_pending_msg_events();
8827         assert_eq!(events.len(), 1);
8828         let carol_revocation = match events[0] {
8829                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8830                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8831                         (*msg).clone()
8832                 },
8833                 _ => panic!("Unexpected event"),
8834         };
8835         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8836         check_added_monitors!(nodes[1], 1);
8837
8838         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8839         // here's where we put said channel's commitment tx on-chain.
8840         let mut txn_to_broadcast = alice_txn.clone();
8841         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8842         if !go_onchain_before_fulfill {
8843                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8844                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8845                 if broadcast_alice {
8846                         check_closed_broadcast!(nodes[1], true);
8847                         check_added_monitors!(nodes[1], 1);
8848                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8849                 }
8850                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8851                 if broadcast_alice {
8852                         assert_eq!(bob_txn.len(), 1);
8853                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8854                 } else {
8855                         assert_eq!(bob_txn.len(), 2);
8856                         check_spends!(bob_txn[0], chan_ab.3);
8857                 }
8858         }
8859
8860         // Step (6):
8861         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8862         // broadcasted commitment transaction.
8863         {
8864                 let script_weight = match broadcast_alice {
8865                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8866                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8867                 };
8868                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8869                 // Bob force-closed and broadcasts the commitment transaction along with a
8870                 // HTLC-output-claiming transaction.
8871                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8872                 if broadcast_alice {
8873                         assert_eq!(bob_txn.len(), 1);
8874                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8875                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8876                 } else {
8877                         assert_eq!(bob_txn.len(), 2);
8878                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8879                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8880                 }
8881         }
8882 }
8883
8884 #[test]
8885 fn test_onchain_htlc_settlement_after_close() {
8886         do_test_onchain_htlc_settlement_after_close(true, true);
8887         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8888         do_test_onchain_htlc_settlement_after_close(true, false);
8889         do_test_onchain_htlc_settlement_after_close(false, false);
8890 }
8891
8892 #[test]
8893 fn test_duplicate_temporary_channel_id_from_different_peers() {
8894         // Tests that we can accept two different `OpenChannel` requests with the same
8895         // `temporary_channel_id`, as long as they are from different peers.
8896         let chanmon_cfgs = create_chanmon_cfgs(3);
8897         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8898         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8899         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8900
8901         // Create an first channel channel
8902         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8903         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8904
8905         // Create an second channel
8906         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8907         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8908
8909         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8910         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8911         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8912
8913         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8914         // `temporary_channel_id` as they are from different peers.
8915         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8916         {
8917                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8918                 assert_eq!(events.len(), 1);
8919                 match &events[0] {
8920                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8921                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8922                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8923                         },
8924                         _ => panic!("Unexpected event"),
8925                 }
8926         }
8927
8928         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8929         {
8930                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8931                 assert_eq!(events.len(), 1);
8932                 match &events[0] {
8933                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8934                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8935                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8936                         },
8937                         _ => panic!("Unexpected event"),
8938                 }
8939         }
8940 }
8941
8942 #[test]
8943 fn test_duplicate_chan_id() {
8944         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8945         // already open we reject it and keep the old channel.
8946         //
8947         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8948         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8949         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8950         // updating logic for the existing channel.
8951         let chanmon_cfgs = create_chanmon_cfgs(2);
8952         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8953         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8954         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8955
8956         // Create an initial channel
8957         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8958         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8959         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8960         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()));
8961
8962         // Try to create a second channel with the same temporary_channel_id as the first and check
8963         // that it is rejected.
8964         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8965         {
8966                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8967                 assert_eq!(events.len(), 1);
8968                 match events[0] {
8969                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8970                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8971                                 // first (valid) and second (invalid) channels are closed, given they both have
8972                                 // the same non-temporary channel_id. However, currently we do not, so we just
8973                                 // move forward with it.
8974                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8975                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8976                         },
8977                         _ => panic!("Unexpected event"),
8978                 }
8979         }
8980
8981         // Move the first channel through the funding flow...
8982         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8983
8984         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8985         check_added_monitors!(nodes[0], 0);
8986
8987         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8988         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8989         {
8990                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8991                 assert_eq!(added_monitors.len(), 1);
8992                 assert_eq!(added_monitors[0].0, funding_output);
8993                 added_monitors.clear();
8994         }
8995         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8996
8997         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8998
8999         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9000         let channel_id = funding_outpoint.to_channel_id();
9001
9002         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9003         // temporary one).
9004
9005         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9006         // Technically this is allowed by the spec, but we don't support it and there's little reason
9007         // to. Still, it shouldn't cause any other issues.
9008         open_chan_msg.temporary_channel_id = channel_id;
9009         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9010         {
9011                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9012                 assert_eq!(events.len(), 1);
9013                 match events[0] {
9014                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9015                                 // Technically, at this point, nodes[1] would be justified in thinking both
9016                                 // channels are closed, but currently we do not, so we just move forward with it.
9017                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9018                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9019                         },
9020                         _ => panic!("Unexpected event"),
9021                 }
9022         }
9023
9024         // Now try to create a second channel which has a duplicate funding output.
9025         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9026         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9027         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9028         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()));
9029         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9030
9031         let (_, funding_created) = {
9032                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9033                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9034                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9035                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9036                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9037                 // channelmanager in a possibly nonsense state instead).
9038                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9039                         ChannelPhase::UnfundedOutboundV1(chan) => {
9040                                 let logger = test_utils::TestLogger::new();
9041                                 chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
9042                         },
9043                         _ => panic!("Unexpected ChannelPhase variant"),
9044                 }
9045         };
9046         check_added_monitors!(nodes[0], 0);
9047         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9048         // At this point we'll look up if the channel_id is present and immediately fail the channel
9049         // without trying to persist the `ChannelMonitor`.
9050         check_added_monitors!(nodes[1], 0);
9051
9052         // ...still, nodes[1] will reject the duplicate channel.
9053         {
9054                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9055                 assert_eq!(events.len(), 1);
9056                 match events[0] {
9057                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9058                                 // Technically, at this point, nodes[1] would be justified in thinking both
9059                                 // channels are closed, but currently we do not, so we just move forward with it.
9060                                 assert_eq!(msg.channel_id, channel_id);
9061                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9062                         },
9063                         _ => panic!("Unexpected event"),
9064                 }
9065         }
9066
9067         // finally, finish creating the original channel and send a payment over it to make sure
9068         // everything is functional.
9069         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9070         {
9071                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9072                 assert_eq!(added_monitors.len(), 1);
9073                 assert_eq!(added_monitors[0].0, funding_output);
9074                 added_monitors.clear();
9075         }
9076         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9077
9078         let events_4 = nodes[0].node.get_and_clear_pending_events();
9079         assert_eq!(events_4.len(), 0);
9080         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9081         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9082
9083         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9084         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9085         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9086
9087         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9088 }
9089
9090 #[test]
9091 fn test_error_chans_closed() {
9092         // Test that we properly handle error messages, closing appropriate channels.
9093         //
9094         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9095         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9096         // we can test various edge cases around it to ensure we don't regress.
9097         let chanmon_cfgs = create_chanmon_cfgs(3);
9098         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9099         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9100         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9101
9102         // Create some initial channels
9103         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9104         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9105         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9106
9107         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9108         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9109         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9110
9111         // Closing a channel from a different peer has no effect
9112         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9113         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9114
9115         // Closing one channel doesn't impact others
9116         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9117         check_added_monitors!(nodes[0], 1);
9118         check_closed_broadcast!(nodes[0], false);
9119         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9120                 [nodes[1].node.get_our_node_id()], 100000);
9121         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9122         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9123         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);
9124         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);
9125
9126         // A null channel ID should close all channels
9127         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9128         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9129         check_added_monitors!(nodes[0], 2);
9130         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9131                 [nodes[1].node.get_our_node_id(); 2], 100000);
9132         let events = nodes[0].node.get_and_clear_pending_msg_events();
9133         assert_eq!(events.len(), 2);
9134         match events[0] {
9135                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9136                         assert_eq!(msg.contents.flags & 2, 2);
9137                 },
9138                 _ => panic!("Unexpected event"),
9139         }
9140         match events[1] {
9141                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9142                         assert_eq!(msg.contents.flags & 2, 2);
9143                 },
9144                 _ => panic!("Unexpected event"),
9145         }
9146         // Note that at this point users of a standard PeerHandler will end up calling
9147         // peer_disconnected.
9148         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9149         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9150
9151         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9152         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9153         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9154 }
9155
9156 #[test]
9157 fn test_invalid_funding_tx() {
9158         // Test that we properly handle invalid funding transactions sent to us from a peer.
9159         //
9160         // Previously, all other major lightning implementations had failed to properly sanitize
9161         // funding transactions from their counterparties, leading to a multi-implementation critical
9162         // security vulnerability (though we always sanitized properly, we've previously had
9163         // un-released crashes in the sanitization process).
9164         //
9165         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9166         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9167         // gave up on it. We test this here by generating such a transaction.
9168         let chanmon_cfgs = create_chanmon_cfgs(2);
9169         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9170         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9171         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9172
9173         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9174         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()));
9175         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()));
9176
9177         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9178
9179         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9180         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9181         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9182         // its length.
9183         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9184         let wit_program_script: Script = wit_program.into();
9185         for output in tx.output.iter_mut() {
9186                 // Make the confirmed funding transaction have a bogus script_pubkey
9187                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9188         }
9189
9190         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9191         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()));
9192         check_added_monitors!(nodes[1], 1);
9193         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9194
9195         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()));
9196         check_added_monitors!(nodes[0], 1);
9197         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9198
9199         let events_1 = nodes[0].node.get_and_clear_pending_events();
9200         assert_eq!(events_1.len(), 0);
9201
9202         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9203         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9204         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9205
9206         let expected_err = "funding tx had wrong script/value or output index";
9207         confirm_transaction_at(&nodes[1], &tx, 1);
9208         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9209                 [nodes[0].node.get_our_node_id()], 100000);
9210         check_added_monitors!(nodes[1], 1);
9211         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9212         assert_eq!(events_2.len(), 1);
9213         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9214                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9215                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9216                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9217                 } else { panic!(); }
9218         } else { panic!(); }
9219         assert_eq!(nodes[1].node.list_channels().len(), 0);
9220
9221         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9222         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9223         // as its not 32 bytes long.
9224         let mut spend_tx = Transaction {
9225                 version: 2i32, lock_time: PackedLockTime::ZERO,
9226                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9227                         previous_output: BitcoinOutPoint {
9228                                 txid: tx.txid(),
9229                                 vout: idx as u32,
9230                         },
9231                         script_sig: Script::new(),
9232                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9233                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9234                 }).collect(),
9235                 output: vec![TxOut {
9236                         value: 1000,
9237                         script_pubkey: Script::new(),
9238                 }]
9239         };
9240         check_spends!(spend_tx, tx);
9241         mine_transaction(&nodes[1], &spend_tx);
9242 }
9243
9244 #[test]
9245 fn test_coinbase_funding_tx() {
9246         // Miners are able to fund channels directly from coinbase transactions, however
9247         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9248         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9249         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9250         //
9251         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9252         // immediately operational after opening.
9253         let chanmon_cfgs = create_chanmon_cfgs(2);
9254         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9256         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9257
9258         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9259         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9260
9261         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9262         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9263
9264         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9265
9266         // Create the coinbase funding transaction.
9267         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9268
9269         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9270         check_added_monitors!(nodes[0], 0);
9271         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9272
9273         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9274         check_added_monitors!(nodes[1], 1);
9275         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9276
9277         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9278
9279         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9280         check_added_monitors!(nodes[0], 1);
9281
9282         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9283         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9284
9285         // Starting at height 0, we "confirm" the coinbase at height 1.
9286         confirm_transaction_at(&nodes[0], &tx, 1);
9287         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9288         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9289         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9290         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9291         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9292         connect_blocks(&nodes[0], 1);
9293         // There should now be a `channel_ready` which can be handled.
9294         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()));
9295
9296         confirm_transaction_at(&nodes[1], &tx, 1);
9297         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9298         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9299         connect_blocks(&nodes[1], 1);
9300         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9301         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9302 }
9303
9304 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9305         // In the first version of the chain::Confirm interface, after a refactor was made to not
9306         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9307         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9308         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9309         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9310         // spending transaction until height N+1 (or greater). This was due to the way
9311         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9312         // spending transaction at the height the input transaction was confirmed at, not whether we
9313         // should broadcast a spending transaction at the current height.
9314         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9315         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9316         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9317         // until we learned about an additional block.
9318         //
9319         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9320         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9321         let chanmon_cfgs = create_chanmon_cfgs(3);
9322         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9323         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9324         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9325         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9326
9327         create_announced_chan_between_nodes(&nodes, 0, 1);
9328         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9329         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9330         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9331         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9332
9333         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9334         check_closed_broadcast!(nodes[1], true);
9335         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9336         check_added_monitors!(nodes[1], 1);
9337         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9338         assert_eq!(node_txn.len(), 1);
9339
9340         let conf_height = nodes[1].best_block_info().1;
9341         if !test_height_before_timelock {
9342                 connect_blocks(&nodes[1], 24 * 6);
9343         }
9344         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9345                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9346         if test_height_before_timelock {
9347                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9348                 // generate any events or broadcast any transactions
9349                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9350                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9351         } else {
9352                 // We should broadcast an HTLC transaction spending our funding transaction first
9353                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9354                 assert_eq!(spending_txn.len(), 2);
9355                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9356                 check_spends!(spending_txn[1], node_txn[0]);
9357                 // We should also generate a SpendableOutputs event with the to_self output (as its
9358                 // timelock is up).
9359                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9360                 assert_eq!(descriptor_spend_txn.len(), 1);
9361
9362                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9363                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9364                 // additional block built on top of the current chain.
9365                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9366                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9367                 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 }]);
9368                 check_added_monitors!(nodes[1], 1);
9369
9370                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9371                 assert!(updates.update_add_htlcs.is_empty());
9372                 assert!(updates.update_fulfill_htlcs.is_empty());
9373                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9374                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9375                 assert!(updates.update_fee.is_none());
9376                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9377                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9378                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9379         }
9380 }
9381
9382 #[test]
9383 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9384         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9385         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9386 }
9387
9388 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9389         let chanmon_cfgs = create_chanmon_cfgs(2);
9390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9392         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9393
9394         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9395
9396         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9397                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9398         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9399
9400         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9401
9402         {
9403                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9404                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9405                 check_added_monitors!(nodes[0], 1);
9406                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9407                 assert_eq!(events.len(), 1);
9408                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9409                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9410                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9411         }
9412         expect_pending_htlcs_forwardable!(nodes[1]);
9413         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9414
9415         {
9416                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9417                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9418                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9419                 check_added_monitors!(nodes[0], 1);
9420                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9421                 assert_eq!(events.len(), 1);
9422                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9423                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9424                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9425                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9426                 // assume the second is a privacy attack (no longer particularly relevant
9427                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9428                 // the first HTLC delivered above.
9429         }
9430
9431         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9432         nodes[1].node.process_pending_htlc_forwards();
9433
9434         if test_for_second_fail_panic {
9435                 // Now we go fail back the first HTLC from the user end.
9436                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9437
9438                 let expected_destinations = vec![
9439                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9440                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9441                 ];
9442                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9443                 nodes[1].node.process_pending_htlc_forwards();
9444
9445                 check_added_monitors!(nodes[1], 1);
9446                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9447                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9448
9449                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9450                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9451                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9452
9453                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9454                 assert_eq!(failure_events.len(), 4);
9455                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9456                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9457                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9458                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9459         } else {
9460                 // Let the second HTLC fail and claim the first
9461                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9462                 nodes[1].node.process_pending_htlc_forwards();
9463
9464                 check_added_monitors!(nodes[1], 1);
9465                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9466                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9467                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9468
9469                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9470
9471                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9472         }
9473 }
9474
9475 #[test]
9476 fn test_dup_htlc_second_fail_panic() {
9477         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9478         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9479         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9480         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9481         do_test_dup_htlc_second_rejected(true);
9482 }
9483
9484 #[test]
9485 fn test_dup_htlc_second_rejected() {
9486         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9487         // simply reject the second HTLC but are still able to claim the first HTLC.
9488         do_test_dup_htlc_second_rejected(false);
9489 }
9490
9491 #[test]
9492 fn test_inconsistent_mpp_params() {
9493         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9494         // such HTLC and allow the second to stay.
9495         let chanmon_cfgs = create_chanmon_cfgs(4);
9496         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9497         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9498         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9499
9500         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9501         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9502         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9503         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9504
9505         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9506                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9507         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9508         assert_eq!(route.paths.len(), 2);
9509         route.paths.sort_by(|path_a, _| {
9510                 // Sort the path so that the path through nodes[1] comes first
9511                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9512                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9513         });
9514
9515         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9516
9517         let cur_height = nodes[0].best_block_info().1;
9518         let payment_id = PaymentId([42; 32]);
9519
9520         let session_privs = {
9521                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9522                 // ultimately have, just not right away.
9523                 let mut dup_route = route.clone();
9524                 dup_route.paths.push(route.paths[1].clone());
9525                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9526                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9527         };
9528         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9529                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9530                 &None, session_privs[0]).unwrap();
9531         check_added_monitors!(nodes[0], 1);
9532
9533         {
9534                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9535                 assert_eq!(events.len(), 1);
9536                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9537         }
9538         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9539
9540         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9541                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9542         check_added_monitors!(nodes[0], 1);
9543
9544         {
9545                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9546                 assert_eq!(events.len(), 1);
9547                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9548
9549                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9550                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9551
9552                 expect_pending_htlcs_forwardable!(nodes[2]);
9553                 check_added_monitors!(nodes[2], 1);
9554
9555                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9556                 assert_eq!(events.len(), 1);
9557                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9558
9559                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9560                 check_added_monitors!(nodes[3], 0);
9561                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9562
9563                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9564                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9565                 // post-payment_secrets) and fail back the new HTLC.
9566         }
9567         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9568         nodes[3].node.process_pending_htlc_forwards();
9569         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9570         nodes[3].node.process_pending_htlc_forwards();
9571
9572         check_added_monitors!(nodes[3], 1);
9573
9574         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9575         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9576         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9577
9578         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 }]);
9579         check_added_monitors!(nodes[2], 1);
9580
9581         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9582         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9583         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9584
9585         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9586
9587         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9588                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9589                 &None, session_privs[2]).unwrap();
9590         check_added_monitors!(nodes[0], 1);
9591
9592         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9593         assert_eq!(events.len(), 1);
9594         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9595
9596         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9597         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9598 }
9599
9600 #[test]
9601 fn test_double_partial_claim() {
9602         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9603         // time out, the sender resends only some of the MPP parts, then the user processes the
9604         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9605         // amount.
9606         let chanmon_cfgs = create_chanmon_cfgs(4);
9607         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9608         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9609         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9610
9611         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9612         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9613         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9614         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9615
9616         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9617         assert_eq!(route.paths.len(), 2);
9618         route.paths.sort_by(|path_a, _| {
9619                 // Sort the path so that the path through nodes[1] comes first
9620                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9621                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9622         });
9623
9624         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9625         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9626         // amount of time to respond to.
9627
9628         // Connect some blocks to time out the payment
9629         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9630         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9631
9632         let failed_destinations = vec![
9633                 HTLCDestination::FailedPayment { payment_hash },
9634                 HTLCDestination::FailedPayment { payment_hash },
9635         ];
9636         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9637
9638         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9639
9640         // nodes[1] now retries one of the two paths...
9641         nodes[0].node.send_payment_with_route(&route, payment_hash,
9642                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9643         check_added_monitors!(nodes[0], 2);
9644
9645         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9646         assert_eq!(events.len(), 2);
9647         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9648         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9649
9650         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9651         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9652         nodes[3].node.claim_funds(payment_preimage);
9653         check_added_monitors!(nodes[3], 0);
9654         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9655 }
9656
9657 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9658 #[derive(Clone, Copy, PartialEq)]
9659 enum ExposureEvent {
9660         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9661         AtHTLCForward,
9662         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9663         AtHTLCReception,
9664         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9665         AtUpdateFeeOutbound,
9666 }
9667
9668 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9669         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9670         // policy.
9671         //
9672         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9673         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9674         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9675         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9676         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9677         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9678         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9679         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9680
9681         let chanmon_cfgs = create_chanmon_cfgs(2);
9682         let mut config = test_default_channel_config();
9683         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9684                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9685                 // to get roughly the same initial value as the default setting when this test was
9686                 // originally written.
9687                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9688         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9689         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9690         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9691         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9692
9693         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9694         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9695         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9696         open_channel.max_accepted_htlcs = 60;
9697         if on_holder_tx {
9698                 open_channel.dust_limit_satoshis = 546;
9699         }
9700         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9701         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9702         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9703
9704         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9705
9706         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9707
9708         if on_holder_tx {
9709                 let mut node_0_per_peer_lock;
9710                 let mut node_0_peer_state_lock;
9711                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9712                         ChannelPhase::UnfundedOutboundV1(chan) => {
9713                                 chan.context.holder_dust_limit_satoshis = 546;
9714                         },
9715                         _ => panic!("Unexpected ChannelPhase variant"),
9716                 }
9717         }
9718
9719         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9720         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()));
9721         check_added_monitors!(nodes[1], 1);
9722         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9723
9724         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()));
9725         check_added_monitors!(nodes[0], 1);
9726         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9727
9728         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9729         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9730         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9731
9732         // Fetch a route in advance as we will be unable to once we're unable to send.
9733         let (mut route, payment_hash, _, payment_secret) =
9734                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9735
9736         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9737                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9738                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9739                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9740                 (chan.context().get_dust_buffer_feerate(None) as u64,
9741                 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9742         };
9743         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9744         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9745
9746         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9747         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9748
9749         let dust_htlc_on_counterparty_tx: u64 = 4;
9750         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9751
9752         if on_holder_tx {
9753                 if dust_outbound_balance {
9754                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9755                         // Outbound dust balance: 4372 sats
9756                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9757                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9758                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9759                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9760                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9761                         }
9762                 } else {
9763                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9764                         // Inbound dust balance: 4372 sats
9765                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9766                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9767                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9768                         }
9769                 }
9770         } else {
9771                 if dust_outbound_balance {
9772                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9773                         // Outbound dust balance: 5000 sats
9774                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9775                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9776                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9777                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9778                         }
9779                 } else {
9780                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9781                         // Inbound dust balance: 5000 sats
9782                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9783                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9784                         }
9785                 }
9786         }
9787
9788         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9789                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9790                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9791                 // With default dust exposure: 5000 sats
9792                 if on_holder_tx {
9793                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9794                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9795                                 ), true, APIError::ChannelUnavailable { .. }, {});
9796                 } else {
9797                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9798                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9799                                 ), true, APIError::ChannelUnavailable { .. }, {});
9800                 }
9801         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9802                 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 });
9803                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9804                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9805                 check_added_monitors!(nodes[1], 1);
9806                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9807                 assert_eq!(events.len(), 1);
9808                 let payment_event = SendEvent::from_event(events.remove(0));
9809                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9810                 // With default dust exposure: 5000 sats
9811                 if on_holder_tx {
9812                         // Outbound dust balance: 6399 sats
9813                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9814                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9815                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
9816                 } else {
9817                         // Outbound dust balance: 5200 sats
9818                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9819                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9820                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9821                                         max_dust_htlc_exposure_msat), 1);
9822                 }
9823         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9824                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9825                 // For the multiplier dust exposure limit, since it scales with feerate,
9826                 // we need to add a lot of HTLCs that will become dust at the new feerate
9827                 // to cross the threshold.
9828                 for _ in 0..20 {
9829                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9830                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9831                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9832                 }
9833                 {
9834                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9835                         *feerate_lock = *feerate_lock * 10;
9836                 }
9837                 nodes[0].node.timer_tick_occurred();
9838                 check_added_monitors!(nodes[0], 1);
9839                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9840         }
9841
9842         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9843         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9844         added_monitors.clear();
9845 }
9846
9847 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9848         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9849         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9850         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9851         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9852         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9853         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9854         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9855         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9856         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9857         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9858         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9859         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9860 }
9861
9862 #[test]
9863 fn test_max_dust_htlc_exposure() {
9864         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9865         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9866 }
9867
9868 #[test]
9869 fn test_non_final_funding_tx() {
9870         let chanmon_cfgs = create_chanmon_cfgs(2);
9871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9873         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9874
9875         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9876         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9877         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9878         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9879         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9880
9881         let best_height = nodes[0].node.best_block.read().unwrap().height();
9882
9883         let chan_id = *nodes[0].network_chan_count.borrow();
9884         let events = nodes[0].node.get_and_clear_pending_events();
9885         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9886         assert_eq!(events.len(), 1);
9887         let mut tx = match events[0] {
9888                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9889                         // Timelock the transaction _beyond_ the best client height + 1.
9890                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9891                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9892                         }]}
9893                 },
9894                 _ => panic!("Unexpected event"),
9895         };
9896         // Transaction should fail as it's evaluated as non-final for propagation.
9897         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9898                 Err(APIError::APIMisuseError { err }) => {
9899                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9900                 },
9901                 _ => panic!()
9902         }
9903
9904         // However, transaction should be accepted if it's in a +1 headroom from best block.
9905         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9906         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9907         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9908 }
9909
9910 #[test]
9911 fn accept_busted_but_better_fee() {
9912         // If a peer sends us a fee update that is too low, but higher than our previous channel
9913         // feerate, we should accept it. In the future we may want to consider closing the channel
9914         // later, but for now we only accept the update.
9915         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9916         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9917         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9918         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9919
9920         create_chan_between_nodes(&nodes[0], &nodes[1]);
9921
9922         // Set nodes[1] to expect 5,000 sat/kW.
9923         {
9924                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9925                 *feerate_lock = 5000;
9926         }
9927
9928         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9929         {
9930                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9931                 *feerate_lock = 1000;
9932         }
9933         nodes[0].node.timer_tick_occurred();
9934         check_added_monitors!(nodes[0], 1);
9935
9936         let events = nodes[0].node.get_and_clear_pending_msg_events();
9937         assert_eq!(events.len(), 1);
9938         match events[0] {
9939                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9940                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9941                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9942                 },
9943                 _ => panic!("Unexpected event"),
9944         };
9945
9946         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9947         // it.
9948         {
9949                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9950                 *feerate_lock = 2000;
9951         }
9952         nodes[0].node.timer_tick_occurred();
9953         check_added_monitors!(nodes[0], 1);
9954
9955         let events = nodes[0].node.get_and_clear_pending_msg_events();
9956         assert_eq!(events.len(), 1);
9957         match events[0] {
9958                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9959                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9960                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9961                 },
9962                 _ => panic!("Unexpected event"),
9963         };
9964
9965         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9966         // channel.
9967         {
9968                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9969                 *feerate_lock = 1000;
9970         }
9971         nodes[0].node.timer_tick_occurred();
9972         check_added_monitors!(nodes[0], 1);
9973
9974         let events = nodes[0].node.get_and_clear_pending_msg_events();
9975         assert_eq!(events.len(), 1);
9976         match events[0] {
9977                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9978                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9979                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9980                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9981                                 [nodes[0].node.get_our_node_id()], 100000);
9982                         check_closed_broadcast!(nodes[1], true);
9983                         check_added_monitors!(nodes[1], 1);
9984                 },
9985                 _ => panic!("Unexpected event"),
9986         };
9987 }
9988
9989 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9990         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9991         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9992         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9993         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9994         let min_final_cltv_expiry_delta = 120;
9995         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9996                 min_final_cltv_expiry_delta - 2 };
9997         let recv_value = 100_000;
9998
9999         create_chan_between_nodes(&nodes[0], &nodes[1]);
10000
10001         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10002         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10003                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10004                         Some(recv_value), Some(min_final_cltv_expiry_delta));
10005                 (payment_hash, payment_preimage, payment_secret)
10006         } else {
10007                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10008                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10009         };
10010         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10011         nodes[0].node.send_payment_with_route(&route, payment_hash,
10012                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10013         check_added_monitors!(nodes[0], 1);
10014         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10015         assert_eq!(events.len(), 1);
10016         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10017         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10018         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10019         expect_pending_htlcs_forwardable!(nodes[1]);
10020
10021         if valid_delta {
10022                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10023                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10024
10025                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10026         } else {
10027                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10028
10029                 check_added_monitors!(nodes[1], 1);
10030
10031                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10032                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10033                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10034
10035                 expect_payment_failed!(nodes[0], payment_hash, true);
10036         }
10037 }
10038
10039 #[test]
10040 fn test_payment_with_custom_min_cltv_expiry_delta() {
10041         do_payment_with_custom_min_final_cltv_expiry(false, false);
10042         do_payment_with_custom_min_final_cltv_expiry(false, true);
10043         do_payment_with_custom_min_final_cltv_expiry(true, false);
10044         do_payment_with_custom_min_final_cltv_expiry(true, true);
10045 }
10046
10047 #[test]
10048 fn test_disconnects_peer_awaiting_response_ticks() {
10049         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10050         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10051         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10052         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10053         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10054         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10055
10056         // Asserts a disconnect event is queued to the user.
10057         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10058                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10059                         if let MessageSendEvent::HandleError { action, .. } = event {
10060                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10061                                         Some(())
10062                                 } else {
10063                                         None
10064                                 }
10065                         } else {
10066                                 None
10067                         }
10068                 );
10069                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10070         };
10071
10072         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10073         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10074         let check_disconnect = |node: &Node| {
10075                 // No disconnect without any timer ticks.
10076                 check_disconnect_event(node, false);
10077
10078                 // No disconnect with 1 timer tick less than required.
10079                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10080                         node.node.timer_tick_occurred();
10081                         check_disconnect_event(node, false);
10082                 }
10083
10084                 // Disconnect after reaching the required ticks.
10085                 node.node.timer_tick_occurred();
10086                 check_disconnect_event(node, true);
10087
10088                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10089                 node.node.timer_tick_occurred();
10090                 check_disconnect_event(node, true);
10091         };
10092
10093         create_chan_between_nodes(&nodes[0], &nodes[1]);
10094
10095         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10096         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10097         nodes[0].node.timer_tick_occurred();
10098         check_added_monitors!(&nodes[0], 1);
10099         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10100         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10101         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10102         check_added_monitors!(&nodes[1], 1);
10103
10104         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10105         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10106         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10107         check_added_monitors!(&nodes[0], 1);
10108         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10109         check_added_monitors(&nodes[0], 1);
10110
10111         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10112         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10113         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10114         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10115         check_disconnect(&nodes[1]);
10116
10117         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10118         //
10119         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10120         // final `RevokeAndACK` to Bob to complete it.
10121         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10122         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10123         let bob_init = msgs::Init {
10124                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10125         };
10126         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10127         let alice_init = msgs::Init {
10128                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10129         };
10130         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10131
10132         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10133         // received Bob's yet, so she should disconnect him after reaching
10134         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10135         let alice_channel_reestablish = get_event_msg!(
10136                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10137         );
10138         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10139         check_disconnect(&nodes[0]);
10140
10141         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10142         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10143                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10144                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10145                         Some(msg.clone())
10146                 } else {
10147                         None
10148                 }
10149         ).unwrap();
10150         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10151
10152         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10153         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10154                 nodes[0].node.timer_tick_occurred();
10155                 check_disconnect_event(&nodes[0], false);
10156         }
10157
10158         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10159         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10160         check_disconnect(&nodes[1]);
10161
10162         // Finally, have Bob process the last message.
10163         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10164         check_added_monitors(&nodes[1], 1);
10165
10166         // At this point, neither node should attempt to disconnect each other, since they aren't
10167         // waiting on any messages.
10168         for node in &nodes {
10169                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10170                         node.node.timer_tick_occurred();
10171                         check_disconnect_event(node, false);
10172                 }
10173         }
10174 }
10175
10176 #[test]
10177 fn test_remove_expired_outbound_unfunded_channels() {
10178         let chanmon_cfgs = create_chanmon_cfgs(2);
10179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10181         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10182
10183         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10184         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10185         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10186         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10187         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10188
10189         let events = nodes[0].node.get_and_clear_pending_events();
10190         assert_eq!(events.len(), 1);
10191         match events[0] {
10192                 Event::FundingGenerationReady { .. } => (),
10193                 _ => panic!("Unexpected event"),
10194         };
10195
10196         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10197         let check_outbound_channel_existence = |should_exist: bool| {
10198                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10199                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10200                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10201         };
10202
10203         // Channel should exist without any timer ticks.
10204         check_outbound_channel_existence(true);
10205
10206         // Channel should exist with 1 timer tick less than required.
10207         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10208                 nodes[0].node.timer_tick_occurred();
10209                 check_outbound_channel_existence(true)
10210         }
10211
10212         // Remove channel after reaching the required ticks.
10213         nodes[0].node.timer_tick_occurred();
10214         check_outbound_channel_existence(false);
10215
10216         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10217         assert_eq!(msg_events.len(), 1);
10218         match msg_events[0] {
10219                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10220                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10221                 },
10222                 _ => panic!("Unexpected event"),
10223         }
10224         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10225 }
10226
10227 #[test]
10228 fn test_remove_expired_inbound_unfunded_channels() {
10229         let chanmon_cfgs = create_chanmon_cfgs(2);
10230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10233
10234         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10235         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10236         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10237         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10238         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10239
10240         let events = nodes[0].node.get_and_clear_pending_events();
10241         assert_eq!(events.len(), 1);
10242         match events[0] {
10243                 Event::FundingGenerationReady { .. } => (),
10244                 _ => panic!("Unexpected event"),
10245         };
10246
10247         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10248         let check_inbound_channel_existence = |should_exist: bool| {
10249                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10250                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10251                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10252         };
10253
10254         // Channel should exist without any timer ticks.
10255         check_inbound_channel_existence(true);
10256
10257         // Channel should exist with 1 timer tick less than required.
10258         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10259                 nodes[1].node.timer_tick_occurred();
10260                 check_inbound_channel_existence(true)
10261         }
10262
10263         // Remove channel after reaching the required ticks.
10264         nodes[1].node.timer_tick_occurred();
10265         check_inbound_channel_existence(false);
10266
10267         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10268         assert_eq!(msg_events.len(), 1);
10269         match msg_events[0] {
10270                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10271                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10272                 },
10273                 _ => panic!("Unexpected event"),
10274         }
10275         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10276 }
10277
10278 fn do_test_multi_post_event_actions(do_reload: bool) {
10279         // Tests handling multiple post-Event actions at once.
10280         // There is specific code in ChannelManager to handle channels where multiple post-Event
10281         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10282         //
10283         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10284         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10285         // - one from an RAA and one from an inbound commitment_signed.
10286         let chanmon_cfgs = create_chanmon_cfgs(3);
10287         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10288         let (persister, chain_monitor);
10289         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10290         let nodes_0_deserialized;
10291         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10292
10293         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10294         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10295
10296         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10297         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10298
10299         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10300         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10301
10302         nodes[1].node.claim_funds(our_payment_preimage);
10303         check_added_monitors!(nodes[1], 1);
10304         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10305
10306         nodes[2].node.claim_funds(payment_preimage_2);
10307         check_added_monitors!(nodes[2], 1);
10308         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10309
10310         for dest in &[1, 2] {
10311                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10312                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10313                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10314                 check_added_monitors(&nodes[0], 0);
10315         }
10316
10317         let (route, payment_hash_3, _, payment_secret_3) =
10318                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10319         let payment_id = PaymentId(payment_hash_3.0);
10320         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10321                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10322         check_added_monitors(&nodes[1], 1);
10323
10324         let send_event = SendEvent::from_node(&nodes[1]);
10325         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10326         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10327         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10328
10329         if do_reload {
10330                 let nodes_0_serialized = nodes[0].node.encode();
10331                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10332                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10333                 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);
10334
10335                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10336                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10337
10338                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10339                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10340         }
10341
10342         let events = nodes[0].node.get_and_clear_pending_events();
10343         assert_eq!(events.len(), 4);
10344         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10345                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10346         } else { panic!(); }
10347         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10348                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10349         } else { panic!(); }
10350         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10351         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10352
10353         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10354         // completion, we'll respond to nodes[1] with an RAA + CS.
10355         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10356         check_added_monitors(&nodes[0], 3);
10357 }
10358
10359 #[test]
10360 fn test_multi_post_event_actions() {
10361         do_test_multi_post_event_actions(true);
10362         do_test_multi_post_event_actions(false);
10363 }