Add PaymentId in ChannelManager.list_recent_payments()
[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::{ChannelSigner, 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         });
1041         hops.push(RouteHop {
1042                 pubkey: nodes[3].node.get_our_node_id(),
1043                 node_features: NodeFeatures::empty(),
1044                 short_channel_id: chan_3.0.contents.short_channel_id,
1045                 channel_features: ChannelFeatures::empty(),
1046                 fee_msat: 0,
1047                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1048         });
1049         hops.push(RouteHop {
1050                 pubkey: nodes[1].node.get_our_node_id(),
1051                 node_features: nodes[1].node.node_features(),
1052                 short_channel_id: chan_4.0.contents.short_channel_id,
1053                 channel_features: nodes[1].node.channel_features(),
1054                 fee_msat: 1000000,
1055                 cltv_expiry_delta: TEST_FINAL_CLTV,
1056         });
1057         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;
1058         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;
1059         let payment_preimage_1 = send_along_route(&nodes[1],
1060                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1061                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1062
1063         let mut hops = Vec::with_capacity(3);
1064         hops.push(RouteHop {
1065                 pubkey: nodes[3].node.get_our_node_id(),
1066                 node_features: NodeFeatures::empty(),
1067                 short_channel_id: chan_4.0.contents.short_channel_id,
1068                 channel_features: ChannelFeatures::empty(),
1069                 fee_msat: 0,
1070                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1071         });
1072         hops.push(RouteHop {
1073                 pubkey: nodes[2].node.get_our_node_id(),
1074                 node_features: NodeFeatures::empty(),
1075                 short_channel_id: chan_3.0.contents.short_channel_id,
1076                 channel_features: ChannelFeatures::empty(),
1077                 fee_msat: 0,
1078                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1079         });
1080         hops.push(RouteHop {
1081                 pubkey: nodes[1].node.get_our_node_id(),
1082                 node_features: nodes[1].node.node_features(),
1083                 short_channel_id: chan_2.0.contents.short_channel_id,
1084                 channel_features: nodes[1].node.channel_features(),
1085                 fee_msat: 1000000,
1086                 cltv_expiry_delta: TEST_FINAL_CLTV,
1087         });
1088         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;
1089         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;
1090         let payment_hash_2 = send_along_route(&nodes[1],
1091                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1092                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1093
1094         // Claim the rebalances...
1095         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1096         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1097
1098         // Close down the channels...
1099         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1100         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1101         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1102         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1103         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1104         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1105         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1106         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1107         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1108         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1109         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1110         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1111 }
1112
1113 #[test]
1114 fn holding_cell_htlc_counting() {
1115         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1116         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1117         // commitment dance rounds.
1118         let chanmon_cfgs = create_chanmon_cfgs(3);
1119         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1120         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1121         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1122         create_announced_chan_between_nodes(&nodes, 0, 1);
1123         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1124
1125         // Fetch a route in advance as we will be unable to once we're unable to send.
1126         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1127
1128         let mut payments = Vec::new();
1129         for _ in 0..50 {
1130                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1131                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1132                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1133                 payments.push((payment_preimage, payment_hash));
1134         }
1135         check_added_monitors!(nodes[1], 1);
1136
1137         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1138         assert_eq!(events.len(), 1);
1139         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1140         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1141
1142         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1143         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1144         // another HTLC.
1145         {
1146                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1147                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1148                         ), true, APIError::ChannelUnavailable { .. }, {});
1149                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1150         }
1151
1152         // This should also be true if we try to forward a payment.
1153         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1154         {
1155                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1156                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1157                 check_added_monitors!(nodes[0], 1);
1158         }
1159
1160         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1161         assert_eq!(events.len(), 1);
1162         let payment_event = SendEvent::from_event(events.pop().unwrap());
1163         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1164
1165         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1166         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1167         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1168         // fails), the second will process the resulting failure and fail the HTLC backward.
1169         expect_pending_htlcs_forwardable!(nodes[1]);
1170         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 }]);
1171         check_added_monitors!(nodes[1], 1);
1172
1173         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1174         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1175         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1176
1177         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1178
1179         // Now forward all the pending HTLCs and claim them back
1180         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1181         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1182         check_added_monitors!(nodes[2], 1);
1183
1184         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1185         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1186         check_added_monitors!(nodes[1], 1);
1187         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1188
1189         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1190         check_added_monitors!(nodes[1], 1);
1191         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1192
1193         for ref update in as_updates.update_add_htlcs.iter() {
1194                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1195         }
1196         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1197         check_added_monitors!(nodes[2], 1);
1198         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1199         check_added_monitors!(nodes[2], 1);
1200         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1201
1202         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1203         check_added_monitors!(nodes[1], 1);
1204         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1205         check_added_monitors!(nodes[1], 1);
1206         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1207
1208         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1209         check_added_monitors!(nodes[2], 1);
1210
1211         expect_pending_htlcs_forwardable!(nodes[2]);
1212
1213         let events = nodes[2].node.get_and_clear_pending_events();
1214         assert_eq!(events.len(), payments.len());
1215         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1216                 match event {
1217                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1218                                 assert_eq!(*payment_hash, *hash);
1219                         },
1220                         _ => panic!("Unexpected event"),
1221                 };
1222         }
1223
1224         for (preimage, _) in payments.drain(..) {
1225                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1226         }
1227
1228         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1229 }
1230
1231 #[test]
1232 fn duplicate_htlc_test() {
1233         // Test that we accept duplicate payment_hash HTLCs across the network and that
1234         // claiming/failing them are all separate and don't affect each other
1235         let chanmon_cfgs = create_chanmon_cfgs(6);
1236         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1237         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1238         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1239
1240         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1241         create_announced_chan_between_nodes(&nodes, 0, 3);
1242         create_announced_chan_between_nodes(&nodes, 1, 3);
1243         create_announced_chan_between_nodes(&nodes, 2, 3);
1244         create_announced_chan_between_nodes(&nodes, 3, 4);
1245         create_announced_chan_between_nodes(&nodes, 3, 5);
1246
1247         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1248
1249         *nodes[0].network_payment_count.borrow_mut() -= 1;
1250         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1251
1252         *nodes[0].network_payment_count.borrow_mut() -= 1;
1253         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1254
1255         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1256         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1257         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1258 }
1259
1260 #[test]
1261 fn test_duplicate_htlc_different_direction_onchain() {
1262         // Test that ChannelMonitor doesn't generate 2 preimage txn
1263         // when we have 2 HTLCs with same preimage that go across a node
1264         // in opposite directions, even with the same payment secret.
1265         let chanmon_cfgs = create_chanmon_cfgs(2);
1266         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1267         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1268         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1269
1270         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1271
1272         // balancing
1273         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1274
1275         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1276
1277         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1278         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1279         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1280
1281         // Provide preimage to node 0 by claiming payment
1282         nodes[0].node.claim_funds(payment_preimage);
1283         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1284         check_added_monitors!(nodes[0], 1);
1285
1286         // Broadcast node 1 commitment txn
1287         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1288
1289         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1290         let mut has_both_htlcs = 0; // check htlcs match ones committed
1291         for outp in remote_txn[0].output.iter() {
1292                 if outp.value == 800_000 / 1000 {
1293                         has_both_htlcs += 1;
1294                 } else if outp.value == 900_000 / 1000 {
1295                         has_both_htlcs += 1;
1296                 }
1297         }
1298         assert_eq!(has_both_htlcs, 2);
1299
1300         mine_transaction(&nodes[0], &remote_txn[0]);
1301         check_added_monitors!(nodes[0], 1);
1302         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1303         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1304
1305         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1306         assert_eq!(claim_txn.len(), 3);
1307
1308         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1309         check_spends!(claim_txn[1], remote_txn[0]);
1310         check_spends!(claim_txn[2], remote_txn[0]);
1311         let preimage_tx = &claim_txn[0];
1312         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1313                 (&claim_txn[1], &claim_txn[2])
1314         } else {
1315                 (&claim_txn[2], &claim_txn[1])
1316         };
1317
1318         assert_eq!(preimage_tx.input.len(), 1);
1319         assert_eq!(preimage_bump_tx.input.len(), 1);
1320
1321         assert_eq!(preimage_tx.input.len(), 1);
1322         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1323         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1324
1325         assert_eq!(timeout_tx.input.len(), 1);
1326         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1327         check_spends!(timeout_tx, remote_txn[0]);
1328         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1329
1330         let events = nodes[0].node.get_and_clear_pending_msg_events();
1331         assert_eq!(events.len(), 3);
1332         for e in events {
1333                 match e {
1334                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1335                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1336                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1337                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1338                         },
1339                         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, .. } } => {
1340                                 assert!(update_add_htlcs.is_empty());
1341                                 assert!(update_fail_htlcs.is_empty());
1342                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1343                                 assert!(update_fail_malformed_htlcs.is_empty());
1344                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1345                         },
1346                         _ => panic!("Unexpected event"),
1347                 }
1348         }
1349 }
1350
1351 #[test]
1352 fn test_basic_channel_reserve() {
1353         let chanmon_cfgs = create_chanmon_cfgs(2);
1354         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1355         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1356         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1357         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1358
1359         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1360         let channel_reserve = chan_stat.channel_reserve_msat;
1361
1362         // The 2* and +1 are for the fee spike reserve.
1363         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));
1364         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1365         let (mut route, our_payment_hash, _, our_payment_secret) =
1366                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1367         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1368         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1369                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1370         match err {
1371                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1372                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1373                         else { panic!("Unexpected error variant"); }
1374                 },
1375                 _ => panic!("Unexpected error variant"),
1376         }
1377         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1378
1379         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1380 }
1381
1382 #[test]
1383 fn test_fee_spike_violation_fails_htlc() {
1384         let chanmon_cfgs = create_chanmon_cfgs(2);
1385         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1386         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1387         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1388         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1389
1390         let (mut route, payment_hash, _, payment_secret) =
1391                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1392         route.paths[0].hops[0].fee_msat += 1;
1393         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1394         let secp_ctx = Secp256k1::new();
1395         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1396
1397         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1398
1399         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1400         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1401                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1402         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1403         let msg = msgs::UpdateAddHTLC {
1404                 channel_id: chan.2,
1405                 htlc_id: 0,
1406                 amount_msat: htlc_msat,
1407                 payment_hash: payment_hash,
1408                 cltv_expiry: htlc_cltv,
1409                 onion_routing_packet: onion_packet,
1410                 skimmed_fee_msat: None,
1411         };
1412
1413         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1414
1415         // Now manually create the commitment_signed message corresponding to the update_add
1416         // nodes[0] just sent. In the code for construction of this message, "local" refers
1417         // to the sender of the message, and "remote" refers to the receiver.
1418
1419         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1420
1421         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1422
1423         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1424         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1425         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1426                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1427                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1428                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1429                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1430                 ).flatten().unwrap();
1431                 let chan_signer = local_chan.get_signer();
1432                 // Make the signer believe we validated another commitment, so we can release the secret
1433                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1434
1435                 let pubkeys = chan_signer.as_ref().pubkeys();
1436                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1437                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1438                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1439                  chan_signer.as_ref().pubkeys().funding_pubkey)
1440         };
1441         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1442                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1443                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1444                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1445                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1446                 ).flatten().unwrap();
1447                 let chan_signer = remote_chan.get_signer();
1448                 let pubkeys = chan_signer.as_ref().pubkeys();
1449                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1450                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1451                  chan_signer.as_ref().pubkeys().funding_pubkey)
1452         };
1453
1454         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1455         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1456                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1457
1458         // Build the remote commitment transaction so we can sign it, and then later use the
1459         // signature for the commitment_signed message.
1460         let local_chan_balance = 1313;
1461
1462         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1463                 offered: false,
1464                 amount_msat: 3460001,
1465                 cltv_expiry: htlc_cltv,
1466                 payment_hash,
1467                 transaction_output_index: Some(1),
1468         };
1469
1470         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1471
1472         let res = {
1473                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1474                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1475                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1476                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1477                 ).flatten().unwrap();
1478                 let local_chan_signer = local_chan.get_signer();
1479                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1480                         commitment_number,
1481                         95000,
1482                         local_chan_balance,
1483                         local_funding, remote_funding,
1484                         commit_tx_keys.clone(),
1485                         feerate_per_kw,
1486                         &mut vec![(accepted_htlc_info, ())],
1487                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1488                 );
1489                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1490         };
1491
1492         let commit_signed_msg = msgs::CommitmentSigned {
1493                 channel_id: chan.2,
1494                 signature: res.0,
1495                 htlc_signatures: res.1,
1496                 #[cfg(taproot)]
1497                 partial_signature_with_nonce: None,
1498         };
1499
1500         // Send the commitment_signed message to the nodes[1].
1501         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1502         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1503
1504         // Send the RAA to nodes[1].
1505         let raa_msg = msgs::RevokeAndACK {
1506                 channel_id: chan.2,
1507                 per_commitment_secret: local_secret,
1508                 next_per_commitment_point: next_local_point,
1509                 #[cfg(taproot)]
1510                 next_local_nonce: None,
1511         };
1512         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1513
1514         let events = nodes[1].node.get_and_clear_pending_msg_events();
1515         assert_eq!(events.len(), 1);
1516         // Make sure the HTLC failed in the way we expect.
1517         match events[0] {
1518                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1519                         assert_eq!(update_fail_htlcs.len(), 1);
1520                         update_fail_htlcs[0].clone()
1521                 },
1522                 _ => panic!("Unexpected event"),
1523         };
1524         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1525                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1526
1527         check_added_monitors!(nodes[1], 2);
1528 }
1529
1530 #[test]
1531 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1532         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1533         // Set the fee rate for the channel very high, to the point where the fundee
1534         // sending any above-dust amount would result in a channel reserve violation.
1535         // In this test we check that we would be prevented from sending an HTLC in
1536         // this situation.
1537         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1540         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1541         let default_config = UserConfig::default();
1542         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1543
1544         let mut push_amt = 100_000_000;
1545         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1546
1547         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1548
1549         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1550
1551         // Fetch a route in advance as we will be unable to once we're unable to send.
1552         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1553         // Sending exactly enough to hit the reserve amount should be accepted
1554         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1555                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1556         }
1557
1558         // However one more HTLC should be significantly over the reserve amount and fail.
1559         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1560                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1561                 ), true, APIError::ChannelUnavailable { .. }, {});
1562         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1563 }
1564
1565 #[test]
1566 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1567         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1568         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1569         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1571         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1572         let default_config = UserConfig::default();
1573         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1574
1575         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1576         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1577         // transaction fee with 0 HTLCs (183 sats)).
1578         let mut push_amt = 100_000_000;
1579         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1580         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1581         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1582
1583         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1584         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1585                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1586         }
1587
1588         let (mut route, payment_hash, _, payment_secret) =
1589                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1590         route.paths[0].hops[0].fee_msat = 700_000;
1591         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1592         let secp_ctx = Secp256k1::new();
1593         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1594         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1595         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1596         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1597                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1598         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1599         let msg = msgs::UpdateAddHTLC {
1600                 channel_id: chan.2,
1601                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1602                 amount_msat: htlc_msat,
1603                 payment_hash: payment_hash,
1604                 cltv_expiry: htlc_cltv,
1605                 onion_routing_packet: onion_packet,
1606                 skimmed_fee_msat: None,
1607         };
1608
1609         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1610         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1611         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);
1612         assert_eq!(nodes[0].node.list_channels().len(), 0);
1613         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1614         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1615         check_added_monitors!(nodes[0], 1);
1616         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() },
1617                 [nodes[1].node.get_our_node_id()], 100000);
1618 }
1619
1620 #[test]
1621 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1622         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1623         // calculating our commitment transaction fee (this was previously broken).
1624         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1625         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1626
1627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1629         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1630         let default_config = UserConfig::default();
1631         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1632
1633         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1634         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1635         // transaction fee with 0 HTLCs (183 sats)).
1636         let mut push_amt = 100_000_000;
1637         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1638         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1639         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1640
1641         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1642                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1643         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1644         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1645         // commitment transaction fee.
1646         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1647
1648         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1649         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1650                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1651         }
1652
1653         // One more than the dust amt should fail, however.
1654         let (mut route, our_payment_hash, _, our_payment_secret) =
1655                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1656         route.paths[0].hops[0].fee_msat += 1;
1657         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1658                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1659                 ), true, APIError::ChannelUnavailable { .. }, {});
1660 }
1661
1662 #[test]
1663 fn test_chan_init_feerate_unaffordability() {
1664         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1665         // channel reserve and feerate requirements.
1666         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1667         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1670         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1671         let default_config = UserConfig::default();
1672         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1673
1674         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1675         // HTLC.
1676         let mut push_amt = 100_000_000;
1677         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1678         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1679                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1680
1681         // During open, we don't have a "counterparty channel reserve" to check against, so that
1682         // requirement only comes into play on the open_channel handling side.
1683         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1684         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1685         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1686         open_channel_msg.push_msat += 1;
1687         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1688
1689         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1690         assert_eq!(msg_events.len(), 1);
1691         match msg_events[0] {
1692                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1693                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1694                 },
1695                 _ => panic!("Unexpected event"),
1696         }
1697 }
1698
1699 #[test]
1700 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1701         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1702         // calculating our counterparty's commitment transaction fee (this was previously broken).
1703         let chanmon_cfgs = create_chanmon_cfgs(2);
1704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1706         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1707         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1708
1709         let payment_amt = 46000; // Dust amount
1710         // In the previous code, these first four payments would succeed.
1711         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1712         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1713         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1714         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1715
1716         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1722
1723         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1724         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1725         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1726         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727 }
1728
1729 #[test]
1730 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1731         let chanmon_cfgs = create_chanmon_cfgs(3);
1732         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1733         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1734         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1735         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1736         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1737
1738         let feemsat = 239;
1739         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1740         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1741         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1742         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1743
1744         // Add a 2* and +1 for the fee spike reserve.
1745         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1746         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;
1747         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1748
1749         // Add a pending HTLC.
1750         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1751         let payment_event_1 = {
1752                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1753                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1754                 check_added_monitors!(nodes[0], 1);
1755
1756                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1757                 assert_eq!(events.len(), 1);
1758                 SendEvent::from_event(events.remove(0))
1759         };
1760         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1761
1762         // Attempt to trigger a channel reserve violation --> payment failure.
1763         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1764         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;
1765         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1766         let mut route_2 = route_1.clone();
1767         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1768
1769         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1770         let secp_ctx = Secp256k1::new();
1771         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1772         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1773         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1774         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1775                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1776         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1777         let msg = msgs::UpdateAddHTLC {
1778                 channel_id: chan.2,
1779                 htlc_id: 1,
1780                 amount_msat: htlc_msat + 1,
1781                 payment_hash: our_payment_hash_1,
1782                 cltv_expiry: htlc_cltv,
1783                 onion_routing_packet: onion_packet,
1784                 skimmed_fee_msat: None,
1785         };
1786
1787         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1788         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1789         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1790         assert_eq!(nodes[1].node.list_channels().len(), 1);
1791         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1792         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1793         check_added_monitors!(nodes[1], 1);
1794         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1795                 [nodes[0].node.get_our_node_id()], 100000);
1796 }
1797
1798 #[test]
1799 fn test_inbound_outbound_capacity_is_not_zero() {
1800         let chanmon_cfgs = create_chanmon_cfgs(2);
1801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1804         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1805         let channels0 = node_chanmgrs[0].list_channels();
1806         let channels1 = node_chanmgrs[1].list_channels();
1807         let default_config = UserConfig::default();
1808         assert_eq!(channels0.len(), 1);
1809         assert_eq!(channels1.len(), 1);
1810
1811         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1812         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1813         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1814
1815         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1816         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1817 }
1818
1819 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1820         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1821 }
1822
1823 #[test]
1824 fn test_channel_reserve_holding_cell_htlcs() {
1825         let chanmon_cfgs = create_chanmon_cfgs(3);
1826         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1827         // When this test was written, the default base fee floated based on the HTLC count.
1828         // It is now fixed, so we simply set the fee to the expected value here.
1829         let mut config = test_default_channel_config();
1830         config.channel_config.forwarding_fee_base_msat = 239;
1831         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1832         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1833         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1834         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1835
1836         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1837         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1838
1839         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1840         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1841
1842         macro_rules! expect_forward {
1843                 ($node: expr) => {{
1844                         let mut events = $node.node.get_and_clear_pending_msg_events();
1845                         assert_eq!(events.len(), 1);
1846                         check_added_monitors!($node, 1);
1847                         let payment_event = SendEvent::from_event(events.remove(0));
1848                         payment_event
1849                 }}
1850         }
1851
1852         let feemsat = 239; // set above
1853         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1854         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1855         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1856
1857         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1858
1859         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1860         {
1861                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1862                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1863                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1864                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1865                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1866
1867                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1868                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1869                         ), true, APIError::ChannelUnavailable { .. }, {});
1870                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1871         }
1872
1873         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1874         // nodes[0]'s wealth
1875         loop {
1876                 let amt_msat = recv_value_0 + total_fee_msat;
1877                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1878                 // Also, ensure that each payment has enough to be over the dust limit to
1879                 // ensure it'll be included in each commit tx fee calculation.
1880                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1881                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1882                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1883                         break;
1884                 }
1885
1886                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1887                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1888                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1889                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1890                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1891
1892                 let (stat01_, stat11_, stat12_, stat22_) = (
1893                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1894                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1895                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1896                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1897                 );
1898
1899                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1900                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1901                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1902                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1903                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1904         }
1905
1906         // adding pending output.
1907         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1908         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1909         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1910         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1911         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1912         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1913         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1914         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1915         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1916         // policy.
1917         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1918         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1919         let amt_msat_1 = recv_value_1 + total_fee_msat;
1920
1921         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);
1922         let payment_event_1 = {
1923                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1924                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1925                 check_added_monitors!(nodes[0], 1);
1926
1927                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1928                 assert_eq!(events.len(), 1);
1929                 SendEvent::from_event(events.remove(0))
1930         };
1931         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1932
1933         // channel reserve test with htlc pending output > 0
1934         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1935         {
1936                 let mut route = route_1.clone();
1937                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1938                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1939                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1940                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1941                         ), true, APIError::ChannelUnavailable { .. }, {});
1942                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1943         }
1944
1945         // split the rest to test holding cell
1946         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1947         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1948         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1949         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1950         {
1951                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1952                 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);
1953         }
1954
1955         // now see if they go through on both sides
1956         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);
1957         // but this will stuck in the holding cell
1958         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1959                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1960         check_added_monitors!(nodes[0], 0);
1961         let events = nodes[0].node.get_and_clear_pending_events();
1962         assert_eq!(events.len(), 0);
1963
1964         // test with outbound holding cell amount > 0
1965         {
1966                 let (mut route, our_payment_hash, _, our_payment_secret) =
1967                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1968                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1969                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1970                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1971                         ), true, APIError::ChannelUnavailable { .. }, {});
1972                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1973         }
1974
1975         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);
1976         // this will also stuck in the holding cell
1977         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1978                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1979         check_added_monitors!(nodes[0], 0);
1980         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1981         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1982
1983         // flush the pending htlc
1984         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1985         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1986         check_added_monitors!(nodes[1], 1);
1987
1988         // the pending htlc should be promoted to committed
1989         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1990         check_added_monitors!(nodes[0], 1);
1991         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1992
1993         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1994         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1995         // No commitment_signed so get_event_msg's assert(len == 1) passes
1996         check_added_monitors!(nodes[0], 1);
1997
1998         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1999         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2000         check_added_monitors!(nodes[1], 1);
2001
2002         expect_pending_htlcs_forwardable!(nodes[1]);
2003
2004         let ref payment_event_11 = expect_forward!(nodes[1]);
2005         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2006         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2007
2008         expect_pending_htlcs_forwardable!(nodes[2]);
2009         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2010
2011         // flush the htlcs in the holding cell
2012         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2013         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2014         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2015         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2016         expect_pending_htlcs_forwardable!(nodes[1]);
2017
2018         let ref payment_event_3 = expect_forward!(nodes[1]);
2019         assert_eq!(payment_event_3.msgs.len(), 2);
2020         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2021         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2022
2023         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2024         expect_pending_htlcs_forwardable!(nodes[2]);
2025
2026         let events = nodes[2].node.get_and_clear_pending_events();
2027         assert_eq!(events.len(), 2);
2028         match events[0] {
2029                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2030                         assert_eq!(our_payment_hash_21, *payment_hash);
2031                         assert_eq!(recv_value_21, amount_msat);
2032                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2033                         assert_eq!(via_channel_id, Some(chan_2.2));
2034                         match &purpose {
2035                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2036                                         assert!(payment_preimage.is_none());
2037                                         assert_eq!(our_payment_secret_21, *payment_secret);
2038                                 },
2039                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2040                         }
2041                 },
2042                 _ => panic!("Unexpected event"),
2043         }
2044         match events[1] {
2045                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2046                         assert_eq!(our_payment_hash_22, *payment_hash);
2047                         assert_eq!(recv_value_22, amount_msat);
2048                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2049                         assert_eq!(via_channel_id, Some(chan_2.2));
2050                         match &purpose {
2051                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2052                                         assert!(payment_preimage.is_none());
2053                                         assert_eq!(our_payment_secret_22, *payment_secret);
2054                                 },
2055                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2056                         }
2057                 },
2058                 _ => panic!("Unexpected event"),
2059         }
2060
2061         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2062         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2063         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2064
2065         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2066         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2067         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2068
2069         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2070         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);
2071         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2072         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2073         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2074
2075         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2076         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2077 }
2078
2079 #[test]
2080 fn channel_reserve_in_flight_removes() {
2081         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2082         // can send to its counterparty, but due to update ordering, the other side may not yet have
2083         // considered those HTLCs fully removed.
2084         // This tests that we don't count HTLCs which will not be included in the next remote
2085         // commitment transaction towards the reserve value (as it implies no commitment transaction
2086         // will be generated which violates the remote reserve value).
2087         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2088         // To test this we:
2089         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2090         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2091         //    you only consider the value of the first HTLC, it may not),
2092         //  * start routing a third HTLC from A to B,
2093         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2094         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2095         //  * deliver the first fulfill from B
2096         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2097         //    claim,
2098         //  * deliver A's response CS and RAA.
2099         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2100         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2101         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2102         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2103         let chanmon_cfgs = create_chanmon_cfgs(2);
2104         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2105         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2106         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2107         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2108
2109         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2110         // Route the first two HTLCs.
2111         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2112         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2113         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2114
2115         // Start routing the third HTLC (this is just used to get everyone in the right state).
2116         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2117         let send_1 = {
2118                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2119                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2120                 check_added_monitors!(nodes[0], 1);
2121                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2122                 assert_eq!(events.len(), 1);
2123                 SendEvent::from_event(events.remove(0))
2124         };
2125
2126         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2127         // initial fulfill/CS.
2128         nodes[1].node.claim_funds(payment_preimage_1);
2129         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2130         check_added_monitors!(nodes[1], 1);
2131         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2132
2133         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2134         // remove the second HTLC when we send the HTLC back from B to A.
2135         nodes[1].node.claim_funds(payment_preimage_2);
2136         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2137         check_added_monitors!(nodes[1], 1);
2138         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2139
2140         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2141         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2142         check_added_monitors!(nodes[0], 1);
2143         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2144         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2145
2146         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2147         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2148         check_added_monitors!(nodes[1], 1);
2149         // B is already AwaitingRAA, so cant generate a CS here
2150         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2151
2152         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2153         check_added_monitors!(nodes[1], 1);
2154         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2155
2156         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2157         check_added_monitors!(nodes[0], 1);
2158         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2159
2160         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2161         check_added_monitors!(nodes[1], 1);
2162         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2163
2164         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2165         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2166         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2167         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2168         // on-chain as necessary).
2169         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2170         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2171         check_added_monitors!(nodes[0], 1);
2172         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2173         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2174
2175         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2176         check_added_monitors!(nodes[1], 1);
2177         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2178
2179         expect_pending_htlcs_forwardable!(nodes[1]);
2180         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2181
2182         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2183         // resolve the second HTLC from A's point of view.
2184         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2185         check_added_monitors!(nodes[0], 1);
2186         expect_payment_path_successful!(nodes[0]);
2187         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2188
2189         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2190         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2191         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2192         let send_2 = {
2193                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2194                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2195                 check_added_monitors!(nodes[1], 1);
2196                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2197                 assert_eq!(events.len(), 1);
2198                 SendEvent::from_event(events.remove(0))
2199         };
2200
2201         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2202         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2203         check_added_monitors!(nodes[0], 1);
2204         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2205
2206         // Now just resolve all the outstanding messages/HTLCs for completeness...
2207
2208         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2209         check_added_monitors!(nodes[1], 1);
2210         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2211
2212         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2213         check_added_monitors!(nodes[1], 1);
2214
2215         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2216         check_added_monitors!(nodes[0], 1);
2217         expect_payment_path_successful!(nodes[0]);
2218         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2219
2220         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2221         check_added_monitors!(nodes[1], 1);
2222         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2223
2224         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2225         check_added_monitors!(nodes[0], 1);
2226
2227         expect_pending_htlcs_forwardable!(nodes[0]);
2228         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2229
2230         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2231         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2232 }
2233
2234 #[test]
2235 fn channel_monitor_network_test() {
2236         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2237         // tests that ChannelMonitor is able to recover from various states.
2238         let chanmon_cfgs = create_chanmon_cfgs(5);
2239         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2240         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2241         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2242
2243         // Create some initial channels
2244         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2245         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2246         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2247         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2248
2249         // Make sure all nodes are at the same starting height
2250         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2251         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2252         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2253         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2254         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2255
2256         // Rebalance the network a bit by relaying one payment through all the channels...
2257         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2258         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2259         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2260         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2261
2262         // Simple case with no pending HTLCs:
2263         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2264         check_added_monitors!(nodes[1], 1);
2265         check_closed_broadcast!(nodes[1], true);
2266         {
2267                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2268                 assert_eq!(node_txn.len(), 1);
2269                 mine_transaction(&nodes[0], &node_txn[0]);
2270                 check_added_monitors!(nodes[0], 1);
2271                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2272         }
2273         check_closed_broadcast!(nodes[0], true);
2274         assert_eq!(nodes[0].node.list_channels().len(), 0);
2275         assert_eq!(nodes[1].node.list_channels().len(), 1);
2276         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2277         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2278
2279         // One pending HTLC is discarded by the force-close:
2280         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2281
2282         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2283         // broadcasted until we reach the timelock time).
2284         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2285         check_closed_broadcast!(nodes[1], true);
2286         check_added_monitors!(nodes[1], 1);
2287         {
2288                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2289                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2290                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2291                 mine_transaction(&nodes[2], &node_txn[0]);
2292                 check_added_monitors!(nodes[2], 1);
2293                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2294         }
2295         check_closed_broadcast!(nodes[2], true);
2296         assert_eq!(nodes[1].node.list_channels().len(), 0);
2297         assert_eq!(nodes[2].node.list_channels().len(), 1);
2298         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2299         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2300
2301         macro_rules! claim_funds {
2302                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2303                         {
2304                                 $node.node.claim_funds($preimage);
2305                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2306                                 check_added_monitors!($node, 1);
2307
2308                                 let events = $node.node.get_and_clear_pending_msg_events();
2309                                 assert_eq!(events.len(), 1);
2310                                 match events[0] {
2311                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2312                                                 assert!(update_add_htlcs.is_empty());
2313                                                 assert!(update_fail_htlcs.is_empty());
2314                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2315                                         },
2316                                         _ => panic!("Unexpected event"),
2317                                 };
2318                         }
2319                 }
2320         }
2321
2322         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2323         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2324         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2325         check_added_monitors!(nodes[2], 1);
2326         check_closed_broadcast!(nodes[2], true);
2327         let node2_commitment_txid;
2328         {
2329                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2330                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2331                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2332                 node2_commitment_txid = node_txn[0].txid();
2333
2334                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2335                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2336                 mine_transaction(&nodes[3], &node_txn[0]);
2337                 check_added_monitors!(nodes[3], 1);
2338                 check_preimage_claim(&nodes[3], &node_txn);
2339         }
2340         check_closed_broadcast!(nodes[3], true);
2341         assert_eq!(nodes[2].node.list_channels().len(), 0);
2342         assert_eq!(nodes[3].node.list_channels().len(), 1);
2343         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2344         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2345
2346         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2347         // confusing us in the following tests.
2348         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2349
2350         // One pending HTLC to time out:
2351         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2352         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2353         // buffer space).
2354
2355         let (close_chan_update_1, close_chan_update_2) = {
2356                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2357                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2358                 assert_eq!(events.len(), 2);
2359                 let close_chan_update_1 = match events[0] {
2360                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2361                                 msg.clone()
2362                         },
2363                         _ => panic!("Unexpected event"),
2364                 };
2365                 match events[1] {
2366                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2367                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2368                         },
2369                         _ => panic!("Unexpected event"),
2370                 }
2371                 check_added_monitors!(nodes[3], 1);
2372
2373                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2374                 {
2375                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2376                         node_txn.retain(|tx| {
2377                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2378                                         false
2379                                 } else { true }
2380                         });
2381                 }
2382
2383                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2384
2385                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2386                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2387
2388                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2389                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2390                 assert_eq!(events.len(), 2);
2391                 let close_chan_update_2 = match events[0] {
2392                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2393                                 msg.clone()
2394                         },
2395                         _ => panic!("Unexpected event"),
2396                 };
2397                 match events[1] {
2398                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2399                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2400                         },
2401                         _ => panic!("Unexpected event"),
2402                 }
2403                 check_added_monitors!(nodes[4], 1);
2404                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2405
2406                 mine_transaction(&nodes[4], &node_txn[0]);
2407                 check_preimage_claim(&nodes[4], &node_txn);
2408                 (close_chan_update_1, close_chan_update_2)
2409         };
2410         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2411         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2412         assert_eq!(nodes[3].node.list_channels().len(), 0);
2413         assert_eq!(nodes[4].node.list_channels().len(), 0);
2414
2415         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2416                 ChannelMonitorUpdateStatus::Completed);
2417         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2418         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2419 }
2420
2421 #[test]
2422 fn test_justice_tx_htlc_timeout() {
2423         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2424         let mut alice_config = UserConfig::default();
2425         alice_config.channel_handshake_config.announced_channel = true;
2426         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2427         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2428         let mut bob_config = UserConfig::default();
2429         bob_config.channel_handshake_config.announced_channel = true;
2430         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2431         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2432         let user_cfgs = [Some(alice_config), Some(bob_config)];
2433         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2434         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2435         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2436         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2437         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2438         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2439         // Create some new channels:
2440         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2441
2442         // A pending HTLC which will be revoked:
2443         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2444         // Get the will-be-revoked local txn from nodes[0]
2445         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2446         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2447         assert_eq!(revoked_local_txn[0].input.len(), 1);
2448         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2449         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2450         assert_eq!(revoked_local_txn[1].input.len(), 1);
2451         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2452         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2453         // Revoke the old state
2454         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2455
2456         {
2457                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2458                 {
2459                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2460                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2461                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2462                         check_spends!(node_txn[0], revoked_local_txn[0]);
2463                         node_txn.swap_remove(0);
2464                 }
2465                 check_added_monitors!(nodes[1], 1);
2466                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2467                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2468
2469                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2470                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2471                 // Verify broadcast of revoked HTLC-timeout
2472                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2473                 check_added_monitors!(nodes[0], 1);
2474                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2475                 // Broadcast revoked HTLC-timeout on node 1
2476                 mine_transaction(&nodes[1], &node_txn[1]);
2477                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2478         }
2479         get_announce_close_broadcast_events(&nodes, 0, 1);
2480         assert_eq!(nodes[0].node.list_channels().len(), 0);
2481         assert_eq!(nodes[1].node.list_channels().len(), 0);
2482 }
2483
2484 #[test]
2485 fn test_justice_tx_htlc_success() {
2486         // Test justice txn built on revoked HTLC-Success tx, against both sides
2487         let mut alice_config = UserConfig::default();
2488         alice_config.channel_handshake_config.announced_channel = true;
2489         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2490         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2491         let mut bob_config = UserConfig::default();
2492         bob_config.channel_handshake_config.announced_channel = true;
2493         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2494         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2495         let user_cfgs = [Some(alice_config), Some(bob_config)];
2496         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2497         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2498         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2501         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2502         // Create some new channels:
2503         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2504
2505         // A pending HTLC which will be revoked:
2506         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2507         // Get the will-be-revoked local txn from B
2508         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2509         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2510         assert_eq!(revoked_local_txn[0].input.len(), 1);
2511         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2512         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2513         // Revoke the old state
2514         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2515         {
2516                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2517                 {
2518                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2519                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2520                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2521
2522                         check_spends!(node_txn[0], revoked_local_txn[0]);
2523                         node_txn.swap_remove(0);
2524                 }
2525                 check_added_monitors!(nodes[0], 1);
2526                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2527
2528                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2529                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2530                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2531                 check_added_monitors!(nodes[1], 1);
2532                 mine_transaction(&nodes[0], &node_txn[1]);
2533                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2534                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2535         }
2536         get_announce_close_broadcast_events(&nodes, 0, 1);
2537         assert_eq!(nodes[0].node.list_channels().len(), 0);
2538         assert_eq!(nodes[1].node.list_channels().len(), 0);
2539 }
2540
2541 #[test]
2542 fn revoked_output_claim() {
2543         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2544         // transaction is broadcast by its counterparty
2545         let chanmon_cfgs = create_chanmon_cfgs(2);
2546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2548         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2549         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2550         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2551         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2552         assert_eq!(revoked_local_txn.len(), 1);
2553         // Only output is the full channel value back to nodes[0]:
2554         assert_eq!(revoked_local_txn[0].output.len(), 1);
2555         // Send a payment through, updating everyone's latest commitment txn
2556         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2557
2558         // Inform nodes[1] that nodes[0] broadcast a stale tx
2559         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2560         check_added_monitors!(nodes[1], 1);
2561         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2562         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2563         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2564
2565         check_spends!(node_txn[0], revoked_local_txn[0]);
2566
2567         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2568         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2569         get_announce_close_broadcast_events(&nodes, 0, 1);
2570         check_added_monitors!(nodes[0], 1);
2571         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2572 }
2573
2574 #[test]
2575 fn test_forming_justice_tx_from_monitor_updates() {
2576         do_test_forming_justice_tx_from_monitor_updates(true);
2577         do_test_forming_justice_tx_from_monitor_updates(false);
2578 }
2579
2580 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2581         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2582         // is properly formed and can be broadcasted/confirmed successfully in the event
2583         // that a revoked commitment transaction is broadcasted
2584         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2585         let chanmon_cfgs = create_chanmon_cfgs(2);
2586         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2587         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2588         let persisters = vec![WatchtowerPersister::new(destination_script0),
2589                 WatchtowerPersister::new(destination_script1)];
2590         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2591         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2592         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2593         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2594         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2595
2596         if !broadcast_initial_commitment {
2597                 // Send a payment to move the channel forward
2598                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2599         }
2600
2601         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2602         // We'll keep this commitment transaction to broadcast once it's revoked.
2603         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2604         assert_eq!(revoked_local_txn.len(), 1);
2605         let revoked_commitment_tx = &revoked_local_txn[0];
2606
2607         // Send another payment, now revoking the previous commitment tx
2608         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2609
2610         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2611         check_spends!(justice_tx, revoked_commitment_tx);
2612
2613         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2614         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2615
2616         check_added_monitors!(nodes[1], 1);
2617         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2618                 &[nodes[0].node.get_our_node_id()], 100_000);
2619         get_announce_close_broadcast_events(&nodes, 1, 0);
2620
2621         check_added_monitors!(nodes[0], 1);
2622         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2623                 &[nodes[1].node.get_our_node_id()], 100_000);
2624
2625         // Check that the justice tx has sent the revoked output value to nodes[1]
2626         let monitor = get_monitor!(nodes[1], channel_id);
2627         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2628                 match balance {
2629                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2630                         _ => panic!("Unexpected balance type"),
2631                 }
2632         });
2633         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2634         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2635         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2636         assert_eq!(total_claimable_balance, expected_claimable_balance);
2637 }
2638
2639
2640 #[test]
2641 fn claim_htlc_outputs_shared_tx() {
2642         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2643         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2644         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2648
2649         // Create some new channel:
2650         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2651
2652         // Rebalance the network to generate htlc in the two directions
2653         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2654         // 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
2655         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2656         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2657
2658         // Get the will-be-revoked local txn from node[0]
2659         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2660         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2661         assert_eq!(revoked_local_txn[0].input.len(), 1);
2662         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2663         assert_eq!(revoked_local_txn[1].input.len(), 1);
2664         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2665         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2666         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2667
2668         //Revoke the old state
2669         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2670
2671         {
2672                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2673                 check_added_monitors!(nodes[0], 1);
2674                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2675                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2676                 check_added_monitors!(nodes[1], 1);
2677                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2678                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2679                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2680
2681                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2682                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2683
2684                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2685                 check_spends!(node_txn[0], revoked_local_txn[0]);
2686
2687                 let mut witness_lens = BTreeSet::new();
2688                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2689                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2690                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2691                 assert_eq!(witness_lens.len(), 3);
2692                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2693                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2694                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2695
2696                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2697                 // ANTI_REORG_DELAY confirmations.
2698                 mine_transaction(&nodes[1], &node_txn[0]);
2699                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2700                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2701         }
2702         get_announce_close_broadcast_events(&nodes, 0, 1);
2703         assert_eq!(nodes[0].node.list_channels().len(), 0);
2704         assert_eq!(nodes[1].node.list_channels().len(), 0);
2705 }
2706
2707 #[test]
2708 fn claim_htlc_outputs_single_tx() {
2709         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2710         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2711         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2712         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2713         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2714         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2715
2716         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2717
2718         // Rebalance the network to generate htlc in the two directions
2719         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2720         // 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
2721         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2722         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2723         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2724
2725         // Get the will-be-revoked local txn from node[0]
2726         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2727
2728         //Revoke the old state
2729         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2730
2731         {
2732                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2733                 check_added_monitors!(nodes[0], 1);
2734                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2735                 check_added_monitors!(nodes[1], 1);
2736                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2737                 let mut events = nodes[0].node.get_and_clear_pending_events();
2738                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2739                 match events.last().unwrap() {
2740                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2741                         _ => panic!("Unexpected event"),
2742                 }
2743
2744                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2745                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2746
2747                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2748
2749                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2750                 assert_eq!(node_txn[0].input.len(), 1);
2751                 check_spends!(node_txn[0], chan_1.3);
2752                 assert_eq!(node_txn[1].input.len(), 1);
2753                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2754                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2755                 check_spends!(node_txn[1], node_txn[0]);
2756
2757                 // Filter out any non justice transactions.
2758                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2759                 assert!(node_txn.len() > 3);
2760
2761                 assert_eq!(node_txn[0].input.len(), 1);
2762                 assert_eq!(node_txn[1].input.len(), 1);
2763                 assert_eq!(node_txn[2].input.len(), 1);
2764
2765                 check_spends!(node_txn[0], revoked_local_txn[0]);
2766                 check_spends!(node_txn[1], revoked_local_txn[0]);
2767                 check_spends!(node_txn[2], revoked_local_txn[0]);
2768
2769                 let mut witness_lens = BTreeSet::new();
2770                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2771                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2772                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2773                 assert_eq!(witness_lens.len(), 3);
2774                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2775                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2776                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2777
2778                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2779                 // ANTI_REORG_DELAY confirmations.
2780                 mine_transaction(&nodes[1], &node_txn[0]);
2781                 mine_transaction(&nodes[1], &node_txn[1]);
2782                 mine_transaction(&nodes[1], &node_txn[2]);
2783                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2784                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2785         }
2786         get_announce_close_broadcast_events(&nodes, 0, 1);
2787         assert_eq!(nodes[0].node.list_channels().len(), 0);
2788         assert_eq!(nodes[1].node.list_channels().len(), 0);
2789 }
2790
2791 #[test]
2792 fn test_htlc_on_chain_success() {
2793         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2794         // the preimage backward accordingly. So here we test that ChannelManager is
2795         // broadcasting the right event to other nodes in payment path.
2796         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2797         // A --------------------> B ----------------------> C (preimage)
2798         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2799         // commitment transaction was broadcast.
2800         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2801         // towards B.
2802         // B should be able to claim via preimage if A then broadcasts its local tx.
2803         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2804         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2805         // PaymentSent event).
2806
2807         let chanmon_cfgs = create_chanmon_cfgs(3);
2808         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2809         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2810         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2811
2812         // Create some initial channels
2813         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2814         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2815
2816         // Ensure all nodes are at the same height
2817         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2818         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2819         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2820         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2821
2822         // Rebalance the network a bit by relaying one payment through all the channels...
2823         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2824         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2825
2826         let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2827         let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2828
2829         // Broadcast legit commitment tx from C on B's chain
2830         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2831         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2832         assert_eq!(commitment_tx.len(), 1);
2833         check_spends!(commitment_tx[0], chan_2.3);
2834         nodes[2].node.claim_funds(our_payment_preimage);
2835         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2836         nodes[2].node.claim_funds(our_payment_preimage_2);
2837         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2838         check_added_monitors!(nodes[2], 2);
2839         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2840         assert!(updates.update_add_htlcs.is_empty());
2841         assert!(updates.update_fail_htlcs.is_empty());
2842         assert!(updates.update_fail_malformed_htlcs.is_empty());
2843         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2844
2845         mine_transaction(&nodes[2], &commitment_tx[0]);
2846         check_closed_broadcast!(nodes[2], true);
2847         check_added_monitors!(nodes[2], 1);
2848         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2849         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2850         assert_eq!(node_txn.len(), 2);
2851         check_spends!(node_txn[0], commitment_tx[0]);
2852         check_spends!(node_txn[1], commitment_tx[0]);
2853         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2855         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2856         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2857         assert_eq!(node_txn[0].lock_time.0, 0);
2858         assert_eq!(node_txn[1].lock_time.0, 0);
2859
2860         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2861         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()]));
2862         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2863         {
2864                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2865                 assert_eq!(added_monitors.len(), 1);
2866                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2867                 added_monitors.clear();
2868         }
2869         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2870         assert_eq!(forwarded_events.len(), 3);
2871         match forwarded_events[0] {
2872                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2873                 _ => panic!("Unexpected event"),
2874         }
2875         let chan_id = Some(chan_1.2);
2876         match forwarded_events[1] {
2877                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2878                         assert_eq!(fee_earned_msat, Some(1000));
2879                         assert_eq!(prev_channel_id, chan_id);
2880                         assert_eq!(claim_from_onchain_tx, true);
2881                         assert_eq!(next_channel_id, Some(chan_2.2));
2882                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2883                 },
2884                 _ => panic!()
2885         }
2886         match forwarded_events[2] {
2887                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2888                         assert_eq!(fee_earned_msat, Some(1000));
2889                         assert_eq!(prev_channel_id, chan_id);
2890                         assert_eq!(claim_from_onchain_tx, true);
2891                         assert_eq!(next_channel_id, Some(chan_2.2));
2892                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2893                 },
2894                 _ => panic!()
2895         }
2896         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2897         {
2898                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2899                 assert_eq!(added_monitors.len(), 2);
2900                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2901                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2902                 added_monitors.clear();
2903         }
2904         assert_eq!(events.len(), 3);
2905
2906         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2907         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2908
2909         match nodes_2_event {
2910                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2911                 _ => panic!("Unexpected event"),
2912         }
2913
2914         match nodes_0_event {
2915                 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, .. } } => {
2916                         assert!(update_add_htlcs.is_empty());
2917                         assert!(update_fail_htlcs.is_empty());
2918                         assert_eq!(update_fulfill_htlcs.len(), 1);
2919                         assert!(update_fail_malformed_htlcs.is_empty());
2920                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2921                 },
2922                 _ => panic!("Unexpected event"),
2923         };
2924
2925         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2926         match events[0] {
2927                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2928                 _ => panic!("Unexpected event"),
2929         }
2930
2931         macro_rules! check_tx_local_broadcast {
2932                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2933                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2934                         assert_eq!(node_txn.len(), 2);
2935                         // Node[1]: 2 * HTLC-timeout tx
2936                         // Node[0]: 2 * HTLC-timeout tx
2937                         check_spends!(node_txn[0], $commitment_tx);
2938                         check_spends!(node_txn[1], $commitment_tx);
2939                         assert_ne!(node_txn[0].lock_time.0, 0);
2940                         assert_ne!(node_txn[1].lock_time.0, 0);
2941                         if $htlc_offered {
2942                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2943                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2944                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2945                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2946                         } else {
2947                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2948                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2949                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2950                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2951                         }
2952                         node_txn.clear();
2953                 } }
2954         }
2955         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2956         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2957
2958         // Broadcast legit commitment tx from A on B's chain
2959         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2960         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2961         check_spends!(node_a_commitment_tx[0], chan_1.3);
2962         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2963         check_closed_broadcast!(nodes[1], true);
2964         check_added_monitors!(nodes[1], 1);
2965         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2966         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2967         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2968         let commitment_spend =
2969                 if node_txn.len() == 1 {
2970                         &node_txn[0]
2971                 } else {
2972                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2973                         // FullBlockViaListen
2974                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2975                                 check_spends!(node_txn[1], commitment_tx[0]);
2976                                 check_spends!(node_txn[2], commitment_tx[0]);
2977                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2978                                 &node_txn[0]
2979                         } else {
2980                                 check_spends!(node_txn[0], commitment_tx[0]);
2981                                 check_spends!(node_txn[1], commitment_tx[0]);
2982                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2983                                 &node_txn[2]
2984                         }
2985                 };
2986
2987         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2988         assert_eq!(commitment_spend.input.len(), 2);
2989         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2990         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2991         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2992         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2993         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2994         // we already checked the same situation with A.
2995
2996         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2997         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2998         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2999         check_closed_broadcast!(nodes[0], true);
3000         check_added_monitors!(nodes[0], 1);
3001         let events = nodes[0].node.get_and_clear_pending_events();
3002         assert_eq!(events.len(), 5);
3003         let mut first_claimed = false;
3004         for event in events {
3005                 match event {
3006                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3007                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3008                                         assert!(!first_claimed);
3009                                         first_claimed = true;
3010                                 } else {
3011                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3012                                         assert_eq!(payment_hash, payment_hash_2);
3013                                 }
3014                         },
3015                         Event::PaymentPathSuccessful { .. } => {},
3016                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3017                         _ => panic!("Unexpected event"),
3018                 }
3019         }
3020         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3021 }
3022
3023 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3024         // Test that in case of a unilateral close onchain, we detect the state of output and
3025         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3026         // broadcasting the right event to other nodes in payment path.
3027         // A ------------------> B ----------------------> C (timeout)
3028         //    B's commitment tx                 C's commitment tx
3029         //            \                                  \
3030         //         B's HTLC timeout tx               B's timeout tx
3031
3032         let chanmon_cfgs = create_chanmon_cfgs(3);
3033         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3034         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3035         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3036         *nodes[0].connect_style.borrow_mut() = connect_style;
3037         *nodes[1].connect_style.borrow_mut() = connect_style;
3038         *nodes[2].connect_style.borrow_mut() = connect_style;
3039
3040         // Create some intial channels
3041         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3042         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3043
3044         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3045         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3046         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3047
3048         let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3049
3050         // Broadcast legit commitment tx from C on B's chain
3051         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3052         check_spends!(commitment_tx[0], chan_2.3);
3053         nodes[2].node.fail_htlc_backwards(&payment_hash);
3054         check_added_monitors!(nodes[2], 0);
3055         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3056         check_added_monitors!(nodes[2], 1);
3057
3058         let events = nodes[2].node.get_and_clear_pending_msg_events();
3059         assert_eq!(events.len(), 1);
3060         match events[0] {
3061                 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, .. } } => {
3062                         assert!(update_add_htlcs.is_empty());
3063                         assert!(!update_fail_htlcs.is_empty());
3064                         assert!(update_fulfill_htlcs.is_empty());
3065                         assert!(update_fail_malformed_htlcs.is_empty());
3066                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3067                 },
3068                 _ => panic!("Unexpected event"),
3069         };
3070         mine_transaction(&nodes[2], &commitment_tx[0]);
3071         check_closed_broadcast!(nodes[2], true);
3072         check_added_monitors!(nodes[2], 1);
3073         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3074         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3075         assert_eq!(node_txn.len(), 0);
3076
3077         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3078         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3079         mine_transaction(&nodes[1], &commitment_tx[0]);
3080         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3081                 , [nodes[2].node.get_our_node_id()], 100000);
3082         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3083         let timeout_tx = {
3084                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3085                 if nodes[1].connect_style.borrow().skips_blocks() {
3086                         assert_eq!(txn.len(), 1);
3087                 } else {
3088                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3089                 }
3090                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3091                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3092                 txn.remove(0)
3093         };
3094
3095         mine_transaction(&nodes[1], &timeout_tx);
3096         check_added_monitors!(nodes[1], 1);
3097         check_closed_broadcast!(nodes[1], true);
3098
3099         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3100
3101         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 }]);
3102         check_added_monitors!(nodes[1], 1);
3103         let events = nodes[1].node.get_and_clear_pending_msg_events();
3104         assert_eq!(events.len(), 1);
3105         match events[0] {
3106                 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, .. } } => {
3107                         assert!(update_add_htlcs.is_empty());
3108                         assert!(!update_fail_htlcs.is_empty());
3109                         assert!(update_fulfill_htlcs.is_empty());
3110                         assert!(update_fail_malformed_htlcs.is_empty());
3111                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3112                 },
3113                 _ => panic!("Unexpected event"),
3114         };
3115
3116         // Broadcast legit commitment tx from B on A's chain
3117         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3118         check_spends!(commitment_tx[0], chan_1.3);
3119
3120         mine_transaction(&nodes[0], &commitment_tx[0]);
3121         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3122
3123         check_closed_broadcast!(nodes[0], true);
3124         check_added_monitors!(nodes[0], 1);
3125         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3126         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3127         assert_eq!(node_txn.len(), 1);
3128         check_spends!(node_txn[0], commitment_tx[0]);
3129         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3130 }
3131
3132 #[test]
3133 fn test_htlc_on_chain_timeout() {
3134         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3135         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3136         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3137 }
3138
3139 #[test]
3140 fn test_simple_commitment_revoked_fail_backward() {
3141         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3142         // and fail backward accordingly.
3143
3144         let chanmon_cfgs = create_chanmon_cfgs(3);
3145         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3146         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3147         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3148
3149         // Create some initial channels
3150         create_announced_chan_between_nodes(&nodes, 0, 1);
3151         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3152
3153         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3154         // Get the will-be-revoked local txn from nodes[2]
3155         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3156         // Revoke the old state
3157         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3158
3159         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3160
3161         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3162         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3163         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3164         check_added_monitors!(nodes[1], 1);
3165         check_closed_broadcast!(nodes[1], true);
3166
3167         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 }]);
3168         check_added_monitors!(nodes[1], 1);
3169         let events = nodes[1].node.get_and_clear_pending_msg_events();
3170         assert_eq!(events.len(), 1);
3171         match events[0] {
3172                 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, .. } } => {
3173                         assert!(update_add_htlcs.is_empty());
3174                         assert_eq!(update_fail_htlcs.len(), 1);
3175                         assert!(update_fulfill_htlcs.is_empty());
3176                         assert!(update_fail_malformed_htlcs.is_empty());
3177                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3178
3179                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3180                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3181                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3182                 },
3183                 _ => panic!("Unexpected event"),
3184         }
3185 }
3186
3187 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3188         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3189         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3190         // commitment transaction anymore.
3191         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3192         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3193         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3194         // technically disallowed and we should probably handle it reasonably.
3195         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3196         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3197         // transactions:
3198         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3199         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3200         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3201         //   and once they revoke the previous commitment transaction (allowing us to send a new
3202         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3203         let chanmon_cfgs = create_chanmon_cfgs(3);
3204         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3205         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3206         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3207
3208         // Create some initial channels
3209         create_announced_chan_between_nodes(&nodes, 0, 1);
3210         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3211
3212         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3213         // Get the will-be-revoked local txn from nodes[2]
3214         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3215         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3216         // Revoke the old state
3217         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3218
3219         let value = if use_dust {
3220                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3221                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3222                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3223                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3224         } else { 3000000 };
3225
3226         let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3227         let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3228         let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3229
3230         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3231         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3232         check_added_monitors!(nodes[2], 1);
3233         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3234         assert!(updates.update_add_htlcs.is_empty());
3235         assert!(updates.update_fulfill_htlcs.is_empty());
3236         assert!(updates.update_fail_malformed_htlcs.is_empty());
3237         assert_eq!(updates.update_fail_htlcs.len(), 1);
3238         assert!(updates.update_fee.is_none());
3239         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3240         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3241         // Drop the last RAA from 3 -> 2
3242
3243         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3244         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3245         check_added_monitors!(nodes[2], 1);
3246         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3247         assert!(updates.update_add_htlcs.is_empty());
3248         assert!(updates.update_fulfill_htlcs.is_empty());
3249         assert!(updates.update_fail_malformed_htlcs.is_empty());
3250         assert_eq!(updates.update_fail_htlcs.len(), 1);
3251         assert!(updates.update_fee.is_none());
3252         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3253         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3254         check_added_monitors!(nodes[1], 1);
3255         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3256         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3257         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3258         check_added_monitors!(nodes[2], 1);
3259
3260         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3261         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3262         check_added_monitors!(nodes[2], 1);
3263         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3264         assert!(updates.update_add_htlcs.is_empty());
3265         assert!(updates.update_fulfill_htlcs.is_empty());
3266         assert!(updates.update_fail_malformed_htlcs.is_empty());
3267         assert_eq!(updates.update_fail_htlcs.len(), 1);
3268         assert!(updates.update_fee.is_none());
3269         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3270         // At this point first_payment_hash has dropped out of the latest two commitment
3271         // transactions that nodes[1] is tracking...
3272         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3273         check_added_monitors!(nodes[1], 1);
3274         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3275         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3276         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3277         check_added_monitors!(nodes[2], 1);
3278
3279         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3280         // on nodes[2]'s RAA.
3281         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3282         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3283                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3284         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3285         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3286         check_added_monitors!(nodes[1], 0);
3287
3288         if deliver_bs_raa {
3289                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3290                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3291                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3292                 check_added_monitors!(nodes[1], 1);
3293                 let events = nodes[1].node.get_and_clear_pending_events();
3294                 assert_eq!(events.len(), 2);
3295                 match events[0] {
3296                         Event::PendingHTLCsForwardable { .. } => { },
3297                         _ => panic!("Unexpected event"),
3298                 };
3299                 match events[1] {
3300                         Event::HTLCHandlingFailed { .. } => { },
3301                         _ => panic!("Unexpected event"),
3302                 }
3303                 // Deliberately don't process the pending fail-back so they all fail back at once after
3304                 // block connection just like the !deliver_bs_raa case
3305         }
3306
3307         let mut failed_htlcs = HashSet::new();
3308         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3309
3310         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3311         check_added_monitors!(nodes[1], 1);
3312         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3313
3314         let events = nodes[1].node.get_and_clear_pending_events();
3315         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3316         match events[0] {
3317                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3318                 _ => panic!("Unexepected event"),
3319         }
3320         match events[1] {
3321                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3322                         assert_eq!(*payment_hash, fourth_payment_hash);
3323                 },
3324                 _ => panic!("Unexpected event"),
3325         }
3326         match events[2] {
3327                 Event::PaymentFailed { ref payment_hash, .. } => {
3328                         assert_eq!(*payment_hash, fourth_payment_hash);
3329                 },
3330                 _ => panic!("Unexpected event"),
3331         }
3332
3333         nodes[1].node.process_pending_htlc_forwards();
3334         check_added_monitors!(nodes[1], 1);
3335
3336         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3337         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3338
3339         if deliver_bs_raa {
3340                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3341                 match nodes_2_event {
3342                         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, .. } } => {
3343                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3344                                 assert_eq!(update_add_htlcs.len(), 1);
3345                                 assert!(update_fulfill_htlcs.is_empty());
3346                                 assert!(update_fail_htlcs.is_empty());
3347                                 assert!(update_fail_malformed_htlcs.is_empty());
3348                         },
3349                         _ => panic!("Unexpected event"),
3350                 }
3351         }
3352
3353         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3354         match nodes_2_event {
3355                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3356                         assert_eq!(channel_id, chan_2.2);
3357                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3358                 },
3359                 _ => panic!("Unexpected event"),
3360         }
3361
3362         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3363         match nodes_0_event {
3364                 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, .. } } => {
3365                         assert!(update_add_htlcs.is_empty());
3366                         assert_eq!(update_fail_htlcs.len(), 3);
3367                         assert!(update_fulfill_htlcs.is_empty());
3368                         assert!(update_fail_malformed_htlcs.is_empty());
3369                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3370
3371                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3372                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3373                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3374
3375                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3376
3377                         let events = nodes[0].node.get_and_clear_pending_events();
3378                         assert_eq!(events.len(), 6);
3379                         match events[0] {
3380                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3381                                         assert!(failed_htlcs.insert(payment_hash.0));
3382                                         // If we delivered B's RAA we got an unknown preimage error, not something
3383                                         // that we should update our routing table for.
3384                                         if !deliver_bs_raa {
3385                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3386                                         }
3387                                 },
3388                                 _ => panic!("Unexpected event"),
3389                         }
3390                         match events[1] {
3391                                 Event::PaymentFailed { ref payment_hash, .. } => {
3392                                         assert_eq!(*payment_hash, first_payment_hash);
3393                                 },
3394                                 _ => panic!("Unexpected event"),
3395                         }
3396                         match events[2] {
3397                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3398                                         assert!(failed_htlcs.insert(payment_hash.0));
3399                                 },
3400                                 _ => panic!("Unexpected event"),
3401                         }
3402                         match events[3] {
3403                                 Event::PaymentFailed { ref payment_hash, .. } => {
3404                                         assert_eq!(*payment_hash, second_payment_hash);
3405                                 },
3406                                 _ => panic!("Unexpected event"),
3407                         }
3408                         match events[4] {
3409                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3410                                         assert!(failed_htlcs.insert(payment_hash.0));
3411                                 },
3412                                 _ => panic!("Unexpected event"),
3413                         }
3414                         match events[5] {
3415                                 Event::PaymentFailed { ref payment_hash, .. } => {
3416                                         assert_eq!(*payment_hash, third_payment_hash);
3417                                 },
3418                                 _ => panic!("Unexpected event"),
3419                         }
3420                 },
3421                 _ => panic!("Unexpected event"),
3422         }
3423
3424         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3425         match events[0] {
3426                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3427                 _ => panic!("Unexpected event"),
3428         }
3429
3430         assert!(failed_htlcs.contains(&first_payment_hash.0));
3431         assert!(failed_htlcs.contains(&second_payment_hash.0));
3432         assert!(failed_htlcs.contains(&third_payment_hash.0));
3433 }
3434
3435 #[test]
3436 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3437         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3438         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3439         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3440         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3441 }
3442
3443 #[test]
3444 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3445         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3446         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3447         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3448         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3449 }
3450
3451 #[test]
3452 fn fail_backward_pending_htlc_upon_channel_failure() {
3453         let chanmon_cfgs = create_chanmon_cfgs(2);
3454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3456         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3457         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3458
3459         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3460         {
3461                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3462                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3463                         PaymentId(payment_hash.0)).unwrap();
3464                 check_added_monitors!(nodes[0], 1);
3465
3466                 let payment_event = {
3467                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3468                         assert_eq!(events.len(), 1);
3469                         SendEvent::from_event(events.remove(0))
3470                 };
3471                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3472                 assert_eq!(payment_event.msgs.len(), 1);
3473         }
3474
3475         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3476         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3477         {
3478                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3479                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3480                 check_added_monitors!(nodes[0], 0);
3481
3482                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3483         }
3484
3485         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3486         {
3487                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3488
3489                 let secp_ctx = Secp256k1::new();
3490                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3491                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3492                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3493                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3494                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3495                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3496
3497                 // Send a 0-msat update_add_htlc to fail the channel.
3498                 let update_add_htlc = msgs::UpdateAddHTLC {
3499                         channel_id: chan.2,
3500                         htlc_id: 0,
3501                         amount_msat: 0,
3502                         payment_hash,
3503                         cltv_expiry,
3504                         onion_routing_packet,
3505                         skimmed_fee_msat: None,
3506                 };
3507                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3508         }
3509         let events = nodes[0].node.get_and_clear_pending_events();
3510         assert_eq!(events.len(), 3);
3511         // Check that Alice fails backward the pending HTLC from the second payment.
3512         match events[0] {
3513                 Event::PaymentPathFailed { payment_hash, .. } => {
3514                         assert_eq!(payment_hash, failed_payment_hash);
3515                 },
3516                 _ => panic!("Unexpected event"),
3517         }
3518         match events[1] {
3519                 Event::PaymentFailed { payment_hash, .. } => {
3520                         assert_eq!(payment_hash, failed_payment_hash);
3521                 },
3522                 _ => panic!("Unexpected event"),
3523         }
3524         match events[2] {
3525                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3526                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3527                 },
3528                 _ => panic!("Unexpected event {:?}", events[1]),
3529         }
3530         check_closed_broadcast!(nodes[0], true);
3531         check_added_monitors!(nodes[0], 1);
3532 }
3533
3534 #[test]
3535 fn test_htlc_ignore_latest_remote_commitment() {
3536         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3537         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3538         let chanmon_cfgs = create_chanmon_cfgs(2);
3539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3541         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3542         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3543                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3544                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3545                 // connect_style.
3546                 return;
3547         }
3548         create_announced_chan_between_nodes(&nodes, 0, 1);
3549
3550         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3551         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3552         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3553         check_closed_broadcast!(nodes[0], true);
3554         check_added_monitors!(nodes[0], 1);
3555         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3556
3557         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3558         assert_eq!(node_txn.len(), 3);
3559         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3560
3561         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3562         connect_block(&nodes[1], &block);
3563         check_closed_broadcast!(nodes[1], true);
3564         check_added_monitors!(nodes[1], 1);
3565         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3566
3567         // Duplicate the connect_block call since this may happen due to other listeners
3568         // registering new transactions
3569         connect_block(&nodes[1], &block);
3570 }
3571
3572 #[test]
3573 fn test_force_close_fail_back() {
3574         // Check which HTLCs are failed-backwards on channel force-closure
3575         let chanmon_cfgs = create_chanmon_cfgs(3);
3576         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3577         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3578         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3579         create_announced_chan_between_nodes(&nodes, 0, 1);
3580         create_announced_chan_between_nodes(&nodes, 1, 2);
3581
3582         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3583
3584         let mut payment_event = {
3585                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3586                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3587                 check_added_monitors!(nodes[0], 1);
3588
3589                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3590                 assert_eq!(events.len(), 1);
3591                 SendEvent::from_event(events.remove(0))
3592         };
3593
3594         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3595         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3596
3597         expect_pending_htlcs_forwardable!(nodes[1]);
3598
3599         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3600         assert_eq!(events_2.len(), 1);
3601         payment_event = SendEvent::from_event(events_2.remove(0));
3602         assert_eq!(payment_event.msgs.len(), 1);
3603
3604         check_added_monitors!(nodes[1], 1);
3605         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3606         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3607         check_added_monitors!(nodes[2], 1);
3608         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3609
3610         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3611         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3612         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3613
3614         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3615         check_closed_broadcast!(nodes[2], true);
3616         check_added_monitors!(nodes[2], 1);
3617         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3618         let tx = {
3619                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3620                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3621                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3622                 // back to nodes[1] upon timeout otherwise.
3623                 assert_eq!(node_txn.len(), 1);
3624                 node_txn.remove(0)
3625         };
3626
3627         mine_transaction(&nodes[1], &tx);
3628
3629         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3630         check_closed_broadcast!(nodes[1], true);
3631         check_added_monitors!(nodes[1], 1);
3632         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3633
3634         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3635         {
3636                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3637                         .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);
3638         }
3639         mine_transaction(&nodes[2], &tx);
3640         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3641         assert_eq!(node_txn.len(), 1);
3642         assert_eq!(node_txn[0].input.len(), 1);
3643         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3644         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3645         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3646
3647         check_spends!(node_txn[0], tx);
3648 }
3649
3650 #[test]
3651 fn test_dup_events_on_peer_disconnect() {
3652         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3653         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3654         // as we used to generate the event immediately upon receipt of the payment preimage in the
3655         // update_fulfill_htlc message.
3656
3657         let chanmon_cfgs = create_chanmon_cfgs(2);
3658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3661         create_announced_chan_between_nodes(&nodes, 0, 1);
3662
3663         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3664
3665         nodes[1].node.claim_funds(payment_preimage);
3666         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3667         check_added_monitors!(nodes[1], 1);
3668         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3669         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3670         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3671
3672         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3673         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3674
3675         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3676         reconnect_args.pending_htlc_claims.0 = 1;
3677         reconnect_nodes(reconnect_args);
3678         expect_payment_path_successful!(nodes[0]);
3679 }
3680
3681 #[test]
3682 fn test_peer_disconnected_before_funding_broadcasted() {
3683         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3684         // before the funding transaction has been broadcasted.
3685         let chanmon_cfgs = create_chanmon_cfgs(2);
3686         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3687         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3688         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3689
3690         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3691         // broadcasted, even though it's created by `nodes[0]`.
3692         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();
3693         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3694         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3695         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3696         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3697
3698         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3699         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3700
3701         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3702
3703         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3704         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3705
3706         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3707         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3708         // broadcasted.
3709         {
3710                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3711         }
3712
3713         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3714         // disconnected before the funding transaction was broadcasted.
3715         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3716         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3717
3718         check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3719                 , [nodes[1].node.get_our_node_id()], 1000000);
3720         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3721                 , [nodes[0].node.get_our_node_id()], 1000000);
3722 }
3723
3724 #[test]
3725 fn test_simple_peer_disconnect() {
3726         // Test that we can reconnect when there are no lost messages
3727         let chanmon_cfgs = create_chanmon_cfgs(3);
3728         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3729         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3730         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3731         create_announced_chan_between_nodes(&nodes, 0, 1);
3732         create_announced_chan_between_nodes(&nodes, 1, 2);
3733
3734         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3735         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3736         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3737         reconnect_args.send_channel_ready = (true, true);
3738         reconnect_nodes(reconnect_args);
3739
3740         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3741         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3742         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3743         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3744
3745         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3746         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3747         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3748
3749         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3750         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3751         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3752         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3753
3754         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3755         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3756
3757         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3758         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3759
3760         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3761         reconnect_args.pending_cell_htlc_fails.0 = 1;
3762         reconnect_args.pending_cell_htlc_claims.0 = 1;
3763         reconnect_nodes(reconnect_args);
3764         {
3765                 let events = nodes[0].node.get_and_clear_pending_events();
3766                 assert_eq!(events.len(), 4);
3767                 match events[0] {
3768                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3769                                 assert_eq!(payment_preimage, payment_preimage_3);
3770                                 assert_eq!(payment_hash, payment_hash_3);
3771                         },
3772                         _ => panic!("Unexpected event"),
3773                 }
3774                 match events[1] {
3775                         Event::PaymentPathSuccessful { .. } => {},
3776                         _ => panic!("Unexpected event"),
3777                 }
3778                 match events[2] {
3779                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3780                                 assert_eq!(payment_hash, payment_hash_5);
3781                                 assert!(payment_failed_permanently);
3782                         },
3783                         _ => panic!("Unexpected event"),
3784                 }
3785                 match events[3] {
3786                         Event::PaymentFailed { payment_hash, .. } => {
3787                                 assert_eq!(payment_hash, payment_hash_5);
3788                         },
3789                         _ => panic!("Unexpected event"),
3790                 }
3791         }
3792         check_added_monitors(&nodes[0], 1);
3793
3794         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3795         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3796 }
3797
3798 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3799         // Test that we can reconnect when in-flight HTLC updates get dropped
3800         let chanmon_cfgs = create_chanmon_cfgs(2);
3801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3803         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3804
3805         let mut as_channel_ready = None;
3806         let channel_id = if messages_delivered == 0 {
3807                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3808                 as_channel_ready = Some(channel_ready);
3809                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3810                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3811                 // it before the channel_reestablish message.
3812                 chan_id
3813         } else {
3814                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3815         };
3816
3817         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3818
3819         let payment_event = {
3820                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3821                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3822                 check_added_monitors!(nodes[0], 1);
3823
3824                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3825                 assert_eq!(events.len(), 1);
3826                 SendEvent::from_event(events.remove(0))
3827         };
3828         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3829
3830         if messages_delivered < 2 {
3831                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3832         } else {
3833                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3834                 if messages_delivered >= 3 {
3835                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3836                         check_added_monitors!(nodes[1], 1);
3837                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3838
3839                         if messages_delivered >= 4 {
3840                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3841                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3842                                 check_added_monitors!(nodes[0], 1);
3843
3844                                 if messages_delivered >= 5 {
3845                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3846                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3847                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3848                                         check_added_monitors!(nodes[0], 1);
3849
3850                                         if messages_delivered >= 6 {
3851                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3852                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3853                                                 check_added_monitors!(nodes[1], 1);
3854                                         }
3855                                 }
3856                         }
3857                 }
3858         }
3859
3860         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3861         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3862         if messages_delivered < 3 {
3863                 if simulate_broken_lnd {
3864                         // lnd has a long-standing bug where they send a channel_ready prior to a
3865                         // channel_reestablish if you reconnect prior to channel_ready time.
3866                         //
3867                         // Here we simulate that behavior, delivering a channel_ready immediately on
3868                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3869                         // in `reconnect_nodes` but we currently don't fail based on that.
3870                         //
3871                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3872                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3873                 }
3874                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3875                 // received on either side, both sides will need to resend them.
3876                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3877                 reconnect_args.send_channel_ready = (true, true);
3878                 reconnect_args.pending_htlc_adds.1 = 1;
3879                 reconnect_nodes(reconnect_args);
3880         } else if messages_delivered == 3 {
3881                 // nodes[0] still wants its RAA + commitment_signed
3882                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3883                 reconnect_args.pending_htlc_adds.0 = -1;
3884                 reconnect_args.pending_raa.0 = true;
3885                 reconnect_nodes(reconnect_args);
3886         } else if messages_delivered == 4 {
3887                 // nodes[0] still wants its commitment_signed
3888                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3889                 reconnect_args.pending_htlc_adds.0 = -1;
3890                 reconnect_nodes(reconnect_args);
3891         } else if messages_delivered == 5 {
3892                 // nodes[1] still wants its final RAA
3893                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3894                 reconnect_args.pending_raa.1 = true;
3895                 reconnect_nodes(reconnect_args);
3896         } else if messages_delivered == 6 {
3897                 // Everything was delivered...
3898                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3899         }
3900
3901         let events_1 = nodes[1].node.get_and_clear_pending_events();
3902         if messages_delivered == 0 {
3903                 assert_eq!(events_1.len(), 2);
3904                 match events_1[0] {
3905                         Event::ChannelReady { .. } => { },
3906                         _ => panic!("Unexpected event"),
3907                 };
3908                 match events_1[1] {
3909                         Event::PendingHTLCsForwardable { .. } => { },
3910                         _ => panic!("Unexpected event"),
3911                 };
3912         } else {
3913                 assert_eq!(events_1.len(), 1);
3914                 match events_1[0] {
3915                         Event::PendingHTLCsForwardable { .. } => { },
3916                         _ => panic!("Unexpected event"),
3917                 };
3918         }
3919
3920         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3921         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3922         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3923
3924         nodes[1].node.process_pending_htlc_forwards();
3925
3926         let events_2 = nodes[1].node.get_and_clear_pending_events();
3927         assert_eq!(events_2.len(), 1);
3928         match events_2[0] {
3929                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3930                         assert_eq!(payment_hash_1, *payment_hash);
3931                         assert_eq!(amount_msat, 1_000_000);
3932                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3933                         assert_eq!(via_channel_id, Some(channel_id));
3934                         match &purpose {
3935                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3936                                         assert!(payment_preimage.is_none());
3937                                         assert_eq!(payment_secret_1, *payment_secret);
3938                                 },
3939                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3940                         }
3941                 },
3942                 _ => panic!("Unexpected event"),
3943         }
3944
3945         nodes[1].node.claim_funds(payment_preimage_1);
3946         check_added_monitors!(nodes[1], 1);
3947         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3948
3949         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3950         assert_eq!(events_3.len(), 1);
3951         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3952                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3953                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3954                         assert!(updates.update_add_htlcs.is_empty());
3955                         assert!(updates.update_fail_htlcs.is_empty());
3956                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3957                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3958                         assert!(updates.update_fee.is_none());
3959                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3960                 },
3961                 _ => panic!("Unexpected event"),
3962         };
3963
3964         if messages_delivered >= 1 {
3965                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3966
3967                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3968                 assert_eq!(events_4.len(), 1);
3969                 match events_4[0] {
3970                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3971                                 assert_eq!(payment_preimage_1, *payment_preimage);
3972                                 assert_eq!(payment_hash_1, *payment_hash);
3973                         },
3974                         _ => panic!("Unexpected event"),
3975                 }
3976
3977                 if messages_delivered >= 2 {
3978                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3979                         check_added_monitors!(nodes[0], 1);
3980                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3981
3982                         if messages_delivered >= 3 {
3983                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3984                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3985                                 check_added_monitors!(nodes[1], 1);
3986
3987                                 if messages_delivered >= 4 {
3988                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3989                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3990                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3991                                         check_added_monitors!(nodes[1], 1);
3992
3993                                         if messages_delivered >= 5 {
3994                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3995                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3996                                                 check_added_monitors!(nodes[0], 1);
3997                                         }
3998                                 }
3999                         }
4000                 }
4001         }
4002
4003         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4004         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4005         if messages_delivered < 2 {
4006                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4007                 reconnect_args.pending_htlc_claims.0 = 1;
4008                 reconnect_nodes(reconnect_args);
4009                 if messages_delivered < 1 {
4010                         expect_payment_sent!(nodes[0], payment_preimage_1);
4011                 } else {
4012                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4013                 }
4014         } else if messages_delivered == 2 {
4015                 // nodes[0] still wants its RAA + commitment_signed
4016                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4017                 reconnect_args.pending_htlc_adds.1 = -1;
4018                 reconnect_args.pending_raa.1 = true;
4019                 reconnect_nodes(reconnect_args);
4020         } else if messages_delivered == 3 {
4021                 // nodes[0] still wants its commitment_signed
4022                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4023                 reconnect_args.pending_htlc_adds.1 = -1;
4024                 reconnect_nodes(reconnect_args);
4025         } else if messages_delivered == 4 {
4026                 // nodes[1] still wants its final RAA
4027                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4028                 reconnect_args.pending_raa.0 = true;
4029                 reconnect_nodes(reconnect_args);
4030         } else if messages_delivered == 5 {
4031                 // Everything was delivered...
4032                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4033         }
4034
4035         if messages_delivered == 1 || messages_delivered == 2 {
4036                 expect_payment_path_successful!(nodes[0]);
4037         }
4038         if messages_delivered <= 5 {
4039                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4040                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4041         }
4042         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4043
4044         if messages_delivered > 2 {
4045                 expect_payment_path_successful!(nodes[0]);
4046         }
4047
4048         // Channel should still work fine...
4049         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4050         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4051         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4052 }
4053
4054 #[test]
4055 fn test_drop_messages_peer_disconnect_a() {
4056         do_test_drop_messages_peer_disconnect(0, true);
4057         do_test_drop_messages_peer_disconnect(0, false);
4058         do_test_drop_messages_peer_disconnect(1, false);
4059         do_test_drop_messages_peer_disconnect(2, false);
4060 }
4061
4062 #[test]
4063 fn test_drop_messages_peer_disconnect_b() {
4064         do_test_drop_messages_peer_disconnect(3, false);
4065         do_test_drop_messages_peer_disconnect(4, false);
4066         do_test_drop_messages_peer_disconnect(5, false);
4067         do_test_drop_messages_peer_disconnect(6, false);
4068 }
4069
4070 #[test]
4071 fn test_channel_ready_without_best_block_updated() {
4072         // Previously, if we were offline when a funding transaction was locked in, and then we came
4073         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4074         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4075         // channel_ready immediately instead.
4076         let chanmon_cfgs = create_chanmon_cfgs(2);
4077         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4078         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4079         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4080         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4081
4082         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4083
4084         let conf_height = nodes[0].best_block_info().1 + 1;
4085         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4086         let block_txn = [funding_tx];
4087         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4088         let conf_block_header = nodes[0].get_block_header(conf_height);
4089         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4090
4091         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4092         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4093         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4094 }
4095
4096 #[test]
4097 fn test_drop_messages_peer_disconnect_dual_htlc() {
4098         // Test that we can handle reconnecting when both sides of a channel have pending
4099         // commitment_updates when we disconnect.
4100         let chanmon_cfgs = create_chanmon_cfgs(2);
4101         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4102         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4103         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4104         create_announced_chan_between_nodes(&nodes, 0, 1);
4105
4106         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4107
4108         // Now try to send a second payment which will fail to send
4109         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4110         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4111                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4112         check_added_monitors!(nodes[0], 1);
4113
4114         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4115         assert_eq!(events_1.len(), 1);
4116         match events_1[0] {
4117                 MessageSendEvent::UpdateHTLCs { .. } => {},
4118                 _ => panic!("Unexpected event"),
4119         }
4120
4121         nodes[1].node.claim_funds(payment_preimage_1);
4122         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4123         check_added_monitors!(nodes[1], 1);
4124
4125         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4126         assert_eq!(events_2.len(), 1);
4127         match events_2[0] {
4128                 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 } } => {
4129                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4130                         assert!(update_add_htlcs.is_empty());
4131                         assert_eq!(update_fulfill_htlcs.len(), 1);
4132                         assert!(update_fail_htlcs.is_empty());
4133                         assert!(update_fail_malformed_htlcs.is_empty());
4134                         assert!(update_fee.is_none());
4135
4136                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4137                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4138                         assert_eq!(events_3.len(), 1);
4139                         match events_3[0] {
4140                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4141                                         assert_eq!(*payment_preimage, payment_preimage_1);
4142                                         assert_eq!(*payment_hash, payment_hash_1);
4143                                 },
4144                                 _ => panic!("Unexpected event"),
4145                         }
4146
4147                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4148                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4149                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4150                         check_added_monitors!(nodes[0], 1);
4151                 },
4152                 _ => panic!("Unexpected event"),
4153         }
4154
4155         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4156         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4157
4158         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4159                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4160         }, true).unwrap();
4161         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4162         assert_eq!(reestablish_1.len(), 1);
4163         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4164                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4165         }, false).unwrap();
4166         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4167         assert_eq!(reestablish_2.len(), 1);
4168
4169         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4170         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4171         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4172         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4173
4174         assert!(as_resp.0.is_none());
4175         assert!(bs_resp.0.is_none());
4176
4177         assert!(bs_resp.1.is_none());
4178         assert!(bs_resp.2.is_none());
4179
4180         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4181
4182         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4183         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4184         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4185         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4186         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4187         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4188         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4189         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4190         // No commitment_signed so get_event_msg's assert(len == 1) passes
4191         check_added_monitors!(nodes[1], 1);
4192
4193         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4194         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4195         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4196         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4197         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4198         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4199         assert!(bs_second_commitment_signed.update_fee.is_none());
4200         check_added_monitors!(nodes[1], 1);
4201
4202         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4203         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4204         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4205         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4206         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4207         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4208         assert!(as_commitment_signed.update_fee.is_none());
4209         check_added_monitors!(nodes[0], 1);
4210
4211         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4212         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4213         // No commitment_signed so get_event_msg's assert(len == 1) passes
4214         check_added_monitors!(nodes[0], 1);
4215
4216         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4217         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4218         // No commitment_signed so get_event_msg's assert(len == 1) passes
4219         check_added_monitors!(nodes[1], 1);
4220
4221         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4222         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4223         check_added_monitors!(nodes[1], 1);
4224
4225         expect_pending_htlcs_forwardable!(nodes[1]);
4226
4227         let events_5 = nodes[1].node.get_and_clear_pending_events();
4228         assert_eq!(events_5.len(), 1);
4229         match events_5[0] {
4230                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4231                         assert_eq!(payment_hash_2, *payment_hash);
4232                         match &purpose {
4233                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4234                                         assert!(payment_preimage.is_none());
4235                                         assert_eq!(payment_secret_2, *payment_secret);
4236                                 },
4237                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4238                         }
4239                 },
4240                 _ => panic!("Unexpected event"),
4241         }
4242
4243         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4244         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4245         check_added_monitors!(nodes[0], 1);
4246
4247         expect_payment_path_successful!(nodes[0]);
4248         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4249 }
4250
4251 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4252         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4253         // to avoid our counterparty failing the channel.
4254         let chanmon_cfgs = create_chanmon_cfgs(2);
4255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4257         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4258
4259         create_announced_chan_between_nodes(&nodes, 0, 1);
4260
4261         let our_payment_hash = if send_partial_mpp {
4262                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4263                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4264                 // indicates there are more HTLCs coming.
4265                 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.
4266                 let payment_id = PaymentId([42; 32]);
4267                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4268                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4269                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4270                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4271                         &None, session_privs[0]).unwrap();
4272                 check_added_monitors!(nodes[0], 1);
4273                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4274                 assert_eq!(events.len(), 1);
4275                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4276                 // hop should *not* yet generate any PaymentClaimable event(s).
4277                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4278                 our_payment_hash
4279         } else {
4280                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4281         };
4282
4283         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4284         connect_block(&nodes[0], &block);
4285         connect_block(&nodes[1], &block);
4286         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4287         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4288                 block.header.prev_blockhash = block.block_hash();
4289                 connect_block(&nodes[0], &block);
4290                 connect_block(&nodes[1], &block);
4291         }
4292
4293         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4294
4295         check_added_monitors!(nodes[1], 1);
4296         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4297         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4298         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4299         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4300         assert!(htlc_timeout_updates.update_fee.is_none());
4301
4302         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4303         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4304         // 100_000 msat as u64, followed by the height at which we failed back above
4305         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4306         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4307         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4308 }
4309
4310 #[test]
4311 fn test_htlc_timeout() {
4312         do_test_htlc_timeout(true);
4313         do_test_htlc_timeout(false);
4314 }
4315
4316 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4317         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4318         let chanmon_cfgs = create_chanmon_cfgs(3);
4319         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4320         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4321         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4322         create_announced_chan_between_nodes(&nodes, 0, 1);
4323         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4324
4325         // Make sure all nodes are at the same starting height
4326         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4327         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4328         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4329
4330         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4331         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4332         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4333                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4334         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4335         check_added_monitors!(nodes[1], 1);
4336
4337         // Now attempt to route a second payment, which should be placed in the holding cell
4338         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4339         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4340         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4341                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4342         if forwarded_htlc {
4343                 check_added_monitors!(nodes[0], 1);
4344                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4345                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4346                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4347                 expect_pending_htlcs_forwardable!(nodes[1]);
4348         }
4349         check_added_monitors!(nodes[1], 0);
4350
4351         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4352         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4353         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4354         connect_blocks(&nodes[1], 1);
4355
4356         if forwarded_htlc {
4357                 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 }]);
4358                 check_added_monitors!(nodes[1], 1);
4359                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4360                 assert_eq!(fail_commit.len(), 1);
4361                 match fail_commit[0] {
4362                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4363                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4364                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4365                         },
4366                         _ => unreachable!(),
4367                 }
4368                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4369         } else {
4370                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4371         }
4372 }
4373
4374 #[test]
4375 fn test_holding_cell_htlc_add_timeouts() {
4376         do_test_holding_cell_htlc_add_timeouts(false);
4377         do_test_holding_cell_htlc_add_timeouts(true);
4378 }
4379
4380 macro_rules! check_spendable_outputs {
4381         ($node: expr, $keysinterface: expr) => {
4382                 {
4383                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4384                         let mut txn = Vec::new();
4385                         let mut all_outputs = Vec::new();
4386                         let secp_ctx = Secp256k1::new();
4387                         for event in events.drain(..) {
4388                                 match event {
4389                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4390                                                 for outp in outputs.drain(..) {
4391                                                         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());
4392                                                         all_outputs.push(outp);
4393                                                 }
4394                                         },
4395                                         _ => panic!("Unexpected event"),
4396                                 };
4397                         }
4398                         if all_outputs.len() > 1 {
4399                                 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) {
4400                                         txn.push(tx);
4401                                 }
4402                         }
4403                         txn
4404                 }
4405         }
4406 }
4407
4408 #[test]
4409 fn test_claim_sizeable_push_msat() {
4410         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4411         let chanmon_cfgs = create_chanmon_cfgs(2);
4412         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4413         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4414         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4415
4416         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4417         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4418         check_closed_broadcast!(nodes[1], true);
4419         check_added_monitors!(nodes[1], 1);
4420         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4421         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4422         assert_eq!(node_txn.len(), 1);
4423         check_spends!(node_txn[0], chan.3);
4424         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
4425
4426         mine_transaction(&nodes[1], &node_txn[0]);
4427         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4428
4429         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4430         assert_eq!(spend_txn.len(), 1);
4431         assert_eq!(spend_txn[0].input.len(), 1);
4432         check_spends!(spend_txn[0], node_txn[0]);
4433         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4434 }
4435
4436 #[test]
4437 fn test_claim_on_remote_sizeable_push_msat() {
4438         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4439         // to_remote output is encumbered by a P2WPKH
4440         let chanmon_cfgs = create_chanmon_cfgs(2);
4441         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4442         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4443         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4444
4445         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4446         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4447         check_closed_broadcast!(nodes[0], true);
4448         check_added_monitors!(nodes[0], 1);
4449         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4450
4451         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4452         assert_eq!(node_txn.len(), 1);
4453         check_spends!(node_txn[0], chan.3);
4454         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
4455
4456         mine_transaction(&nodes[1], &node_txn[0]);
4457         check_closed_broadcast!(nodes[1], true);
4458         check_added_monitors!(nodes[1], 1);
4459         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4460         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4461
4462         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4463         assert_eq!(spend_txn.len(), 1);
4464         check_spends!(spend_txn[0], node_txn[0]);
4465 }
4466
4467 #[test]
4468 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4469         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4470         // to_remote output is encumbered by a P2WPKH
4471
4472         let chanmon_cfgs = create_chanmon_cfgs(2);
4473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4476
4477         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4478         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4479         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4480         assert_eq!(revoked_local_txn[0].input.len(), 1);
4481         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4482
4483         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4484         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4485         check_closed_broadcast!(nodes[1], true);
4486         check_added_monitors!(nodes[1], 1);
4487         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4488
4489         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4490         mine_transaction(&nodes[1], &node_txn[0]);
4491         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4492
4493         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4494         assert_eq!(spend_txn.len(), 3);
4495         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4496         check_spends!(spend_txn[1], node_txn[0]);
4497         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4498 }
4499
4500 #[test]
4501 fn test_static_spendable_outputs_preimage_tx() {
4502         let chanmon_cfgs = create_chanmon_cfgs(2);
4503         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4504         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4505         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4506
4507         // Create some initial channels
4508         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4509
4510         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4511
4512         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4513         assert_eq!(commitment_tx[0].input.len(), 1);
4514         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4515
4516         // Settle A's commitment tx on B's chain
4517         nodes[1].node.claim_funds(payment_preimage);
4518         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4519         check_added_monitors!(nodes[1], 1);
4520         mine_transaction(&nodes[1], &commitment_tx[0]);
4521         check_added_monitors!(nodes[1], 1);
4522         let events = nodes[1].node.get_and_clear_pending_msg_events();
4523         match events[0] {
4524                 MessageSendEvent::UpdateHTLCs { .. } => {},
4525                 _ => panic!("Unexpected event"),
4526         }
4527         match events[1] {
4528                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4529                 _ => panic!("Unexepected event"),
4530         }
4531
4532         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4533         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4534         assert_eq!(node_txn.len(), 1);
4535         check_spends!(node_txn[0], commitment_tx[0]);
4536         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4537
4538         mine_transaction(&nodes[1], &node_txn[0]);
4539         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4540         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4541
4542         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4543         assert_eq!(spend_txn.len(), 1);
4544         check_spends!(spend_txn[0], node_txn[0]);
4545 }
4546
4547 #[test]
4548 fn test_static_spendable_outputs_timeout_tx() {
4549         let chanmon_cfgs = create_chanmon_cfgs(2);
4550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4552         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4553
4554         // Create some initial channels
4555         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4556
4557         // Rebalance the network a bit by relaying one payment through all the channels ...
4558         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4559
4560         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4561
4562         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4563         assert_eq!(commitment_tx[0].input.len(), 1);
4564         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4565
4566         // Settle A's commitment tx on B' chain
4567         mine_transaction(&nodes[1], &commitment_tx[0]);
4568         check_added_monitors!(nodes[1], 1);
4569         let events = nodes[1].node.get_and_clear_pending_msg_events();
4570         match events[0] {
4571                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4572                 _ => panic!("Unexpected event"),
4573         }
4574         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4575
4576         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4577         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4578         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4579         check_spends!(node_txn[0],  commitment_tx[0].clone());
4580         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4581
4582         mine_transaction(&nodes[1], &node_txn[0]);
4583         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4584         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4585         expect_payment_failed!(nodes[1], our_payment_hash, false);
4586
4587         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4588         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4589         check_spends!(spend_txn[0], commitment_tx[0]);
4590         check_spends!(spend_txn[1], node_txn[0]);
4591         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4592 }
4593
4594 #[test]
4595 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4596         let chanmon_cfgs = create_chanmon_cfgs(2);
4597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4599         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4600
4601         // Create some initial channels
4602         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4603
4604         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4605         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4606         assert_eq!(revoked_local_txn[0].input.len(), 1);
4607         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4608
4609         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4610
4611         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4612         check_closed_broadcast!(nodes[1], true);
4613         check_added_monitors!(nodes[1], 1);
4614         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4615
4616         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4617         assert_eq!(node_txn.len(), 1);
4618         assert_eq!(node_txn[0].input.len(), 2);
4619         check_spends!(node_txn[0], revoked_local_txn[0]);
4620
4621         mine_transaction(&nodes[1], &node_txn[0]);
4622         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4623
4624         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4625         assert_eq!(spend_txn.len(), 1);
4626         check_spends!(spend_txn[0], node_txn[0]);
4627 }
4628
4629 #[test]
4630 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4631         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4632         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4633         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4634         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4635         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4636
4637         // Create some initial channels
4638         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4639
4640         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4641         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4642         assert_eq!(revoked_local_txn[0].input.len(), 1);
4643         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4644
4645         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4646
4647         // A will generate HTLC-Timeout from revoked commitment tx
4648         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4649         check_closed_broadcast!(nodes[0], true);
4650         check_added_monitors!(nodes[0], 1);
4651         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4652         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4653
4654         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4655         assert_eq!(revoked_htlc_txn.len(), 1);
4656         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4657         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4658         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4659         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4660
4661         // B will generate justice tx from A's revoked commitment/HTLC tx
4662         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4663         check_closed_broadcast!(nodes[1], true);
4664         check_added_monitors!(nodes[1], 1);
4665         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4666
4667         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4668         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4669         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4670         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4671         // transactions next...
4672         assert_eq!(node_txn[0].input.len(), 3);
4673         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4674
4675         assert_eq!(node_txn[1].input.len(), 2);
4676         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4677         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4678                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4679         } else {
4680                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4681                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4682         }
4683
4684         mine_transaction(&nodes[1], &node_txn[1]);
4685         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4686
4687         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4688         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4689         assert_eq!(spend_txn.len(), 1);
4690         assert_eq!(spend_txn[0].input.len(), 1);
4691         check_spends!(spend_txn[0], node_txn[1]);
4692 }
4693
4694 #[test]
4695 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4696         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4697         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4698         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4699         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4700         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4701
4702         // Create some initial channels
4703         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4704
4705         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4706         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4707         assert_eq!(revoked_local_txn[0].input.len(), 1);
4708         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4709
4710         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4711         assert_eq!(revoked_local_txn[0].output.len(), 2);
4712
4713         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4714
4715         // B will generate HTLC-Success from revoked commitment tx
4716         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4717         check_closed_broadcast!(nodes[1], true);
4718         check_added_monitors!(nodes[1], 1);
4719         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4720         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4721
4722         assert_eq!(revoked_htlc_txn.len(), 1);
4723         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4724         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4725         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4726
4727         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4728         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4729         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4730
4731         // A will generate justice tx from B's revoked commitment/HTLC tx
4732         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4733         check_closed_broadcast!(nodes[0], true);
4734         check_added_monitors!(nodes[0], 1);
4735         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4736
4737         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4738         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4739
4740         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4741         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4742         // transactions next...
4743         assert_eq!(node_txn[0].input.len(), 2);
4744         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4745         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4746                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4747         } else {
4748                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4749                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4750         }
4751
4752         assert_eq!(node_txn[1].input.len(), 1);
4753         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4754
4755         mine_transaction(&nodes[0], &node_txn[1]);
4756         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4757
4758         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4759         // didn't try to generate any new transactions.
4760
4761         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4762         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4763         assert_eq!(spend_txn.len(), 3);
4764         assert_eq!(spend_txn[0].input.len(), 1);
4765         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4766         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4767         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4768         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4769 }
4770
4771 #[test]
4772 fn test_onchain_to_onchain_claim() {
4773         // Test that in case of channel closure, we detect the state of output and claim HTLC
4774         // on downstream peer's remote commitment tx.
4775         // First, have C claim an HTLC against its own latest commitment transaction.
4776         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4777         // channel.
4778         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4779         // gets broadcast.
4780
4781         let chanmon_cfgs = create_chanmon_cfgs(3);
4782         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4783         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4784         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4785
4786         // Create some initial channels
4787         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4788         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4789
4790         // Ensure all nodes are at the same height
4791         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4792         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4793         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4794         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4795
4796         // Rebalance the network a bit by relaying one payment through all the channels ...
4797         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4798         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4799
4800         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4801         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4802         check_spends!(commitment_tx[0], chan_2.3);
4803         nodes[2].node.claim_funds(payment_preimage);
4804         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4805         check_added_monitors!(nodes[2], 1);
4806         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4807         assert!(updates.update_add_htlcs.is_empty());
4808         assert!(updates.update_fail_htlcs.is_empty());
4809         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4810         assert!(updates.update_fail_malformed_htlcs.is_empty());
4811
4812         mine_transaction(&nodes[2], &commitment_tx[0]);
4813         check_closed_broadcast!(nodes[2], true);
4814         check_added_monitors!(nodes[2], 1);
4815         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4816
4817         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4818         assert_eq!(c_txn.len(), 1);
4819         check_spends!(c_txn[0], commitment_tx[0]);
4820         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4821         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4822         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4823
4824         // 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
4825         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4826         check_added_monitors!(nodes[1], 1);
4827         let events = nodes[1].node.get_and_clear_pending_events();
4828         assert_eq!(events.len(), 2);
4829         match events[0] {
4830                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4831                 _ => panic!("Unexpected event"),
4832         }
4833         match events[1] {
4834                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4835                         assert_eq!(fee_earned_msat, Some(1000));
4836                         assert_eq!(prev_channel_id, Some(chan_1.2));
4837                         assert_eq!(claim_from_onchain_tx, true);
4838                         assert_eq!(next_channel_id, Some(chan_2.2));
4839                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4840                 },
4841                 _ => panic!("Unexpected event"),
4842         }
4843         check_added_monitors!(nodes[1], 1);
4844         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4845         assert_eq!(msg_events.len(), 3);
4846         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4847         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4848
4849         match nodes_2_event {
4850                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4851                 _ => panic!("Unexpected event"),
4852         }
4853
4854         match nodes_0_event {
4855                 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, .. } } => {
4856                         assert!(update_add_htlcs.is_empty());
4857                         assert!(update_fail_htlcs.is_empty());
4858                         assert_eq!(update_fulfill_htlcs.len(), 1);
4859                         assert!(update_fail_malformed_htlcs.is_empty());
4860                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4861                 },
4862                 _ => panic!("Unexpected event"),
4863         };
4864
4865         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4866         match msg_events[0] {
4867                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4868                 _ => panic!("Unexpected event"),
4869         }
4870
4871         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4872         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4873         mine_transaction(&nodes[1], &commitment_tx[0]);
4874         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4875         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4876         // ChannelMonitor: HTLC-Success tx
4877         assert_eq!(b_txn.len(), 1);
4878         check_spends!(b_txn[0], commitment_tx[0]);
4879         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4880         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4881         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4882
4883         check_closed_broadcast!(nodes[1], true);
4884         check_added_monitors!(nodes[1], 1);
4885 }
4886
4887 #[test]
4888 fn test_duplicate_payment_hash_one_failure_one_success() {
4889         // Topology : A --> B --> C --> D
4890         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4891         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4892         // we forward one of the payments onwards to D.
4893         let chanmon_cfgs = create_chanmon_cfgs(4);
4894         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4895         // When this test was written, the default base fee floated based on the HTLC count.
4896         // It is now fixed, so we simply set the fee to the expected value here.
4897         let mut config = test_default_channel_config();
4898         config.channel_config.forwarding_fee_base_msat = 196;
4899         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4900                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4901         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4902
4903         create_announced_chan_between_nodes(&nodes, 0, 1);
4904         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4905         create_announced_chan_between_nodes(&nodes, 2, 3);
4906
4907         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4908         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4909         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4910         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4911         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4912
4913         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4914
4915         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4916         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4917         // script push size limit so that the below script length checks match
4918         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4919         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4920                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4921         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4922         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4923
4924         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4925         assert_eq!(commitment_txn[0].input.len(), 1);
4926         check_spends!(commitment_txn[0], chan_2.3);
4927
4928         mine_transaction(&nodes[1], &commitment_txn[0]);
4929         check_closed_broadcast!(nodes[1], true);
4930         check_added_monitors!(nodes[1], 1);
4931         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4932         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4933
4934         let htlc_timeout_tx;
4935         { // Extract one of the two HTLC-Timeout transaction
4936                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4937                 // ChannelMonitor: timeout tx * 2-or-3
4938                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4939
4940                 check_spends!(node_txn[0], commitment_txn[0]);
4941                 assert_eq!(node_txn[0].input.len(), 1);
4942                 assert_eq!(node_txn[0].output.len(), 1);
4943
4944                 if node_txn.len() > 2 {
4945                         check_spends!(node_txn[1], commitment_txn[0]);
4946                         assert_eq!(node_txn[1].input.len(), 1);
4947                         assert_eq!(node_txn[1].output.len(), 1);
4948                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4949
4950                         check_spends!(node_txn[2], commitment_txn[0]);
4951                         assert_eq!(node_txn[2].input.len(), 1);
4952                         assert_eq!(node_txn[2].output.len(), 1);
4953                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4954                 } else {
4955                         check_spends!(node_txn[1], commitment_txn[0]);
4956                         assert_eq!(node_txn[1].input.len(), 1);
4957                         assert_eq!(node_txn[1].output.len(), 1);
4958                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4959                 }
4960
4961                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4962                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4963                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4964                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4965                 if node_txn.len() > 2 {
4966                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4967                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4968                 } else {
4969                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4970                 }
4971         }
4972
4973         nodes[2].node.claim_funds(our_payment_preimage);
4974         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4975
4976         mine_transaction(&nodes[2], &commitment_txn[0]);
4977         check_added_monitors!(nodes[2], 2);
4978         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4979         let events = nodes[2].node.get_and_clear_pending_msg_events();
4980         match events[0] {
4981                 MessageSendEvent::UpdateHTLCs { .. } => {},
4982                 _ => panic!("Unexpected event"),
4983         }
4984         match events[1] {
4985                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4986                 _ => panic!("Unexepected event"),
4987         }
4988         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4989         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4990         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4991         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4992         assert_eq!(htlc_success_txn[0].input.len(), 1);
4993         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4994         assert_eq!(htlc_success_txn[1].input.len(), 1);
4995         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4996         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4997         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4998
4999         mine_transaction(&nodes[1], &htlc_timeout_tx);
5000         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5001         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 }]);
5002         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5003         assert!(htlc_updates.update_add_htlcs.is_empty());
5004         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5005         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5006         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5007         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5008         check_added_monitors!(nodes[1], 1);
5009
5010         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5011         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5012         {
5013                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5014         }
5015         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5016
5017         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5018         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5019         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5020         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5021         assert!(updates.update_add_htlcs.is_empty());
5022         assert!(updates.update_fail_htlcs.is_empty());
5023         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5024         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5025         assert!(updates.update_fail_malformed_htlcs.is_empty());
5026         check_added_monitors!(nodes[1], 1);
5027
5028         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5029         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5030         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5031 }
5032
5033 #[test]
5034 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5035         let chanmon_cfgs = create_chanmon_cfgs(2);
5036         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5037         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5038         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5039
5040         // Create some initial channels
5041         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5042
5043         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5044         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5045         assert_eq!(local_txn.len(), 1);
5046         assert_eq!(local_txn[0].input.len(), 1);
5047         check_spends!(local_txn[0], chan_1.3);
5048
5049         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5050         nodes[1].node.claim_funds(payment_preimage);
5051         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5052         check_added_monitors!(nodes[1], 1);
5053
5054         mine_transaction(&nodes[1], &local_txn[0]);
5055         check_added_monitors!(nodes[1], 1);
5056         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5057         let events = nodes[1].node.get_and_clear_pending_msg_events();
5058         match events[0] {
5059                 MessageSendEvent::UpdateHTLCs { .. } => {},
5060                 _ => panic!("Unexpected event"),
5061         }
5062         match events[1] {
5063                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5064                 _ => panic!("Unexepected event"),
5065         }
5066         let node_tx = {
5067                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5068                 assert_eq!(node_txn.len(), 1);
5069                 assert_eq!(node_txn[0].input.len(), 1);
5070                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5071                 check_spends!(node_txn[0], local_txn[0]);
5072                 node_txn[0].clone()
5073         };
5074
5075         mine_transaction(&nodes[1], &node_tx);
5076         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5077
5078         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5079         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5080         assert_eq!(spend_txn.len(), 1);
5081         assert_eq!(spend_txn[0].input.len(), 1);
5082         check_spends!(spend_txn[0], node_tx);
5083         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5084 }
5085
5086 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5087         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5088         // unrevoked commitment transaction.
5089         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5090         // a remote RAA before they could be failed backwards (and combinations thereof).
5091         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5092         // use the same payment hashes.
5093         // Thus, we use a six-node network:
5094         //
5095         // A \         / E
5096         //    - C - D -
5097         // B /         \ F
5098         // And test where C fails back to A/B when D announces its latest commitment transaction
5099         let chanmon_cfgs = create_chanmon_cfgs(6);
5100         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5101         // When this test was written, the default base fee floated based on the HTLC count.
5102         // It is now fixed, so we simply set the fee to the expected value here.
5103         let mut config = test_default_channel_config();
5104         config.channel_config.forwarding_fee_base_msat = 196;
5105         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5106                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5107         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5108
5109         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5110         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5111         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5112         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5113         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5114
5115         // Rebalance and check output sanity...
5116         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5117         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5118         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5119
5120         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5121                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5122         // 0th HTLC:
5123         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
5124         // 1st HTLC:
5125         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
5126         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5127         // 2nd HTLC:
5128         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
5129         // 3rd HTLC:
5130         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
5131         // 4th HTLC:
5132         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5133         // 5th HTLC:
5134         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5135         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5136         // 6th HTLC:
5137         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());
5138         // 7th HTLC:
5139         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());
5140
5141         // 8th HTLC:
5142         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5143         // 9th HTLC:
5144         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5145         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
5146
5147         // 10th HTLC:
5148         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
5149         // 11th HTLC:
5150         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5151         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());
5152
5153         // Double-check that six of the new HTLC were added
5154         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5155         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5156         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5157         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5158
5159         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5160         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5161         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5162         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5163         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5164         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5165         check_added_monitors!(nodes[4], 0);
5166
5167         let failed_destinations = vec![
5168                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5169                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5170                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5171                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5172         ];
5173         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5174         check_added_monitors!(nodes[4], 1);
5175
5176         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5177         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5178         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5179         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5180         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5181         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5182
5183         // Fail 3rd below-dust and 7th above-dust HTLCs
5184         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5185         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5186         check_added_monitors!(nodes[5], 0);
5187
5188         let failed_destinations_2 = vec![
5189                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5190                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5191         ];
5192         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5193         check_added_monitors!(nodes[5], 1);
5194
5195         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5196         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5197         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5198         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5199
5200         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5201
5202         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5203         let failed_destinations_3 = vec![
5204                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5205                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5206                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5207                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5208                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5209                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5210         ];
5211         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5212         check_added_monitors!(nodes[3], 1);
5213         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5214         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5215         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5216         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5217         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5218         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5219         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5220         if deliver_last_raa {
5221                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5222         } else {
5223                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5224         }
5225
5226         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5227         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5228         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5229         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5230         //
5231         // We now broadcast the latest commitment transaction, which *should* result in failures for
5232         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5233         // the non-broadcast above-dust HTLCs.
5234         //
5235         // Alternatively, we may broadcast the previous commitment transaction, which should only
5236         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5237         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5238
5239         if announce_latest {
5240                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5241         } else {
5242                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5243         }
5244         let events = nodes[2].node.get_and_clear_pending_events();
5245         let close_event = if deliver_last_raa {
5246                 assert_eq!(events.len(), 2 + 6);
5247                 events.last().clone().unwrap()
5248         } else {
5249                 assert_eq!(events.len(), 1);
5250                 events.last().clone().unwrap()
5251         };
5252         match close_event {
5253                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5254                 _ => panic!("Unexpected event"),
5255         }
5256
5257         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5258         check_closed_broadcast!(nodes[2], true);
5259         if deliver_last_raa {
5260                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5261
5262                 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();
5263                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5264         } else {
5265                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5266                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5267                 } else {
5268                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5269                 };
5270
5271                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5272         }
5273         check_added_monitors!(nodes[2], 3);
5274
5275         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5276         assert_eq!(cs_msgs.len(), 2);
5277         let mut a_done = false;
5278         for msg in cs_msgs {
5279                 match msg {
5280                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5281                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5282                                 // should be failed-backwards here.
5283                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5284                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5285                                         for htlc in &updates.update_fail_htlcs {
5286                                                 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 });
5287                                         }
5288                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5289                                         assert!(!a_done);
5290                                         a_done = true;
5291                                         &nodes[0]
5292                                 } else {
5293                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5294                                         for htlc in &updates.update_fail_htlcs {
5295                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5296                                         }
5297                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5298                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5299                                         &nodes[1]
5300                                 };
5301                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5302                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5303                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5304                                 if announce_latest {
5305                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5306                                         if *node_id == nodes[0].node.get_our_node_id() {
5307                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5308                                         }
5309                                 }
5310                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5311                         },
5312                         _ => panic!("Unexpected event"),
5313                 }
5314         }
5315
5316         let as_events = nodes[0].node.get_and_clear_pending_events();
5317         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5318         let mut as_failds = HashSet::new();
5319         let mut as_updates = 0;
5320         for event in as_events.iter() {
5321                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5322                         assert!(as_failds.insert(*payment_hash));
5323                         if *payment_hash != payment_hash_2 {
5324                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5325                         } else {
5326                                 assert!(!payment_failed_permanently);
5327                         }
5328                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5329                                 as_updates += 1;
5330                         }
5331                 } else if let &Event::PaymentFailed { .. } = event {
5332                 } else { panic!("Unexpected event"); }
5333         }
5334         assert!(as_failds.contains(&payment_hash_1));
5335         assert!(as_failds.contains(&payment_hash_2));
5336         if announce_latest {
5337                 assert!(as_failds.contains(&payment_hash_3));
5338                 assert!(as_failds.contains(&payment_hash_5));
5339         }
5340         assert!(as_failds.contains(&payment_hash_6));
5341
5342         let bs_events = nodes[1].node.get_and_clear_pending_events();
5343         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5344         let mut bs_failds = HashSet::new();
5345         let mut bs_updates = 0;
5346         for event in bs_events.iter() {
5347                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5348                         assert!(bs_failds.insert(*payment_hash));
5349                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5350                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5351                         } else {
5352                                 assert!(!payment_failed_permanently);
5353                         }
5354                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5355                                 bs_updates += 1;
5356                         }
5357                 } else if let &Event::PaymentFailed { .. } = event {
5358                 } else { panic!("Unexpected event"); }
5359         }
5360         assert!(bs_failds.contains(&payment_hash_1));
5361         assert!(bs_failds.contains(&payment_hash_2));
5362         if announce_latest {
5363                 assert!(bs_failds.contains(&payment_hash_4));
5364         }
5365         assert!(bs_failds.contains(&payment_hash_5));
5366
5367         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5368         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5369         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5370         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5371         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5372         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5373 }
5374
5375 #[test]
5376 fn test_fail_backwards_latest_remote_announce_a() {
5377         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5378 }
5379
5380 #[test]
5381 fn test_fail_backwards_latest_remote_announce_b() {
5382         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5383 }
5384
5385 #[test]
5386 fn test_fail_backwards_previous_remote_announce() {
5387         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5388         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5389         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5390 }
5391
5392 #[test]
5393 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5394         let chanmon_cfgs = create_chanmon_cfgs(2);
5395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5397         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5398
5399         // Create some initial channels
5400         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5401
5402         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5403         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5404         assert_eq!(local_txn[0].input.len(), 1);
5405         check_spends!(local_txn[0], chan_1.3);
5406
5407         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5408         mine_transaction(&nodes[0], &local_txn[0]);
5409         check_closed_broadcast!(nodes[0], true);
5410         check_added_monitors!(nodes[0], 1);
5411         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5412         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5413
5414         let htlc_timeout = {
5415                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5416                 assert_eq!(node_txn.len(), 1);
5417                 assert_eq!(node_txn[0].input.len(), 1);
5418                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5419                 check_spends!(node_txn[0], local_txn[0]);
5420                 node_txn[0].clone()
5421         };
5422
5423         mine_transaction(&nodes[0], &htlc_timeout);
5424         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5425         expect_payment_failed!(nodes[0], our_payment_hash, false);
5426
5427         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5428         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5429         assert_eq!(spend_txn.len(), 3);
5430         check_spends!(spend_txn[0], local_txn[0]);
5431         assert_eq!(spend_txn[1].input.len(), 1);
5432         check_spends!(spend_txn[1], htlc_timeout);
5433         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5434         assert_eq!(spend_txn[2].input.len(), 2);
5435         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5436         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5437                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5438 }
5439
5440 #[test]
5441 fn test_key_derivation_params() {
5442         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5443         // manager rotation to test that `channel_keys_id` returned in
5444         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5445         // then derive a `delayed_payment_key`.
5446
5447         let chanmon_cfgs = create_chanmon_cfgs(3);
5448
5449         // We manually create the node configuration to backup the seed.
5450         let seed = [42; 32];
5451         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5452         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);
5453         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5454         let scorer = RwLock::new(test_utils::TestScorer::new());
5455         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5456         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)) };
5457         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5458         node_cfgs.remove(0);
5459         node_cfgs.insert(0, node);
5460
5461         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5462         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5463
5464         // Create some initial channels
5465         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5466         // for node 0
5467         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5468         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5469         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5470
5471         // Ensure all nodes are at the same height
5472         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5473         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5474         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5475         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5476
5477         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5478         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5479         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5480         assert_eq!(local_txn_1[0].input.len(), 1);
5481         check_spends!(local_txn_1[0], chan_1.3);
5482
5483         // We check funding pubkey are unique
5484         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]));
5485         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]));
5486         if from_0_funding_key_0 == from_1_funding_key_0
5487             || from_0_funding_key_0 == from_1_funding_key_1
5488             || from_0_funding_key_1 == from_1_funding_key_0
5489             || from_0_funding_key_1 == from_1_funding_key_1 {
5490                 panic!("Funding pubkeys aren't unique");
5491         }
5492
5493         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5494         mine_transaction(&nodes[0], &local_txn_1[0]);
5495         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5496         check_closed_broadcast!(nodes[0], true);
5497         check_added_monitors!(nodes[0], 1);
5498         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5499
5500         let htlc_timeout = {
5501                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5502                 assert_eq!(node_txn.len(), 1);
5503                 assert_eq!(node_txn[0].input.len(), 1);
5504                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5505                 check_spends!(node_txn[0], local_txn_1[0]);
5506                 node_txn[0].clone()
5507         };
5508
5509         mine_transaction(&nodes[0], &htlc_timeout);
5510         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5511         expect_payment_failed!(nodes[0], our_payment_hash, false);
5512
5513         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5514         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5515         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5516         assert_eq!(spend_txn.len(), 3);
5517         check_spends!(spend_txn[0], local_txn_1[0]);
5518         assert_eq!(spend_txn[1].input.len(), 1);
5519         check_spends!(spend_txn[1], htlc_timeout);
5520         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5521         assert_eq!(spend_txn[2].input.len(), 2);
5522         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5523         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5524                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5525 }
5526
5527 #[test]
5528 fn test_static_output_closing_tx() {
5529         let chanmon_cfgs = create_chanmon_cfgs(2);
5530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5532         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5533
5534         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5535
5536         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5537         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5538
5539         mine_transaction(&nodes[0], &closing_tx);
5540         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5541         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5542
5543         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5544         assert_eq!(spend_txn.len(), 1);
5545         check_spends!(spend_txn[0], closing_tx);
5546
5547         mine_transaction(&nodes[1], &closing_tx);
5548         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5549         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5550
5551         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5552         assert_eq!(spend_txn.len(), 1);
5553         check_spends!(spend_txn[0], closing_tx);
5554 }
5555
5556 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5557         let chanmon_cfgs = create_chanmon_cfgs(2);
5558         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5559         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5560         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5561         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5562
5563         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5564
5565         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5566         // present in B's local commitment transaction, but none of A's commitment transactions.
5567         nodes[1].node.claim_funds(payment_preimage);
5568         check_added_monitors!(nodes[1], 1);
5569         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5570
5571         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5572         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5573         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5574
5575         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5576         check_added_monitors!(nodes[0], 1);
5577         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5578         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5579         check_added_monitors!(nodes[1], 1);
5580
5581         let starting_block = nodes[1].best_block_info();
5582         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5583         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5584                 connect_block(&nodes[1], &block);
5585                 block.header.prev_blockhash = block.block_hash();
5586         }
5587         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5588         check_closed_broadcast!(nodes[1], true);
5589         check_added_monitors!(nodes[1], 1);
5590         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5591 }
5592
5593 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5594         let chanmon_cfgs = create_chanmon_cfgs(2);
5595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5597         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5598         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5599
5600         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5601         nodes[0].node.send_payment_with_route(&route, payment_hash,
5602                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5603         check_added_monitors!(nodes[0], 1);
5604
5605         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5606
5607         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5608         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5609         // to "time out" the HTLC.
5610
5611         let starting_block = nodes[1].best_block_info();
5612         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5613
5614         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5615                 connect_block(&nodes[0], &block);
5616                 block.header.prev_blockhash = block.block_hash();
5617         }
5618         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5619         check_closed_broadcast!(nodes[0], true);
5620         check_added_monitors!(nodes[0], 1);
5621         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5622 }
5623
5624 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5625         let chanmon_cfgs = create_chanmon_cfgs(3);
5626         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5627         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5628         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5629         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5630
5631         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5632         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5633         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5634         // actually revoked.
5635         let htlc_value = if use_dust { 50000 } else { 3000000 };
5636         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5637         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5638         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5639         check_added_monitors!(nodes[1], 1);
5640
5641         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5642         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5643         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5644         check_added_monitors!(nodes[0], 1);
5645         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5646         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5647         check_added_monitors!(nodes[1], 1);
5648         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5649         check_added_monitors!(nodes[1], 1);
5650         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5651
5652         if check_revoke_no_close {
5653                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5654                 check_added_monitors!(nodes[0], 1);
5655         }
5656
5657         let starting_block = nodes[1].best_block_info();
5658         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5659         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5660                 connect_block(&nodes[0], &block);
5661                 block.header.prev_blockhash = block.block_hash();
5662         }
5663         if !check_revoke_no_close {
5664                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5665                 check_closed_broadcast!(nodes[0], true);
5666                 check_added_monitors!(nodes[0], 1);
5667                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5668         } else {
5669                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5670         }
5671 }
5672
5673 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5674 // There are only a few cases to test here:
5675 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5676 //    broadcastable commitment transactions result in channel closure,
5677 //  * its included in an unrevoked-but-previous remote commitment transaction,
5678 //  * its included in the latest remote or local commitment transactions.
5679 // We test each of the three possible commitment transactions individually and use both dust and
5680 // non-dust HTLCs.
5681 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5682 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5683 // tested for at least one of the cases in other tests.
5684 #[test]
5685 fn htlc_claim_single_commitment_only_a() {
5686         do_htlc_claim_local_commitment_only(true);
5687         do_htlc_claim_local_commitment_only(false);
5688
5689         do_htlc_claim_current_remote_commitment_only(true);
5690         do_htlc_claim_current_remote_commitment_only(false);
5691 }
5692
5693 #[test]
5694 fn htlc_claim_single_commitment_only_b() {
5695         do_htlc_claim_previous_remote_commitment_only(true, false);
5696         do_htlc_claim_previous_remote_commitment_only(false, false);
5697         do_htlc_claim_previous_remote_commitment_only(true, true);
5698         do_htlc_claim_previous_remote_commitment_only(false, true);
5699 }
5700
5701 #[test]
5702 #[should_panic]
5703 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5704         let chanmon_cfgs = create_chanmon_cfgs(2);
5705         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5706         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5707         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5708         // Force duplicate randomness for every get-random call
5709         for node in nodes.iter() {
5710                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5711         }
5712
5713         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5714         let channel_value_satoshis=10000;
5715         let push_msat=10001;
5716         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5717         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5718         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5719         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5720
5721         // Create a second channel with the same random values. This used to panic due to a colliding
5722         // channel_id, but now panics due to a colliding outbound SCID alias.
5723         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5724 }
5725
5726 #[test]
5727 fn bolt2_open_channel_sending_node_checks_part2() {
5728         let chanmon_cfgs = create_chanmon_cfgs(2);
5729         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5730         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5731         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5732
5733         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5734         let channel_value_satoshis=2^24;
5735         let push_msat=10001;
5736         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5737
5738         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5739         let channel_value_satoshis=10000;
5740         // Test when push_msat is equal to 1000 * funding_satoshis.
5741         let push_msat=1000*channel_value_satoshis+1;
5742         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5743
5744         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5745         let channel_value_satoshis=10000;
5746         let push_msat=10001;
5747         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
5748         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5749         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5750
5751         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5752         // 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
5753         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5754
5755         // 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.
5756         assert!(BREAKDOWN_TIMEOUT>0);
5757         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5758
5759         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5760         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5761         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5762
5763         // 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.
5764         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5765         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5766         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5767         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5768         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5769 }
5770
5771 #[test]
5772 fn bolt2_open_channel_sane_dust_limit() {
5773         let chanmon_cfgs = create_chanmon_cfgs(2);
5774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5776         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5777
5778         let channel_value_satoshis=1000000;
5779         let push_msat=10001;
5780         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5781         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5782         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5783         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5784
5785         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5786         let events = nodes[1].node.get_and_clear_pending_msg_events();
5787         let err_msg = match events[0] {
5788                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5789                         msg.clone()
5790                 },
5791                 _ => panic!("Unexpected event"),
5792         };
5793         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5794 }
5795
5796 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5797 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5798 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5799 // is no longer affordable once it's freed.
5800 #[test]
5801 fn test_fail_holding_cell_htlc_upon_free() {
5802         let chanmon_cfgs = create_chanmon_cfgs(2);
5803         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5804         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5805         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5806         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5807
5808         // First nodes[0] generates an update_fee, setting the channel's
5809         // pending_update_fee.
5810         {
5811                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5812                 *feerate_lock += 20;
5813         }
5814         nodes[0].node.timer_tick_occurred();
5815         check_added_monitors!(nodes[0], 1);
5816
5817         let events = nodes[0].node.get_and_clear_pending_msg_events();
5818         assert_eq!(events.len(), 1);
5819         let (update_msg, commitment_signed) = match events[0] {
5820                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5821                         (update_fee.as_ref(), commitment_signed)
5822                 },
5823                 _ => panic!("Unexpected event"),
5824         };
5825
5826         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5827
5828         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5829         let channel_reserve = chan_stat.channel_reserve_msat;
5830         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5831         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5832
5833         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5834         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5835         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5836
5837         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5838         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5839                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5840         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5841         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5842
5843         // Flush the pending fee update.
5844         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5845         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5846         check_added_monitors!(nodes[1], 1);
5847         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5848         check_added_monitors!(nodes[0], 1);
5849
5850         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5851         // HTLC, but now that the fee has been raised the payment will now fail, causing
5852         // us to surface its failure to the user.
5853         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5854         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5855         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5856
5857         // Check that the payment failed to be sent out.
5858         let events = nodes[0].node.get_and_clear_pending_events();
5859         assert_eq!(events.len(), 2);
5860         match &events[0] {
5861                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5862                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5863                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5864                         assert_eq!(*payment_failed_permanently, false);
5865                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5866                 },
5867                 _ => panic!("Unexpected event"),
5868         }
5869         match &events[1] {
5870                 &Event::PaymentFailed { ref payment_hash, .. } => {
5871                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5872                 },
5873                 _ => panic!("Unexpected event"),
5874         }
5875 }
5876
5877 // Test that if multiple HTLCs are released from the holding cell and one is
5878 // valid but the other is no longer valid upon release, the valid HTLC can be
5879 // successfully completed while the other one fails as expected.
5880 #[test]
5881 fn test_free_and_fail_holding_cell_htlcs() {
5882         let chanmon_cfgs = create_chanmon_cfgs(2);
5883         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5884         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5885         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5886         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5887
5888         // First nodes[0] generates an update_fee, setting the channel's
5889         // pending_update_fee.
5890         {
5891                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5892                 *feerate_lock += 200;
5893         }
5894         nodes[0].node.timer_tick_occurred();
5895         check_added_monitors!(nodes[0], 1);
5896
5897         let events = nodes[0].node.get_and_clear_pending_msg_events();
5898         assert_eq!(events.len(), 1);
5899         let (update_msg, commitment_signed) = match events[0] {
5900                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5901                         (update_fee.as_ref(), commitment_signed)
5902                 },
5903                 _ => panic!("Unexpected event"),
5904         };
5905
5906         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5907
5908         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5909         let channel_reserve = chan_stat.channel_reserve_msat;
5910         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5911         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5912
5913         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5914         let amt_1 = 20000;
5915         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5916         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5917         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5918
5919         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5920         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5921                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5922         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5923         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5924         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5925         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5926                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5927         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5928         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5929
5930         // Flush the pending fee update.
5931         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5932         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5933         check_added_monitors!(nodes[1], 1);
5934         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5935         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5936         check_added_monitors!(nodes[0], 2);
5937
5938         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5939         // but now that the fee has been raised the second payment will now fail, causing us
5940         // to surface its failure to the user. The first payment should succeed.
5941         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5942         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5943         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
5944
5945         // Check that the second payment failed to be sent out.
5946         let events = nodes[0].node.get_and_clear_pending_events();
5947         assert_eq!(events.len(), 2);
5948         match &events[0] {
5949                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5950                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5951                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5952                         assert_eq!(*payment_failed_permanently, false);
5953                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5954                 },
5955                 _ => panic!("Unexpected event"),
5956         }
5957         match &events[1] {
5958                 &Event::PaymentFailed { ref payment_hash, .. } => {
5959                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5960                 },
5961                 _ => panic!("Unexpected event"),
5962         }
5963
5964         // Complete the first payment and the RAA from the fee update.
5965         let (payment_event, send_raa_event) = {
5966                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5967                 assert_eq!(msgs.len(), 2);
5968                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5969         };
5970         let raa = match send_raa_event {
5971                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5972                 _ => panic!("Unexpected event"),
5973         };
5974         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5975         check_added_monitors!(nodes[1], 1);
5976         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5977         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5978         let events = nodes[1].node.get_and_clear_pending_events();
5979         assert_eq!(events.len(), 1);
5980         match events[0] {
5981                 Event::PendingHTLCsForwardable { .. } => {},
5982                 _ => panic!("Unexpected event"),
5983         }
5984         nodes[1].node.process_pending_htlc_forwards();
5985         let events = nodes[1].node.get_and_clear_pending_events();
5986         assert_eq!(events.len(), 1);
5987         match events[0] {
5988                 Event::PaymentClaimable { .. } => {},
5989                 _ => panic!("Unexpected event"),
5990         }
5991         nodes[1].node.claim_funds(payment_preimage_1);
5992         check_added_monitors!(nodes[1], 1);
5993         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5994
5995         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5996         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5997         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5998         expect_payment_sent!(nodes[0], payment_preimage_1);
5999 }
6000
6001 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6002 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6003 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6004 // once it's freed.
6005 #[test]
6006 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6007         let chanmon_cfgs = create_chanmon_cfgs(3);
6008         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6009         // Avoid having to include routing fees in calculations
6010         let mut config = test_default_channel_config();
6011         config.channel_config.forwarding_fee_base_msat = 0;
6012         config.channel_config.forwarding_fee_proportional_millionths = 0;
6013         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6014         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6015         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6016         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6017
6018         // First nodes[1] generates an update_fee, setting the channel's
6019         // pending_update_fee.
6020         {
6021                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6022                 *feerate_lock += 20;
6023         }
6024         nodes[1].node.timer_tick_occurred();
6025         check_added_monitors!(nodes[1], 1);
6026
6027         let events = nodes[1].node.get_and_clear_pending_msg_events();
6028         assert_eq!(events.len(), 1);
6029         let (update_msg, commitment_signed) = match events[0] {
6030                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6031                         (update_fee.as_ref(), commitment_signed)
6032                 },
6033                 _ => panic!("Unexpected event"),
6034         };
6035
6036         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6037
6038         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6039         let channel_reserve = chan_stat.channel_reserve_msat;
6040         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6041         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6042
6043         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6044         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6045         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6046         let payment_event = {
6047                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6048                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6049                 check_added_monitors!(nodes[0], 1);
6050
6051                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6052                 assert_eq!(events.len(), 1);
6053
6054                 SendEvent::from_event(events.remove(0))
6055         };
6056         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6057         check_added_monitors!(nodes[1], 0);
6058         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6059         expect_pending_htlcs_forwardable!(nodes[1]);
6060
6061         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6062         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6063
6064         // Flush the pending fee update.
6065         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6066         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6067         check_added_monitors!(nodes[2], 1);
6068         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6069         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6070         check_added_monitors!(nodes[1], 2);
6071
6072         // A final RAA message is generated to finalize the fee update.
6073         let events = nodes[1].node.get_and_clear_pending_msg_events();
6074         assert_eq!(events.len(), 1);
6075
6076         let raa_msg = match &events[0] {
6077                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6078                         msg.clone()
6079                 },
6080                 _ => panic!("Unexpected event"),
6081         };
6082
6083         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6084         check_added_monitors!(nodes[2], 1);
6085         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6086
6087         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6088         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6089         assert_eq!(process_htlc_forwards_event.len(), 2);
6090         match &process_htlc_forwards_event[0] {
6091                 &Event::PendingHTLCsForwardable { .. } => {},
6092                 _ => panic!("Unexpected event"),
6093         }
6094
6095         // In response, we call ChannelManager's process_pending_htlc_forwards
6096         nodes[1].node.process_pending_htlc_forwards();
6097         check_added_monitors!(nodes[1], 1);
6098
6099         // This causes the HTLC to be failed backwards.
6100         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6101         assert_eq!(fail_event.len(), 1);
6102         let (fail_msg, commitment_signed) = match &fail_event[0] {
6103                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6104                         assert_eq!(updates.update_add_htlcs.len(), 0);
6105                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6106                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6107                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6108                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6109                 },
6110                 _ => panic!("Unexpected event"),
6111         };
6112
6113         // Pass the failure messages back to nodes[0].
6114         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6115         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6116
6117         // Complete the HTLC failure+removal process.
6118         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6119         check_added_monitors!(nodes[0], 1);
6120         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6121         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6122         check_added_monitors!(nodes[1], 2);
6123         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6124         assert_eq!(final_raa_event.len(), 1);
6125         let raa = match &final_raa_event[0] {
6126                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6127                 _ => panic!("Unexpected event"),
6128         };
6129         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6130         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6131         check_added_monitors!(nodes[0], 1);
6132 }
6133
6134 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6135 // 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.
6136 //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.
6137
6138 #[test]
6139 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6140         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6141         let chanmon_cfgs = create_chanmon_cfgs(2);
6142         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6143         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6144         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6145         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6146
6147         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6148         route.paths[0].hops[0].fee_msat = 100;
6149
6150         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6151                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6152                 ), true, APIError::ChannelUnavailable { .. }, {});
6153         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6154 }
6155
6156 #[test]
6157 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6158         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6159         let chanmon_cfgs = create_chanmon_cfgs(2);
6160         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6161         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6162         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6163         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6164
6165         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6166         route.paths[0].hops[0].fee_msat = 0;
6167         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6168                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6169                 true, APIError::ChannelUnavailable { ref err },
6170                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6171
6172         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6173         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6174 }
6175
6176 #[test]
6177 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6178         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6179         let chanmon_cfgs = create_chanmon_cfgs(2);
6180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6182         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6183         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6184
6185         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6186         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6187                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6188         check_added_monitors!(nodes[0], 1);
6189         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6190         updates.update_add_htlcs[0].amount_msat = 0;
6191
6192         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6193         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6194         check_closed_broadcast!(nodes[1], true).unwrap();
6195         check_added_monitors!(nodes[1], 1);
6196         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6197                 [nodes[0].node.get_our_node_id()], 100000);
6198 }
6199
6200 #[test]
6201 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6202         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6203         //It is enforced when constructing a route.
6204         let chanmon_cfgs = create_chanmon_cfgs(2);
6205         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6206         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6207         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6208         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6209
6210         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6211                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6212         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6213         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6214         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6215                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6216                 ), true, APIError::InvalidRoute { ref err },
6217                 assert_eq!(err, &"Channel CLTV overflowed?"));
6218 }
6219
6220 #[test]
6221 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6222         //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.
6223         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6224         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6225         let chanmon_cfgs = create_chanmon_cfgs(2);
6226         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6227         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6228         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6229         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6230         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6231                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6232
6233         // Fetch a route in advance as we will be unable to once we're unable to send.
6234         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6235         for i in 0..max_accepted_htlcs {
6236                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6237                 let payment_event = {
6238                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6239                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6240                         check_added_monitors!(nodes[0], 1);
6241
6242                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6243                         assert_eq!(events.len(), 1);
6244                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6245                                 assert_eq!(htlcs[0].htlc_id, i);
6246                         } else {
6247                                 assert!(false);
6248                         }
6249                         SendEvent::from_event(events.remove(0))
6250                 };
6251                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6252                 check_added_monitors!(nodes[1], 0);
6253                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6254
6255                 expect_pending_htlcs_forwardable!(nodes[1]);
6256                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6257         }
6258         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6259                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6260                 ), true, APIError::ChannelUnavailable { .. }, {});
6261
6262         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6263 }
6264
6265 #[test]
6266 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6267         //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.
6268         let chanmon_cfgs = create_chanmon_cfgs(2);
6269         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6270         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6271         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6272         let channel_value = 100000;
6273         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6274         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6275
6276         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6277
6278         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6279         // Manually create a route over our max in flight (which our router normally automatically
6280         // limits us to.
6281         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6282         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6283                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6284                 ), true, APIError::ChannelUnavailable { .. }, {});
6285         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6286
6287         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6288 }
6289
6290 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6291 #[test]
6292 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6293         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6294         let chanmon_cfgs = create_chanmon_cfgs(2);
6295         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6296         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6297         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6298         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6299         let htlc_minimum_msat: u64;
6300         {
6301                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6302                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6303                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6304                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6305         }
6306
6307         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6308         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6309                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6310         check_added_monitors!(nodes[0], 1);
6311         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6312         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6313         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6314         assert!(nodes[1].node.list_channels().is_empty());
6315         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6316         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()));
6317         check_added_monitors!(nodes[1], 1);
6318         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6319 }
6320
6321 #[test]
6322 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6323         //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
6324         let chanmon_cfgs = create_chanmon_cfgs(2);
6325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6327         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6328         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6329
6330         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6331         let channel_reserve = chan_stat.channel_reserve_msat;
6332         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6333         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6334         // The 2* and +1 are for the fee spike reserve.
6335         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6336
6337         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6338         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6339         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6340                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6341         check_added_monitors!(nodes[0], 1);
6342         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6343
6344         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6345         // at this time channel-initiatee receivers are not required to enforce that senders
6346         // respect the fee_spike_reserve.
6347         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6348         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6349
6350         assert!(nodes[1].node.list_channels().is_empty());
6351         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6352         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6353         check_added_monitors!(nodes[1], 1);
6354         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6355 }
6356
6357 #[test]
6358 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6359         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6360         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6361         let chanmon_cfgs = create_chanmon_cfgs(2);
6362         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6363         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6364         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6365         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6366
6367         let send_amt = 3999999;
6368         let (mut route, our_payment_hash, _, our_payment_secret) =
6369                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6370         route.paths[0].hops[0].fee_msat = send_amt;
6371         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6372         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6373         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6374         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6375                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6376         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6377
6378         let mut msg = msgs::UpdateAddHTLC {
6379                 channel_id: chan.2,
6380                 htlc_id: 0,
6381                 amount_msat: 1000,
6382                 payment_hash: our_payment_hash,
6383                 cltv_expiry: htlc_cltv,
6384                 onion_routing_packet: onion_packet.clone(),
6385                 skimmed_fee_msat: None,
6386         };
6387
6388         for i in 0..50 {
6389                 msg.htlc_id = i as u64;
6390                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6391         }
6392         msg.htlc_id = (50) as u64;
6393         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6394
6395         assert!(nodes[1].node.list_channels().is_empty());
6396         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6397         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6398         check_added_monitors!(nodes[1], 1);
6399         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6400 }
6401
6402 #[test]
6403 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6404         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6405         let chanmon_cfgs = create_chanmon_cfgs(2);
6406         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6407         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6408         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6409         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6410
6411         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
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         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;
6417         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6418
6419         assert!(nodes[1].node.list_channels().is_empty());
6420         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6421         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6422         check_added_monitors!(nodes[1], 1);
6423         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6424 }
6425
6426 #[test]
6427 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6428         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6429         let chanmon_cfgs = create_chanmon_cfgs(2);
6430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6433
6434         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6435         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6436         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6437                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6438         check_added_monitors!(nodes[0], 1);
6439         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6440         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6441         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6442
6443         assert!(nodes[1].node.list_channels().is_empty());
6444         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6445         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6446         check_added_monitors!(nodes[1], 1);
6447         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6448 }
6449
6450 #[test]
6451 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6452         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6453         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6454         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6455         let chanmon_cfgs = create_chanmon_cfgs(2);
6456         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6457         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6458         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6459
6460         create_announced_chan_between_nodes(&nodes, 0, 1);
6461         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6462         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6463                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6464         check_added_monitors!(nodes[0], 1);
6465         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6466         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6467
6468         //Disconnect and Reconnect
6469         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6470         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6471         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6472                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6473         }, true).unwrap();
6474         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6475         assert_eq!(reestablish_1.len(), 1);
6476         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6477                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6478         }, false).unwrap();
6479         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6480         assert_eq!(reestablish_2.len(), 1);
6481         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6482         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6483         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6484         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6485
6486         //Resend HTLC
6487         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6488         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6489         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6490         check_added_monitors!(nodes[1], 1);
6491         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6492
6493         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6494
6495         assert!(nodes[1].node.list_channels().is_empty());
6496         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6497         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6498         check_added_monitors!(nodes[1], 1);
6499         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6500 }
6501
6502 #[test]
6503 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6504         //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.
6505
6506         let chanmon_cfgs = create_chanmon_cfgs(2);
6507         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6508         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6509         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6510         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6511         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6512         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6513                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6514
6515         check_added_monitors!(nodes[0], 1);
6516         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6517         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6518
6519         let update_msg = msgs::UpdateFulfillHTLC{
6520                 channel_id: chan.2,
6521                 htlc_id: 0,
6522                 payment_preimage: our_payment_preimage,
6523         };
6524
6525         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6526
6527         assert!(nodes[0].node.list_channels().is_empty());
6528         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6529         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()));
6530         check_added_monitors!(nodes[0], 1);
6531         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6532 }
6533
6534 #[test]
6535 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6536         //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.
6537
6538         let chanmon_cfgs = create_chanmon_cfgs(2);
6539         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6540         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6541         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6542         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6543
6544         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6545         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6546                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6547         check_added_monitors!(nodes[0], 1);
6548         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6549         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6550
6551         let update_msg = msgs::UpdateFailHTLC{
6552                 channel_id: chan.2,
6553                 htlc_id: 0,
6554                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6555         };
6556
6557         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6558
6559         assert!(nodes[0].node.list_channels().is_empty());
6560         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6561         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()));
6562         check_added_monitors!(nodes[0], 1);
6563         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6564 }
6565
6566 #[test]
6567 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6568         //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.
6569
6570         let chanmon_cfgs = create_chanmon_cfgs(2);
6571         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6572         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6573         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6574         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6575
6576         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6577         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6578                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6579         check_added_monitors!(nodes[0], 1);
6580         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6581         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6582         let update_msg = msgs::UpdateFailMalformedHTLC{
6583                 channel_id: chan.2,
6584                 htlc_id: 0,
6585                 sha256_of_onion: [1; 32],
6586                 failure_code: 0x8000,
6587         };
6588
6589         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6590
6591         assert!(nodes[0].node.list_channels().is_empty());
6592         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6593         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()));
6594         check_added_monitors!(nodes[0], 1);
6595         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6596 }
6597
6598 #[test]
6599 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6600         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6601
6602         let chanmon_cfgs = create_chanmon_cfgs(2);
6603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6606         create_announced_chan_between_nodes(&nodes, 0, 1);
6607
6608         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6609
6610         nodes[1].node.claim_funds(our_payment_preimage);
6611         check_added_monitors!(nodes[1], 1);
6612         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6613
6614         let events = nodes[1].node.get_and_clear_pending_msg_events();
6615         assert_eq!(events.len(), 1);
6616         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6617                 match events[0] {
6618                         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, .. } } => {
6619                                 assert!(update_add_htlcs.is_empty());
6620                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6621                                 assert!(update_fail_htlcs.is_empty());
6622                                 assert!(update_fail_malformed_htlcs.is_empty());
6623                                 assert!(update_fee.is_none());
6624                                 update_fulfill_htlcs[0].clone()
6625                         },
6626                         _ => panic!("Unexpected event"),
6627                 }
6628         };
6629
6630         update_fulfill_msg.htlc_id = 1;
6631
6632         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6633
6634         assert!(nodes[0].node.list_channels().is_empty());
6635         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6636         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6637         check_added_monitors!(nodes[0], 1);
6638         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6639 }
6640
6641 #[test]
6642 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6643         //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.
6644
6645         let chanmon_cfgs = create_chanmon_cfgs(2);
6646         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6647         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6648         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6649         create_announced_chan_between_nodes(&nodes, 0, 1);
6650
6651         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6652
6653         nodes[1].node.claim_funds(our_payment_preimage);
6654         check_added_monitors!(nodes[1], 1);
6655         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6656
6657         let events = nodes[1].node.get_and_clear_pending_msg_events();
6658         assert_eq!(events.len(), 1);
6659         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6660                 match events[0] {
6661                         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, .. } } => {
6662                                 assert!(update_add_htlcs.is_empty());
6663                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6664                                 assert!(update_fail_htlcs.is_empty());
6665                                 assert!(update_fail_malformed_htlcs.is_empty());
6666                                 assert!(update_fee.is_none());
6667                                 update_fulfill_htlcs[0].clone()
6668                         },
6669                         _ => panic!("Unexpected event"),
6670                 }
6671         };
6672
6673         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6674
6675         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6676
6677         assert!(nodes[0].node.list_channels().is_empty());
6678         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6679         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6680         check_added_monitors!(nodes[0], 1);
6681         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6682 }
6683
6684 #[test]
6685 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6686         //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.
6687
6688         let chanmon_cfgs = create_chanmon_cfgs(2);
6689         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6690         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6691         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6692         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6693
6694         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6695         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6696                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6697         check_added_monitors!(nodes[0], 1);
6698
6699         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6700         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6701
6702         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6703         check_added_monitors!(nodes[1], 0);
6704         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6705
6706         let events = nodes[1].node.get_and_clear_pending_msg_events();
6707
6708         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6709                 match events[0] {
6710                         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, .. } } => {
6711                                 assert!(update_add_htlcs.is_empty());
6712                                 assert!(update_fulfill_htlcs.is_empty());
6713                                 assert!(update_fail_htlcs.is_empty());
6714                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6715                                 assert!(update_fee.is_none());
6716                                 update_fail_malformed_htlcs[0].clone()
6717                         },
6718                         _ => panic!("Unexpected event"),
6719                 }
6720         };
6721         update_msg.failure_code &= !0x8000;
6722         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6723
6724         assert!(nodes[0].node.list_channels().is_empty());
6725         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6726         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6727         check_added_monitors!(nodes[0], 1);
6728         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6729 }
6730
6731 #[test]
6732 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6733         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6734         //    * 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.
6735
6736         let chanmon_cfgs = create_chanmon_cfgs(3);
6737         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6738         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6739         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6740         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6741         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6742
6743         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6744
6745         //First hop
6746         let mut payment_event = {
6747                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6748                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6749                 check_added_monitors!(nodes[0], 1);
6750                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6751                 assert_eq!(events.len(), 1);
6752                 SendEvent::from_event(events.remove(0))
6753         };
6754         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6755         check_added_monitors!(nodes[1], 0);
6756         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6757         expect_pending_htlcs_forwardable!(nodes[1]);
6758         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6759         assert_eq!(events_2.len(), 1);
6760         check_added_monitors!(nodes[1], 1);
6761         payment_event = SendEvent::from_event(events_2.remove(0));
6762         assert_eq!(payment_event.msgs.len(), 1);
6763
6764         //Second Hop
6765         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6766         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6767         check_added_monitors!(nodes[2], 0);
6768         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6769
6770         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6771         assert_eq!(events_3.len(), 1);
6772         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6773                 match events_3[0] {
6774                         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 } } => {
6775                                 assert!(update_add_htlcs.is_empty());
6776                                 assert!(update_fulfill_htlcs.is_empty());
6777                                 assert!(update_fail_htlcs.is_empty());
6778                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6779                                 assert!(update_fee.is_none());
6780                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6781                         },
6782                         _ => panic!("Unexpected event"),
6783                 }
6784         };
6785
6786         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6787
6788         check_added_monitors!(nodes[1], 0);
6789         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6790         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 }]);
6791         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6792         assert_eq!(events_4.len(), 1);
6793
6794         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6795         match events_4[0] {
6796                 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, .. } } => {
6797                         assert!(update_add_htlcs.is_empty());
6798                         assert!(update_fulfill_htlcs.is_empty());
6799                         assert_eq!(update_fail_htlcs.len(), 1);
6800                         assert!(update_fail_malformed_htlcs.is_empty());
6801                         assert!(update_fee.is_none());
6802                 },
6803                 _ => panic!("Unexpected event"),
6804         };
6805
6806         check_added_monitors!(nodes[1], 1);
6807 }
6808
6809 #[test]
6810 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6811         let chanmon_cfgs = create_chanmon_cfgs(3);
6812         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6813         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6814         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6815         create_announced_chan_between_nodes(&nodes, 0, 1);
6816         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6817
6818         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6819
6820         // First hop
6821         let mut payment_event = {
6822                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6823                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6824                 check_added_monitors!(nodes[0], 1);
6825                 SendEvent::from_node(&nodes[0])
6826         };
6827
6828         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6829         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6830         expect_pending_htlcs_forwardable!(nodes[1]);
6831         check_added_monitors!(nodes[1], 1);
6832         payment_event = SendEvent::from_node(&nodes[1]);
6833         assert_eq!(payment_event.msgs.len(), 1);
6834
6835         // Second Hop
6836         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6837         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6838         check_added_monitors!(nodes[2], 0);
6839         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6840
6841         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6842         assert_eq!(events_3.len(), 1);
6843         match events_3[0] {
6844                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6845                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6846                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6847                         update_msg.failure_code |= 0x2000;
6848
6849                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6850                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6851                 },
6852                 _ => panic!("Unexpected event"),
6853         }
6854
6855         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6856                 vec![HTLCDestination::NextHopChannel {
6857                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6858         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6859         assert_eq!(events_4.len(), 1);
6860         check_added_monitors!(nodes[1], 1);
6861
6862         match events_4[0] {
6863                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6864                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6865                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6866                 },
6867                 _ => panic!("Unexpected event"),
6868         }
6869
6870         let events_5 = nodes[0].node.get_and_clear_pending_events();
6871         assert_eq!(events_5.len(), 2);
6872
6873         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6874         // the node originating the error to its next hop.
6875         match events_5[0] {
6876                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6877                 } => {
6878                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6879                         assert!(is_permanent);
6880                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6881                 },
6882                 _ => panic!("Unexpected event"),
6883         }
6884         match events_5[1] {
6885                 Event::PaymentFailed { payment_hash, .. } => {
6886                         assert_eq!(payment_hash, our_payment_hash);
6887                 },
6888                 _ => panic!("Unexpected event"),
6889         }
6890
6891         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6892 }
6893
6894 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6895         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6896         // 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
6897         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6898
6899         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6900         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6901         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6902         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6903         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6904         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6905
6906         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6907                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
6908
6909         // We route 2 dust-HTLCs between A and B
6910         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6911         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6912         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6913
6914         // Cache one local commitment tx as previous
6915         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6916
6917         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6918         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6919         check_added_monitors!(nodes[1], 0);
6920         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6921         check_added_monitors!(nodes[1], 1);
6922
6923         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6924         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6925         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6926         check_added_monitors!(nodes[0], 1);
6927
6928         // Cache one local commitment tx as lastest
6929         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6930
6931         let events = nodes[0].node.get_and_clear_pending_msg_events();
6932         match events[0] {
6933                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6934                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6935                 },
6936                 _ => panic!("Unexpected event"),
6937         }
6938         match events[1] {
6939                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6940                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6941                 },
6942                 _ => panic!("Unexpected event"),
6943         }
6944
6945         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6946         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6947         if announce_latest {
6948                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6949         } else {
6950                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6951         }
6952
6953         check_closed_broadcast!(nodes[0], true);
6954         check_added_monitors!(nodes[0], 1);
6955         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6956
6957         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6958         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6959         let events = nodes[0].node.get_and_clear_pending_events();
6960         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6961         assert_eq!(events.len(), 4);
6962         let mut first_failed = false;
6963         for event in events {
6964                 match event {
6965                         Event::PaymentPathFailed { payment_hash, .. } => {
6966                                 if payment_hash == payment_hash_1 {
6967                                         assert!(!first_failed);
6968                                         first_failed = true;
6969                                 } else {
6970                                         assert_eq!(payment_hash, payment_hash_2);
6971                                 }
6972                         },
6973                         Event::PaymentFailed { .. } => {}
6974                         _ => panic!("Unexpected event"),
6975                 }
6976         }
6977 }
6978
6979 #[test]
6980 fn test_failure_delay_dust_htlc_local_commitment() {
6981         do_test_failure_delay_dust_htlc_local_commitment(true);
6982         do_test_failure_delay_dust_htlc_local_commitment(false);
6983 }
6984
6985 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6986         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6987         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6988         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6989         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6990         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6991         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6992
6993         let chanmon_cfgs = create_chanmon_cfgs(3);
6994         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6995         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6996         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6997         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6998
6999         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7000                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7001
7002         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7003         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7004
7005         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7006         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7007
7008         // We revoked bs_commitment_tx
7009         if revoked {
7010                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7011                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7012         }
7013
7014         let mut timeout_tx = Vec::new();
7015         if local {
7016                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7017                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7018                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7019                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7020                 expect_payment_failed!(nodes[0], dust_hash, false);
7021
7022                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7023                 check_closed_broadcast!(nodes[0], true);
7024                 check_added_monitors!(nodes[0], 1);
7025                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7026                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7027                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7028                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7029                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7030                 mine_transaction(&nodes[0], &timeout_tx[0]);
7031                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7032                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7033         } else {
7034                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7035                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7036                 check_closed_broadcast!(nodes[0], true);
7037                 check_added_monitors!(nodes[0], 1);
7038                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7039                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7040
7041                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7042                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7043                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7044                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7045                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7046                 // dust HTLC should have been failed.
7047                 expect_payment_failed!(nodes[0], dust_hash, false);
7048
7049                 if !revoked {
7050                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7051                 } else {
7052                         assert_eq!(timeout_tx[0].lock_time.0, 11);
7053                 }
7054                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7055                 mine_transaction(&nodes[0], &timeout_tx[0]);
7056                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7057                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7058                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7059         }
7060 }
7061
7062 #[test]
7063 fn test_sweep_outbound_htlc_failure_update() {
7064         do_test_sweep_outbound_htlc_failure_update(false, true);
7065         do_test_sweep_outbound_htlc_failure_update(false, false);
7066         do_test_sweep_outbound_htlc_failure_update(true, false);
7067 }
7068
7069 #[test]
7070 fn test_user_configurable_csv_delay() {
7071         // We test our channel constructors yield errors when we pass them absurd csv delay
7072
7073         let mut low_our_to_self_config = UserConfig::default();
7074         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7075         let mut high_their_to_self_config = UserConfig::default();
7076         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7077         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7078         let chanmon_cfgs = create_chanmon_cfgs(2);
7079         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7080         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7081         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7082
7083         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7084         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7085                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7086                 &low_our_to_self_config, 0, 42)
7087         {
7088                 match error {
7089                         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())); },
7090                         _ => panic!("Unexpected event"),
7091                 }
7092         } else { assert!(false) }
7093
7094         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7095         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7096         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7097         open_channel.to_self_delay = 200;
7098         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7099                 &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,
7100                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7101         {
7102                 match error {
7103                         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()));  },
7104                         _ => panic!("Unexpected event"),
7105                 }
7106         } else { assert!(false); }
7107
7108         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7109         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7110         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()));
7111         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7112         accept_channel.to_self_delay = 200;
7113         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7114         let reason_msg;
7115         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7116                 match action {
7117                         &ErrorAction::SendErrorMessage { ref msg } => {
7118                                 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()));
7119                                 reason_msg = msg.data.clone();
7120                         },
7121                         _ => { panic!(); }
7122                 }
7123         } else { panic!(); }
7124         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7125
7126         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7127         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7128         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7129         open_channel.to_self_delay = 200;
7130         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7131                 &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,
7132                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7133         {
7134                 match error {
7135                         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())); },
7136                         _ => panic!("Unexpected event"),
7137                 }
7138         } else { assert!(false); }
7139 }
7140
7141 #[test]
7142 fn test_check_htlc_underpaying() {
7143         // Send payment through A -> B but A is maliciously
7144         // sending a probe payment (i.e less than expected value0
7145         // to B, B should refuse payment.
7146
7147         let chanmon_cfgs = create_chanmon_cfgs(2);
7148         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7149         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7150         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7151
7152         // Create some initial channels
7153         create_announced_chan_between_nodes(&nodes, 0, 1);
7154
7155         let scorer = test_utils::TestScorer::new();
7156         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7157         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7158                 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7159         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7160         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7161                 None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7162         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7163         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7164         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7165                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7166         check_added_monitors!(nodes[0], 1);
7167
7168         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7169         assert_eq!(events.len(), 1);
7170         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7171         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7172         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7173
7174         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7175         // and then will wait a second random delay before failing the HTLC back:
7176         expect_pending_htlcs_forwardable!(nodes[1]);
7177         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7178
7179         // Node 3 is expecting payment of 100_000 but received 10_000,
7180         // it should fail htlc like we didn't know the preimage.
7181         nodes[1].node.process_pending_htlc_forwards();
7182
7183         let events = nodes[1].node.get_and_clear_pending_msg_events();
7184         assert_eq!(events.len(), 1);
7185         let (update_fail_htlc, commitment_signed) = match events[0] {
7186                 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 } } => {
7187                         assert!(update_add_htlcs.is_empty());
7188                         assert!(update_fulfill_htlcs.is_empty());
7189                         assert_eq!(update_fail_htlcs.len(), 1);
7190                         assert!(update_fail_malformed_htlcs.is_empty());
7191                         assert!(update_fee.is_none());
7192                         (update_fail_htlcs[0].clone(), commitment_signed)
7193                 },
7194                 _ => panic!("Unexpected event"),
7195         };
7196         check_added_monitors!(nodes[1], 1);
7197
7198         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7199         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7200
7201         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7202         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7203         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7204         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7205 }
7206
7207 #[test]
7208 fn test_announce_disable_channels() {
7209         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7210         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7211
7212         let chanmon_cfgs = create_chanmon_cfgs(2);
7213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7215         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7216
7217         create_announced_chan_between_nodes(&nodes, 0, 1);
7218         create_announced_chan_between_nodes(&nodes, 1, 0);
7219         create_announced_chan_between_nodes(&nodes, 0, 1);
7220
7221         // Disconnect peers
7222         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7223         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7224
7225         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7226                 nodes[0].node.timer_tick_occurred();
7227         }
7228         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7229         assert_eq!(msg_events.len(), 3);
7230         let mut chans_disabled = HashMap::new();
7231         for e in msg_events {
7232                 match e {
7233                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7234                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7235                                 // Check that each channel gets updated exactly once
7236                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7237                                         panic!("Generated ChannelUpdate for wrong chan!");
7238                                 }
7239                         },
7240                         _ => panic!("Unexpected event"),
7241                 }
7242         }
7243         // Reconnect peers
7244         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7245                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7246         }, true).unwrap();
7247         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7248         assert_eq!(reestablish_1.len(), 3);
7249         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7250                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7251         }, false).unwrap();
7252         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7253         assert_eq!(reestablish_2.len(), 3);
7254
7255         // Reestablish chan_1
7256         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7257         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7258         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7259         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7260         // Reestablish chan_2
7261         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7262         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7263         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7264         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7265         // Reestablish chan_3
7266         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7267         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7268         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7269         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7270
7271         for _ in 0..ENABLE_GOSSIP_TICKS {
7272                 nodes[0].node.timer_tick_occurred();
7273         }
7274         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7275         nodes[0].node.timer_tick_occurred();
7276         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7277         assert_eq!(msg_events.len(), 3);
7278         for e in msg_events {
7279                 match e {
7280                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7281                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7282                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7283                                         // Each update should have a higher timestamp than the previous one, replacing
7284                                         // the old one.
7285                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7286                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7287                                 }
7288                         },
7289                         _ => panic!("Unexpected event"),
7290                 }
7291         }
7292         // Check that each channel gets updated exactly once
7293         assert!(chans_disabled.is_empty());
7294 }
7295
7296 #[test]
7297 fn test_bump_penalty_txn_on_revoked_commitment() {
7298         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7299         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7300
7301         let chanmon_cfgs = create_chanmon_cfgs(2);
7302         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7303         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7304         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7305
7306         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7307
7308         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7309         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7310                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7311         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7312         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7313
7314         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7315         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7316         assert_eq!(revoked_txn[0].output.len(), 4);
7317         assert_eq!(revoked_txn[0].input.len(), 1);
7318         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7319         let revoked_txid = revoked_txn[0].txid();
7320
7321         let mut penalty_sum = 0;
7322         for outp in revoked_txn[0].output.iter() {
7323                 if outp.script_pubkey.is_v0_p2wsh() {
7324                         penalty_sum += outp.value;
7325                 }
7326         }
7327
7328         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7329         let header_114 = connect_blocks(&nodes[1], 14);
7330
7331         // Actually revoke tx by claiming a HTLC
7332         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7333         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7334         check_added_monitors!(nodes[1], 1);
7335
7336         // One or more justice tx should have been broadcast, check it
7337         let penalty_1;
7338         let feerate_1;
7339         {
7340                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7341                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7342                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7343                 assert_eq!(node_txn[0].output.len(), 1);
7344                 check_spends!(node_txn[0], revoked_txn[0]);
7345                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7346                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7347                 penalty_1 = node_txn[0].txid();
7348                 node_txn.clear();
7349         };
7350
7351         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7352         connect_blocks(&nodes[1], 15);
7353         let mut penalty_2 = penalty_1;
7354         let mut feerate_2 = 0;
7355         {
7356                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7357                 assert_eq!(node_txn.len(), 1);
7358                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7359                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7360                         assert_eq!(node_txn[0].output.len(), 1);
7361                         check_spends!(node_txn[0], revoked_txn[0]);
7362                         penalty_2 = node_txn[0].txid();
7363                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7364                         assert_ne!(penalty_2, penalty_1);
7365                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7366                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7367                         // Verify 25% bump heuristic
7368                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7369                         node_txn.clear();
7370                 }
7371         }
7372         assert_ne!(feerate_2, 0);
7373
7374         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7375         connect_blocks(&nodes[1], 1);
7376         let penalty_3;
7377         let mut feerate_3 = 0;
7378         {
7379                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7380                 assert_eq!(node_txn.len(), 1);
7381                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7382                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7383                         assert_eq!(node_txn[0].output.len(), 1);
7384                         check_spends!(node_txn[0], revoked_txn[0]);
7385                         penalty_3 = node_txn[0].txid();
7386                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7387                         assert_ne!(penalty_3, penalty_2);
7388                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7389                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7390                         // Verify 25% bump heuristic
7391                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7392                         node_txn.clear();
7393                 }
7394         }
7395         assert_ne!(feerate_3, 0);
7396
7397         nodes[1].node.get_and_clear_pending_events();
7398         nodes[1].node.get_and_clear_pending_msg_events();
7399 }
7400
7401 #[test]
7402 fn test_bump_penalty_txn_on_revoked_htlcs() {
7403         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7404         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7405
7406         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7407         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7411
7412         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7413         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7414         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7415         let scorer = test_utils::TestScorer::new();
7416         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7417         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7418         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7419                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7420         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7421         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7422         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7423         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7424                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7425         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7426
7427         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7428         assert_eq!(revoked_local_txn[0].input.len(), 1);
7429         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7430
7431         // Revoke local commitment tx
7432         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7433
7434         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7435         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7436         check_closed_broadcast!(nodes[1], true);
7437         check_added_monitors!(nodes[1], 1);
7438         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7439         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7440
7441         let revoked_htlc_txn = {
7442                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7443                 assert_eq!(txn.len(), 2);
7444
7445                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7446                 assert_eq!(txn[0].input.len(), 1);
7447                 check_spends!(txn[0], revoked_local_txn[0]);
7448
7449                 assert_eq!(txn[1].input.len(), 1);
7450                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7451                 assert_eq!(txn[1].output.len(), 1);
7452                 check_spends!(txn[1], revoked_local_txn[0]);
7453
7454                 txn
7455         };
7456
7457         // Broadcast set of revoked txn on A
7458         let hash_128 = connect_blocks(&nodes[0], 40);
7459         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7460         connect_block(&nodes[0], &block_11);
7461         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7462         connect_block(&nodes[0], &block_129);
7463         let events = nodes[0].node.get_and_clear_pending_events();
7464         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7465         match events.last().unwrap() {
7466                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7467                 _ => panic!("Unexpected event"),
7468         }
7469         let first;
7470         let feerate_1;
7471         let penalty_txn;
7472         {
7473                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7474                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7475                 // Verify claim tx are spending revoked HTLC txn
7476
7477                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7478                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7479                 // which are included in the same block (they are broadcasted because we scan the
7480                 // transactions linearly and generate claims as we go, they likely should be removed in the
7481                 // future).
7482                 assert_eq!(node_txn[0].input.len(), 1);
7483                 check_spends!(node_txn[0], revoked_local_txn[0]);
7484                 assert_eq!(node_txn[1].input.len(), 1);
7485                 check_spends!(node_txn[1], revoked_local_txn[0]);
7486                 assert_eq!(node_txn[2].input.len(), 1);
7487                 check_spends!(node_txn[2], revoked_local_txn[0]);
7488
7489                 // Each of the three justice transactions claim a separate (single) output of the three
7490                 // available, which we check here:
7491                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7492                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7493                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7494
7495                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7496                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7497
7498                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7499                 // output, checked above).
7500                 assert_eq!(node_txn[3].input.len(), 2);
7501                 assert_eq!(node_txn[3].output.len(), 1);
7502                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7503
7504                 first = node_txn[3].txid();
7505                 // Store both feerates for later comparison
7506                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7507                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7508                 penalty_txn = vec![node_txn[2].clone()];
7509                 node_txn.clear();
7510         }
7511
7512         // Connect one more block to see if bumped penalty are issued for HTLC txn
7513         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7514         connect_block(&nodes[0], &block_130);
7515         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7516         connect_block(&nodes[0], &block_131);
7517
7518         // Few more blocks to confirm penalty txn
7519         connect_blocks(&nodes[0], 4);
7520         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7521         let header_144 = connect_blocks(&nodes[0], 9);
7522         let node_txn = {
7523                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7524                 assert_eq!(node_txn.len(), 1);
7525
7526                 assert_eq!(node_txn[0].input.len(), 2);
7527                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7528                 // Verify bumped tx is different and 25% bump heuristic
7529                 assert_ne!(first, node_txn[0].txid());
7530                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7531                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7532                 assert!(feerate_2 * 100 > feerate_1 * 125);
7533                 let txn = vec![node_txn[0].clone()];
7534                 node_txn.clear();
7535                 txn
7536         };
7537         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7538         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7539         connect_blocks(&nodes[0], 20);
7540         {
7541                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7542                 // We verify than no new transaction has been broadcast because previously
7543                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7544                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7545                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7546                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7547                 // up bumped justice generation.
7548                 assert_eq!(node_txn.len(), 0);
7549                 node_txn.clear();
7550         }
7551         check_closed_broadcast!(nodes[0], true);
7552         check_added_monitors!(nodes[0], 1);
7553 }
7554
7555 #[test]
7556 fn test_bump_penalty_txn_on_remote_commitment() {
7557         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7558         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7559
7560         // Create 2 HTLCs
7561         // Provide preimage for one
7562         // Check aggregation
7563
7564         let chanmon_cfgs = create_chanmon_cfgs(2);
7565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7568
7569         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7570         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7571         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7572
7573         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7574         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7575         assert_eq!(remote_txn[0].output.len(), 4);
7576         assert_eq!(remote_txn[0].input.len(), 1);
7577         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7578
7579         // Claim a HTLC without revocation (provide B monitor with preimage)
7580         nodes[1].node.claim_funds(payment_preimage);
7581         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7582         mine_transaction(&nodes[1], &remote_txn[0]);
7583         check_added_monitors!(nodes[1], 2);
7584         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7585
7586         // One or more claim tx should have been broadcast, check it
7587         let timeout;
7588         let preimage;
7589         let preimage_bump;
7590         let feerate_timeout;
7591         let feerate_preimage;
7592         {
7593                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7594                 // 3 transactions including:
7595                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7596                 assert_eq!(node_txn.len(), 3);
7597                 assert_eq!(node_txn[0].input.len(), 1);
7598                 assert_eq!(node_txn[1].input.len(), 1);
7599                 assert_eq!(node_txn[2].input.len(), 1);
7600                 check_spends!(node_txn[0], remote_txn[0]);
7601                 check_spends!(node_txn[1], remote_txn[0]);
7602                 check_spends!(node_txn[2], remote_txn[0]);
7603
7604                 preimage = node_txn[0].txid();
7605                 let index = node_txn[0].input[0].previous_output.vout;
7606                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7607                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7608
7609                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7610                         (node_txn[2].clone(), node_txn[1].clone())
7611                 } else {
7612                         (node_txn[1].clone(), node_txn[2].clone())
7613                 };
7614
7615                 preimage_bump = preimage_bump_tx;
7616                 check_spends!(preimage_bump, remote_txn[0]);
7617                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7618
7619                 timeout = timeout_tx.txid();
7620                 let index = timeout_tx.input[0].previous_output.vout;
7621                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7622                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7623
7624                 node_txn.clear();
7625         };
7626         assert_ne!(feerate_timeout, 0);
7627         assert_ne!(feerate_preimage, 0);
7628
7629         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7630         connect_blocks(&nodes[1], 1);
7631         {
7632                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7633                 assert_eq!(node_txn.len(), 1);
7634                 assert_eq!(node_txn[0].input.len(), 1);
7635                 assert_eq!(preimage_bump.input.len(), 1);
7636                 check_spends!(node_txn[0], remote_txn[0]);
7637                 check_spends!(preimage_bump, remote_txn[0]);
7638
7639                 let index = preimage_bump.input[0].previous_output.vout;
7640                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7641                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7642                 assert!(new_feerate * 100 > feerate_timeout * 125);
7643                 assert_ne!(timeout, preimage_bump.txid());
7644
7645                 let index = node_txn[0].input[0].previous_output.vout;
7646                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7647                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7648                 assert!(new_feerate * 100 > feerate_preimage * 125);
7649                 assert_ne!(preimage, node_txn[0].txid());
7650
7651                 node_txn.clear();
7652         }
7653
7654         nodes[1].node.get_and_clear_pending_events();
7655         nodes[1].node.get_and_clear_pending_msg_events();
7656 }
7657
7658 #[test]
7659 fn test_counterparty_raa_skip_no_crash() {
7660         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7661         // commitment transaction, we would have happily carried on and provided them the next
7662         // commitment transaction based on one RAA forward. This would probably eventually have led to
7663         // channel closure, but it would not have resulted in funds loss. Still, our
7664         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7665         // check simply that the channel is closed in response to such an RAA, but don't check whether
7666         // we decide to punish our counterparty for revoking their funds (as we don't currently
7667         // implement that).
7668         let chanmon_cfgs = create_chanmon_cfgs(2);
7669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7672         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7673
7674         let per_commitment_secret;
7675         let next_per_commitment_point;
7676         {
7677                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7678                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7679                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7680                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7681                 ).flatten().unwrap().get_signer();
7682
7683                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7684
7685                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7686                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7687                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7688
7689                 // Must revoke without gaps
7690                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7691                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7692
7693                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7694                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7695                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7696         }
7697
7698         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7699                 &msgs::RevokeAndACK {
7700                         channel_id,
7701                         per_commitment_secret,
7702                         next_per_commitment_point,
7703                         #[cfg(taproot)]
7704                         next_local_nonce: None,
7705                 });
7706         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7707         check_added_monitors!(nodes[1], 1);
7708         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7709                 , [nodes[0].node.get_our_node_id()], 100000);
7710 }
7711
7712 #[test]
7713 fn test_bump_txn_sanitize_tracking_maps() {
7714         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7715         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7716
7717         let chanmon_cfgs = create_chanmon_cfgs(2);
7718         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7719         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7720         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7721
7722         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7723         // Lock HTLC in both directions
7724         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7725         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7726
7727         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7728         assert_eq!(revoked_local_txn[0].input.len(), 1);
7729         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7730
7731         // Revoke local commitment tx
7732         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7733
7734         // Broadcast set of revoked txn on A
7735         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7736         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7737         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7738
7739         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7740         check_closed_broadcast!(nodes[0], true);
7741         check_added_monitors!(nodes[0], 1);
7742         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7743         let penalty_txn = {
7744                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7745                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7746                 check_spends!(node_txn[0], revoked_local_txn[0]);
7747                 check_spends!(node_txn[1], revoked_local_txn[0]);
7748                 check_spends!(node_txn[2], revoked_local_txn[0]);
7749                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7750                 node_txn.clear();
7751                 penalty_txn
7752         };
7753         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7754         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7755         {
7756                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7757                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7758                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7759         }
7760 }
7761
7762 #[test]
7763 fn test_channel_conf_timeout() {
7764         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7765         // confirm within 2016 blocks, as recommended by BOLT 2.
7766         let chanmon_cfgs = create_chanmon_cfgs(2);
7767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7770
7771         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7772
7773         // The outbound node should wait forever for confirmation:
7774         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7775         // copied here instead of directly referencing the constant.
7776         connect_blocks(&nodes[0], 2016);
7777         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7778
7779         // The inbound node should fail the channel after exactly 2016 blocks
7780         connect_blocks(&nodes[1], 2015);
7781         check_added_monitors!(nodes[1], 0);
7782         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7783
7784         connect_blocks(&nodes[1], 1);
7785         check_added_monitors!(nodes[1], 1);
7786         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7787         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7788         assert_eq!(close_ev.len(), 1);
7789         match close_ev[0] {
7790                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7791                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7792                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7793                 },
7794                 _ => panic!("Unexpected event"),
7795         }
7796 }
7797
7798 #[test]
7799 fn test_override_channel_config() {
7800         let chanmon_cfgs = create_chanmon_cfgs(2);
7801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7804
7805         // Node0 initiates a channel to node1 using the override config.
7806         let mut override_config = UserConfig::default();
7807         override_config.channel_handshake_config.our_to_self_delay = 200;
7808
7809         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7810
7811         // Assert the channel created by node0 is using the override config.
7812         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7813         assert_eq!(res.channel_flags, 0);
7814         assert_eq!(res.to_self_delay, 200);
7815 }
7816
7817 #[test]
7818 fn test_override_0msat_htlc_minimum() {
7819         let mut zero_config = UserConfig::default();
7820         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7821         let chanmon_cfgs = create_chanmon_cfgs(2);
7822         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7823         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7824         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7825
7826         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7827         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7828         assert_eq!(res.htlc_minimum_msat, 1);
7829
7830         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7831         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7832         assert_eq!(res.htlc_minimum_msat, 1);
7833 }
7834
7835 #[test]
7836 fn test_channel_update_has_correct_htlc_maximum_msat() {
7837         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7838         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7839         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7840         // 90% of the `channel_value`.
7841         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7842
7843         let mut config_30_percent = UserConfig::default();
7844         config_30_percent.channel_handshake_config.announced_channel = true;
7845         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7846         let mut config_50_percent = UserConfig::default();
7847         config_50_percent.channel_handshake_config.announced_channel = true;
7848         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7849         let mut config_95_percent = UserConfig::default();
7850         config_95_percent.channel_handshake_config.announced_channel = true;
7851         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7852         let mut config_100_percent = UserConfig::default();
7853         config_100_percent.channel_handshake_config.announced_channel = true;
7854         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7855
7856         let chanmon_cfgs = create_chanmon_cfgs(4);
7857         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7858         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)]);
7859         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7860
7861         let channel_value_satoshis = 100000;
7862         let channel_value_msat = channel_value_satoshis * 1000;
7863         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7864         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7865         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7866
7867         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7868         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7869
7870         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7871         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7872         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7873         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7874         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7875         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7876
7877         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7878         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7879         // `channel_value`.
7880         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7881         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7882         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7883         // `channel_value`.
7884         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7885 }
7886
7887 #[test]
7888 fn test_manually_accept_inbound_channel_request() {
7889         let mut manually_accept_conf = UserConfig::default();
7890         manually_accept_conf.manually_accept_inbound_channels = true;
7891         let chanmon_cfgs = create_chanmon_cfgs(2);
7892         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7893         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7894         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7895
7896         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7897         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7898
7899         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7900
7901         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7902         // accepting the inbound channel request.
7903         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7904
7905         let events = nodes[1].node.get_and_clear_pending_events();
7906         match events[0] {
7907                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7908                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7909                 }
7910                 _ => panic!("Unexpected event"),
7911         }
7912
7913         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7914         assert_eq!(accept_msg_ev.len(), 1);
7915
7916         match accept_msg_ev[0] {
7917                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7918                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7919                 }
7920                 _ => panic!("Unexpected event"),
7921         }
7922
7923         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7924
7925         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7926         assert_eq!(close_msg_ev.len(), 1);
7927
7928         let events = nodes[1].node.get_and_clear_pending_events();
7929         match events[0] {
7930                 Event::ChannelClosed { user_channel_id, .. } => {
7931                         assert_eq!(user_channel_id, 23);
7932                 }
7933                 _ => panic!("Unexpected event"),
7934         }
7935 }
7936
7937 #[test]
7938 fn test_manually_reject_inbound_channel_request() {
7939         let mut manually_accept_conf = UserConfig::default();
7940         manually_accept_conf.manually_accept_inbound_channels = true;
7941         let chanmon_cfgs = create_chanmon_cfgs(2);
7942         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7943         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7944         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7945
7946         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7947         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7948
7949         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7950
7951         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7952         // rejecting the inbound channel request.
7953         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7954
7955         let events = nodes[1].node.get_and_clear_pending_events();
7956         match events[0] {
7957                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7958                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7959                 }
7960                 _ => panic!("Unexpected event"),
7961         }
7962
7963         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7964         assert_eq!(close_msg_ev.len(), 1);
7965
7966         match close_msg_ev[0] {
7967                 MessageSendEvent::HandleError { ref node_id, .. } => {
7968                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7969                 }
7970                 _ => panic!("Unexpected event"),
7971         }
7972
7973         // There should be no more events to process, as the channel was never opened.
7974         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7975 }
7976
7977 #[test]
7978 fn test_can_not_accept_inbound_channel_twice() {
7979         let mut manually_accept_conf = UserConfig::default();
7980         manually_accept_conf.manually_accept_inbound_channels = true;
7981         let chanmon_cfgs = create_chanmon_cfgs(2);
7982         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7983         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7984         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7985
7986         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7987         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7988
7989         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7990
7991         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7992         // accepting the inbound channel request.
7993         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7994
7995         let events = nodes[1].node.get_and_clear_pending_events();
7996         match events[0] {
7997                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7998                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7999                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8000                         match api_res {
8001                                 Err(APIError::APIMisuseError { err }) => {
8002                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8003                                 },
8004                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8005                                 Err(e) => panic!("Unexpected Error {:?}", e),
8006                         }
8007                 }
8008                 _ => panic!("Unexpected event"),
8009         }
8010
8011         // Ensure that the channel wasn't closed after attempting to accept it twice.
8012         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8013         assert_eq!(accept_msg_ev.len(), 1);
8014
8015         match accept_msg_ev[0] {
8016                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8017                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8018                 }
8019                 _ => panic!("Unexpected event"),
8020         }
8021 }
8022
8023 #[test]
8024 fn test_can_not_accept_unknown_inbound_channel() {
8025         let chanmon_cfg = create_chanmon_cfgs(2);
8026         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8027         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8028         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8029
8030         let unknown_channel_id = ChannelId::new_zero();
8031         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8032         match api_res {
8033                 Err(APIError::APIMisuseError { err }) => {
8034                         assert_eq!(err, "No such channel awaiting to be accepted.");
8035                 },
8036                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8037                 Err(e) => panic!("Unexpected Error: {:?}", e),
8038         }
8039 }
8040
8041 #[test]
8042 fn test_onion_value_mpp_set_calculation() {
8043         // Test that we use the onion value `amt_to_forward` when
8044         // calculating whether we've reached the `total_msat` of an MPP
8045         // by having a routing node forward more than `amt_to_forward`
8046         // and checking that the receiving node doesn't generate
8047         // a PaymentClaimable event too early
8048         let node_count = 4;
8049         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8050         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8051         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8052         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8053
8054         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8055         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8056         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8057         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8058
8059         let total_msat = 100_000;
8060         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8061         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8062         let sample_path = route.paths.pop().unwrap();
8063
8064         let mut path_1 = sample_path.clone();
8065         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8066         path_1.hops[0].short_channel_id = chan_1_id;
8067         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8068         path_1.hops[1].short_channel_id = chan_3_id;
8069         path_1.hops[1].fee_msat = 100_000;
8070         route.paths.push(path_1);
8071
8072         let mut path_2 = sample_path.clone();
8073         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8074         path_2.hops[0].short_channel_id = chan_2_id;
8075         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8076         path_2.hops[1].short_channel_id = chan_4_id;
8077         path_2.hops[1].fee_msat = 1_000;
8078         route.paths.push(path_2);
8079
8080         // Send payment
8081         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8082         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8083                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8084         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8085                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8086         check_added_monitors!(nodes[0], expected_paths.len());
8087
8088         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8089         assert_eq!(events.len(), expected_paths.len());
8090
8091         // First path
8092         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8093         let mut payment_event = SendEvent::from_event(ev);
8094         let mut prev_node = &nodes[0];
8095
8096         for (idx, &node) in expected_paths[0].iter().enumerate() {
8097                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8098
8099                 if idx == 0 { // routing node
8100                         let session_priv = [3; 32];
8101                         let height = nodes[0].best_block_info().1;
8102                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8103                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8104                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8105                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8106                         // Edit amt_to_forward to simulate the sender having set
8107                         // the final amount and the routing node taking less fee
8108                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8109                                 *amt_msat = 99_000;
8110                         } else { panic!() }
8111                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8112                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8113                 }
8114
8115                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8116                 check_added_monitors!(node, 0);
8117                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8118                 expect_pending_htlcs_forwardable!(node);
8119
8120                 if idx == 0 {
8121                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8122                         assert_eq!(events_2.len(), 1);
8123                         check_added_monitors!(node, 1);
8124                         payment_event = SendEvent::from_event(events_2.remove(0));
8125                         assert_eq!(payment_event.msgs.len(), 1);
8126                 } else {
8127                         let events_2 = node.node.get_and_clear_pending_events();
8128                         assert!(events_2.is_empty());
8129                 }
8130
8131                 prev_node = node;
8132         }
8133
8134         // Second path
8135         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8136         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8137
8138         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8139 }
8140
8141 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8142
8143         let routing_node_count = msat_amounts.len();
8144         let node_count = routing_node_count + 2;
8145
8146         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8147         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8148         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8149         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8150
8151         let src_idx = 0;
8152         let dst_idx = 1;
8153
8154         // Create channels for each amount
8155         let mut expected_paths = Vec::with_capacity(routing_node_count);
8156         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8157         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8158         for i in 0..routing_node_count {
8159                 let routing_node = 2 + i;
8160                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8161                 src_chan_ids.push(src_chan_id);
8162                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8163                 dst_chan_ids.push(dst_chan_id);
8164                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8165                 expected_paths.push(path);
8166         }
8167         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8168
8169         // Create a route for each amount
8170         let example_amount = 100000;
8171         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);
8172         let sample_path = route.paths.pop().unwrap();
8173         for i in 0..routing_node_count {
8174                 let routing_node = 2 + i;
8175                 let mut path = sample_path.clone();
8176                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8177                 path.hops[0].short_channel_id = src_chan_ids[i];
8178                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8179                 path.hops[1].short_channel_id = dst_chan_ids[i];
8180                 path.hops[1].fee_msat = msat_amounts[i];
8181                 route.paths.push(path);
8182         }
8183
8184         // Send payment with manually set total_msat
8185         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8186         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8187                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8188         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8189                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8190         check_added_monitors!(nodes[src_idx], expected_paths.len());
8191
8192         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8193         assert_eq!(events.len(), expected_paths.len());
8194         let mut amount_received = 0;
8195         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8196                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8197
8198                 let current_path_amount = msat_amounts[path_idx];
8199                 amount_received += current_path_amount;
8200                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8201                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8202         }
8203
8204         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8205 }
8206
8207 #[test]
8208 fn test_overshoot_mpp() {
8209         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8210         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8211 }
8212
8213 #[test]
8214 fn test_simple_mpp() {
8215         // Simple test of sending a multi-path payment.
8216         let chanmon_cfgs = create_chanmon_cfgs(4);
8217         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8218         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8219         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8220
8221         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8222         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8223         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8224         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8225
8226         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8227         let path = route.paths[0].clone();
8228         route.paths.push(path);
8229         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8230         route.paths[0].hops[0].short_channel_id = chan_1_id;
8231         route.paths[0].hops[1].short_channel_id = chan_3_id;
8232         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8233         route.paths[1].hops[0].short_channel_id = chan_2_id;
8234         route.paths[1].hops[1].short_channel_id = chan_4_id;
8235         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8236         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8237 }
8238
8239 #[test]
8240 fn test_preimage_storage() {
8241         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8242         let chanmon_cfgs = create_chanmon_cfgs(2);
8243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8245         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8246
8247         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8248
8249         {
8250                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8251                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8252                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8253                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8254                 check_added_monitors!(nodes[0], 1);
8255                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8256                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8257                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8258                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8259         }
8260         // Note that after leaving the above scope we have no knowledge of any arguments or return
8261         // values from previous calls.
8262         expect_pending_htlcs_forwardable!(nodes[1]);
8263         let events = nodes[1].node.get_and_clear_pending_events();
8264         assert_eq!(events.len(), 1);
8265         match events[0] {
8266                 Event::PaymentClaimable { ref purpose, .. } => {
8267                         match &purpose {
8268                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8269                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8270                                 },
8271                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8272                         }
8273                 },
8274                 _ => panic!("Unexpected event"),
8275         }
8276 }
8277
8278 #[test]
8279 fn test_bad_secret_hash() {
8280         // Simple test of unregistered payment hash/invalid payment secret handling
8281         let chanmon_cfgs = create_chanmon_cfgs(2);
8282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8284         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8285
8286         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8287
8288         let random_payment_hash = PaymentHash([42; 32]);
8289         let random_payment_secret = PaymentSecret([43; 32]);
8290         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8291         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8292
8293         // All the below cases should end up being handled exactly identically, so we macro the
8294         // resulting events.
8295         macro_rules! handle_unknown_invalid_payment_data {
8296                 ($payment_hash: expr) => {
8297                         check_added_monitors!(nodes[0], 1);
8298                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8299                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8300                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8301                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8302
8303                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8304                         // again to process the pending backwards-failure of the HTLC
8305                         expect_pending_htlcs_forwardable!(nodes[1]);
8306                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8307                         check_added_monitors!(nodes[1], 1);
8308
8309                         // We should fail the payment back
8310                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8311                         match events.pop().unwrap() {
8312                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8313                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8314                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8315                                 },
8316                                 _ => panic!("Unexpected event"),
8317                         }
8318                 }
8319         }
8320
8321         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8322         // Error data is the HTLC value (100,000) and current block height
8323         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8324
8325         // Send a payment with the right payment hash but the wrong payment secret
8326         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8327                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8328         handle_unknown_invalid_payment_data!(our_payment_hash);
8329         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8330
8331         // Send a payment with a random payment hash, but the right payment secret
8332         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8333                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8334         handle_unknown_invalid_payment_data!(random_payment_hash);
8335         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8336
8337         // Send a payment with a random payment hash and random payment secret
8338         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8339                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8340         handle_unknown_invalid_payment_data!(random_payment_hash);
8341         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8342 }
8343
8344 #[test]
8345 fn test_update_err_monitor_lockdown() {
8346         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8347         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8348         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8349         // error.
8350         //
8351         // This scenario may happen in a watchtower setup, where watchtower process a block height
8352         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8353         // commitment at same time.
8354
8355         let chanmon_cfgs = create_chanmon_cfgs(2);
8356         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8357         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8358         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8359
8360         // Create some initial channel
8361         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8362         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8363
8364         // Rebalance the network to generate htlc in the two directions
8365         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8366
8367         // Route a HTLC from node 0 to node 1 (but don't settle)
8368         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8369
8370         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8371         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8372         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8373         let persister = test_utils::TestPersister::new();
8374         let watchtower = {
8375                 let new_monitor = {
8376                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8377                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8378                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8379                         assert!(new_monitor == *monitor);
8380                         new_monitor
8381                 };
8382                 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);
8383                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8384                 watchtower
8385         };
8386         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8387         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8388         // transaction lock time requirements here.
8389         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8390         watchtower.chain_monitor.block_connected(&block, 200);
8391
8392         // Try to update ChannelMonitor
8393         nodes[1].node.claim_funds(preimage);
8394         check_added_monitors!(nodes[1], 1);
8395         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8396
8397         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8398         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8399         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8400         {
8401                 let mut node_0_per_peer_lock;
8402                 let mut node_0_peer_state_lock;
8403                 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) {
8404                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8405                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8406                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8407                         } else { assert!(false); }
8408                 } else {
8409                         assert!(false);
8410                 }
8411         }
8412         // Our local monitor is in-sync and hasn't processed yet timeout
8413         check_added_monitors!(nodes[0], 1);
8414         let events = nodes[0].node.get_and_clear_pending_events();
8415         assert_eq!(events.len(), 1);
8416 }
8417
8418 #[test]
8419 fn test_concurrent_monitor_claim() {
8420         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8421         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8422         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8423         // state N+1 confirms. Alice claims output from state N+1.
8424
8425         let chanmon_cfgs = create_chanmon_cfgs(2);
8426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8429
8430         // Create some initial channel
8431         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8432         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8433
8434         // Rebalance the network to generate htlc in the two directions
8435         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8436
8437         // Route a HTLC from node 0 to node 1 (but don't settle)
8438         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8439
8440         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8441         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8442         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8443         let persister = test_utils::TestPersister::new();
8444         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8445                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8446         );
8447         let watchtower_alice = {
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), &alice_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 Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8461         // requirements here.
8462         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8463         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8464         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8465
8466         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8467         let alice_state = {
8468                 let mut txn = alice_broadcaster.txn_broadcast();
8469                 assert_eq!(txn.len(), 2);
8470                 txn.remove(0)
8471         };
8472
8473         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8474         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8475         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8476         let persister = test_utils::TestPersister::new();
8477         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8478         let watchtower_bob = {
8479                 let new_monitor = {
8480                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8481                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8482                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8483                         assert!(new_monitor == *monitor);
8484                         new_monitor
8485                 };
8486                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8487                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8488                 watchtower
8489         };
8490         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8491
8492         // Route another payment to generate another update with still previous HTLC pending
8493         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8494         nodes[1].node.send_payment_with_route(&route, payment_hash,
8495                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8496         check_added_monitors!(nodes[1], 1);
8497
8498         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8499         assert_eq!(updates.update_add_htlcs.len(), 1);
8500         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8501         {
8502                 let mut node_0_per_peer_lock;
8503                 let mut node_0_peer_state_lock;
8504                 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) {
8505                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8506                                 // Watchtower Alice should already have seen the block and reject the update
8507                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8508                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8509                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8510                         } else { assert!(false); }
8511                 } else {
8512                         assert!(false);
8513                 }
8514         }
8515         // Our local monitor is in-sync and hasn't processed yet timeout
8516         check_added_monitors!(nodes[0], 1);
8517
8518         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8519         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8520
8521         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8522         let bob_state_y;
8523         {
8524                 let mut txn = bob_broadcaster.txn_broadcast();
8525                 assert_eq!(txn.len(), 2);
8526                 bob_state_y = txn.remove(0);
8527         };
8528
8529         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8530         let height = HTLC_TIMEOUT_BROADCAST + 1;
8531         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8532         check_closed_broadcast(&nodes[0], 1, true);
8533         check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8534                 [nodes[1].node.get_our_node_id()], 100000);
8535         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8536         check_added_monitors(&nodes[0], 1);
8537         {
8538                 let htlc_txn = alice_broadcaster.txn_broadcast();
8539                 assert_eq!(htlc_txn.len(), 2);
8540                 check_spends!(htlc_txn[0], bob_state_y);
8541                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8542                 // it. However, she should, because it now has an invalid parent.
8543                 check_spends!(htlc_txn[1], alice_state);
8544         }
8545 }
8546
8547 #[test]
8548 fn test_pre_lockin_no_chan_closed_update() {
8549         // Test that if a peer closes a channel in response to a funding_created message we don't
8550         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8551         // message).
8552         //
8553         // Doing so would imply a channel monitor update before the initial channel monitor
8554         // registration, violating our API guarantees.
8555         //
8556         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8557         // then opening a second channel with the same funding output as the first (which is not
8558         // rejected because the first channel does not exist in the ChannelManager) and closing it
8559         // before receiving funding_signed.
8560         let chanmon_cfgs = create_chanmon_cfgs(2);
8561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8563         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8564
8565         // Create an initial channel
8566         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8567         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8568         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8569         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8570         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8571
8572         // Move the first channel through the funding flow...
8573         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8574
8575         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8576         check_added_monitors!(nodes[0], 0);
8577
8578         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8579         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8580         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8581         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8582         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8583                 [nodes[1].node.get_our_node_id(); 2], 100000);
8584 }
8585
8586 #[test]
8587 fn test_htlc_no_detection() {
8588         // This test is a mutation to underscore the detection logic bug we had
8589         // before #653. HTLC value routed is above the remaining balance, thus
8590         // inverting HTLC and `to_remote` output. HTLC will come second and
8591         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8592         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8593         // outputs order detection for correct spending children filtring.
8594
8595         let chanmon_cfgs = create_chanmon_cfgs(2);
8596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8598         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8599
8600         // Create some initial channels
8601         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8602
8603         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8604         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8605         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8606         assert_eq!(local_txn[0].input.len(), 1);
8607         assert_eq!(local_txn[0].output.len(), 3);
8608         check_spends!(local_txn[0], chan_1.3);
8609
8610         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8611         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8612         connect_block(&nodes[0], &block);
8613         // We deliberately connect the local tx twice as this should provoke a failure calling
8614         // this test before #653 fix.
8615         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8616         check_closed_broadcast!(nodes[0], true);
8617         check_added_monitors!(nodes[0], 1);
8618         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8619         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8620
8621         let htlc_timeout = {
8622                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8623                 assert_eq!(node_txn.len(), 1);
8624                 assert_eq!(node_txn[0].input.len(), 1);
8625                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8626                 check_spends!(node_txn[0], local_txn[0]);
8627                 node_txn[0].clone()
8628         };
8629
8630         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8631         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8632         expect_payment_failed!(nodes[0], our_payment_hash, false);
8633 }
8634
8635 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8636         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8637         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8638         // Carol, Alice would be the upstream node, and Carol the downstream.)
8639         //
8640         // Steps of the test:
8641         // 1) Alice sends a HTLC to Carol through Bob.
8642         // 2) Carol doesn't settle the HTLC.
8643         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8644         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8645         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8646         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8647         // 5) Carol release the preimage to Bob off-chain.
8648         // 6) Bob claims the offered output on the broadcasted commitment.
8649         let chanmon_cfgs = create_chanmon_cfgs(3);
8650         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8651         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8652         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8653
8654         // Create some initial channels
8655         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8656         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8657
8658         // Steps (1) and (2):
8659         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8660         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8661
8662         // Check that Alice's commitment transaction now contains an output for this HTLC.
8663         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8664         check_spends!(alice_txn[0], chan_ab.3);
8665         assert_eq!(alice_txn[0].output.len(), 2);
8666         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8667         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8668         assert_eq!(alice_txn.len(), 2);
8669
8670         // Steps (3) and (4):
8671         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8672         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8673         let mut force_closing_node = 0; // Alice force-closes
8674         let mut counterparty_node = 1; // Bob if Alice force-closes
8675
8676         // Bob force-closes
8677         if !broadcast_alice {
8678                 force_closing_node = 1;
8679                 counterparty_node = 0;
8680         }
8681         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8682         check_closed_broadcast!(nodes[force_closing_node], true);
8683         check_added_monitors!(nodes[force_closing_node], 1);
8684         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8685         if go_onchain_before_fulfill {
8686                 let txn_to_broadcast = match broadcast_alice {
8687                         true => alice_txn.clone(),
8688                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8689                 };
8690                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8691                 if broadcast_alice {
8692                         check_closed_broadcast!(nodes[1], true);
8693                         check_added_monitors!(nodes[1], 1);
8694                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8695                 }
8696         }
8697
8698         // Step (5):
8699         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8700         // process of removing the HTLC from their commitment transactions.
8701         nodes[2].node.claim_funds(payment_preimage);
8702         check_added_monitors!(nodes[2], 1);
8703         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8704
8705         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8706         assert!(carol_updates.update_add_htlcs.is_empty());
8707         assert!(carol_updates.update_fail_htlcs.is_empty());
8708         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8709         assert!(carol_updates.update_fee.is_none());
8710         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8711
8712         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8713         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8714         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8715         if !go_onchain_before_fulfill && broadcast_alice {
8716                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8717                 assert_eq!(events.len(), 1);
8718                 match events[0] {
8719                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8720                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8721                         },
8722                         _ => panic!("Unexpected event"),
8723                 };
8724         }
8725         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8726         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8727         // Carol<->Bob's updated commitment transaction info.
8728         check_added_monitors!(nodes[1], 2);
8729
8730         let events = nodes[1].node.get_and_clear_pending_msg_events();
8731         assert_eq!(events.len(), 2);
8732         let bob_revocation = match events[0] {
8733                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8734                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8735                         (*msg).clone()
8736                 },
8737                 _ => panic!("Unexpected event"),
8738         };
8739         let bob_updates = match events[1] {
8740                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8741                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8742                         (*updates).clone()
8743                 },
8744                 _ => panic!("Unexpected event"),
8745         };
8746
8747         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8748         check_added_monitors!(nodes[2], 1);
8749         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8750         check_added_monitors!(nodes[2], 1);
8751
8752         let events = nodes[2].node.get_and_clear_pending_msg_events();
8753         assert_eq!(events.len(), 1);
8754         let carol_revocation = match events[0] {
8755                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8756                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8757                         (*msg).clone()
8758                 },
8759                 _ => panic!("Unexpected event"),
8760         };
8761         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8762         check_added_monitors!(nodes[1], 1);
8763
8764         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8765         // here's where we put said channel's commitment tx on-chain.
8766         let mut txn_to_broadcast = alice_txn.clone();
8767         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8768         if !go_onchain_before_fulfill {
8769                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8770                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8771                 if broadcast_alice {
8772                         check_closed_broadcast!(nodes[1], true);
8773                         check_added_monitors!(nodes[1], 1);
8774                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8775                 }
8776                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8777                 if broadcast_alice {
8778                         assert_eq!(bob_txn.len(), 1);
8779                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8780                 } else {
8781                         assert_eq!(bob_txn.len(), 2);
8782                         check_spends!(bob_txn[0], chan_ab.3);
8783                 }
8784         }
8785
8786         // Step (6):
8787         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8788         // broadcasted commitment transaction.
8789         {
8790                 let script_weight = match broadcast_alice {
8791                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8792                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8793                 };
8794                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8795                 // Bob force-closed and broadcasts the commitment transaction along with a
8796                 // HTLC-output-claiming transaction.
8797                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8798                 if broadcast_alice {
8799                         assert_eq!(bob_txn.len(), 1);
8800                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8801                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8802                 } else {
8803                         assert_eq!(bob_txn.len(), 2);
8804                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8805                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8806                 }
8807         }
8808 }
8809
8810 #[test]
8811 fn test_onchain_htlc_settlement_after_close() {
8812         do_test_onchain_htlc_settlement_after_close(true, true);
8813         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8814         do_test_onchain_htlc_settlement_after_close(true, false);
8815         do_test_onchain_htlc_settlement_after_close(false, false);
8816 }
8817
8818 #[test]
8819 fn test_duplicate_temporary_channel_id_from_different_peers() {
8820         // Tests that we can accept two different `OpenChannel` requests with the same
8821         // `temporary_channel_id`, as long as they are from different peers.
8822         let chanmon_cfgs = create_chanmon_cfgs(3);
8823         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8824         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8825         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8826
8827         // Create an first channel channel
8828         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8829         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8830
8831         // Create an second channel
8832         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8833         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8834
8835         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8836         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8837         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8838
8839         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8840         // `temporary_channel_id` as they are from different peers.
8841         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8842         {
8843                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8844                 assert_eq!(events.len(), 1);
8845                 match &events[0] {
8846                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8847                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8848                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8849                         },
8850                         _ => panic!("Unexpected event"),
8851                 }
8852         }
8853
8854         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8855         {
8856                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8857                 assert_eq!(events.len(), 1);
8858                 match &events[0] {
8859                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8860                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8861                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8862                         },
8863                         _ => panic!("Unexpected event"),
8864                 }
8865         }
8866 }
8867
8868 #[test]
8869 fn test_duplicate_chan_id() {
8870         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8871         // already open we reject it and keep the old channel.
8872         //
8873         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8874         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8875         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8876         // updating logic for the existing channel.
8877         let chanmon_cfgs = create_chanmon_cfgs(2);
8878         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8879         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8880         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8881
8882         // Create an initial channel
8883         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8884         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8885         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8886         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()));
8887
8888         // Try to create a second channel with the same temporary_channel_id as the first and check
8889         // that it is rejected.
8890         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8891         {
8892                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8893                 assert_eq!(events.len(), 1);
8894                 match events[0] {
8895                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8896                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8897                                 // first (valid) and second (invalid) channels are closed, given they both have
8898                                 // the same non-temporary channel_id. However, currently we do not, so we just
8899                                 // move forward with it.
8900                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8901                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8902                         },
8903                         _ => panic!("Unexpected event"),
8904                 }
8905         }
8906
8907         // Move the first channel through the funding flow...
8908         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8909
8910         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8911         check_added_monitors!(nodes[0], 0);
8912
8913         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8914         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8915         {
8916                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8917                 assert_eq!(added_monitors.len(), 1);
8918                 assert_eq!(added_monitors[0].0, funding_output);
8919                 added_monitors.clear();
8920         }
8921         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8922
8923         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8924
8925         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8926         let channel_id = funding_outpoint.to_channel_id();
8927
8928         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8929         // temporary one).
8930
8931         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8932         // Technically this is allowed by the spec, but we don't support it and there's little reason
8933         // to. Still, it shouldn't cause any other issues.
8934         open_chan_msg.temporary_channel_id = channel_id;
8935         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8936         {
8937                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8938                 assert_eq!(events.len(), 1);
8939                 match events[0] {
8940                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8941                                 // Technically, at this point, nodes[1] would be justified in thinking both
8942                                 // channels are closed, but currently we do not, so we just move forward with it.
8943                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8944                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8945                         },
8946                         _ => panic!("Unexpected event"),
8947                 }
8948         }
8949
8950         // Now try to create a second channel which has a duplicate funding output.
8951         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8952         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8953         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8954         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()));
8955         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8956
8957         let (_, funding_created) = {
8958                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8959                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8960                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8961                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8962                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8963                 // channelmanager in a possibly nonsense state instead).
8964                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
8965                         ChannelPhase::UnfundedOutboundV1(chan) => {
8966                                 let logger = test_utils::TestLogger::new();
8967                                 chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8968                         },
8969                         _ => panic!("Unexpected ChannelPhase variant"),
8970                 }
8971         };
8972         check_added_monitors!(nodes[0], 0);
8973         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8974         // At this point we'll look up if the channel_id is present and immediately fail the channel
8975         // without trying to persist the `ChannelMonitor`.
8976         check_added_monitors!(nodes[1], 0);
8977
8978         // ...still, nodes[1] will reject the duplicate channel.
8979         {
8980                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8981                 assert_eq!(events.len(), 1);
8982                 match events[0] {
8983                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8984                                 // Technically, at this point, nodes[1] would be justified in thinking both
8985                                 // channels are closed, but currently we do not, so we just move forward with it.
8986                                 assert_eq!(msg.channel_id, channel_id);
8987                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8988                         },
8989                         _ => panic!("Unexpected event"),
8990                 }
8991         }
8992
8993         // finally, finish creating the original channel and send a payment over it to make sure
8994         // everything is functional.
8995         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8996         {
8997                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8998                 assert_eq!(added_monitors.len(), 1);
8999                 assert_eq!(added_monitors[0].0, funding_output);
9000                 added_monitors.clear();
9001         }
9002         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9003
9004         let events_4 = nodes[0].node.get_and_clear_pending_events();
9005         assert_eq!(events_4.len(), 0);
9006         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9007         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9008
9009         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9010         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9011         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9012
9013         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9014 }
9015
9016 #[test]
9017 fn test_error_chans_closed() {
9018         // Test that we properly handle error messages, closing appropriate channels.
9019         //
9020         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9021         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9022         // we can test various edge cases around it to ensure we don't regress.
9023         let chanmon_cfgs = create_chanmon_cfgs(3);
9024         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9025         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9026         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9027
9028         // Create some initial channels
9029         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9030         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9031         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9032
9033         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9034         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9035         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9036
9037         // Closing a channel from a different peer has no effect
9038         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9039         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9040
9041         // Closing one channel doesn't impact others
9042         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9043         check_added_monitors!(nodes[0], 1);
9044         check_closed_broadcast!(nodes[0], false);
9045         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9046                 [nodes[1].node.get_our_node_id()], 100000);
9047         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9048         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9049         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);
9050         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);
9051
9052         // A null channel ID should close all channels
9053         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9054         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9055         check_added_monitors!(nodes[0], 2);
9056         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9057                 [nodes[1].node.get_our_node_id(); 2], 100000);
9058         let events = nodes[0].node.get_and_clear_pending_msg_events();
9059         assert_eq!(events.len(), 2);
9060         match events[0] {
9061                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9062                         assert_eq!(msg.contents.flags & 2, 2);
9063                 },
9064                 _ => panic!("Unexpected event"),
9065         }
9066         match events[1] {
9067                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9068                         assert_eq!(msg.contents.flags & 2, 2);
9069                 },
9070                 _ => panic!("Unexpected event"),
9071         }
9072         // Note that at this point users of a standard PeerHandler will end up calling
9073         // peer_disconnected.
9074         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9075         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9076
9077         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9078         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9079         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9080 }
9081
9082 #[test]
9083 fn test_invalid_funding_tx() {
9084         // Test that we properly handle invalid funding transactions sent to us from a peer.
9085         //
9086         // Previously, all other major lightning implementations had failed to properly sanitize
9087         // funding transactions from their counterparties, leading to a multi-implementation critical
9088         // security vulnerability (though we always sanitized properly, we've previously had
9089         // un-released crashes in the sanitization process).
9090         //
9091         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9092         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9093         // gave up on it. We test this here by generating such a transaction.
9094         let chanmon_cfgs = create_chanmon_cfgs(2);
9095         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9096         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9097         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9098
9099         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9100         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()));
9101         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()));
9102
9103         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9104
9105         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9106         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9107         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9108         // its length.
9109         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9110         let wit_program_script: Script = wit_program.into();
9111         for output in tx.output.iter_mut() {
9112                 // Make the confirmed funding transaction have a bogus script_pubkey
9113                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9114         }
9115
9116         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9117         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()));
9118         check_added_monitors!(nodes[1], 1);
9119         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9120
9121         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9122         check_added_monitors!(nodes[0], 1);
9123         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9124
9125         let events_1 = nodes[0].node.get_and_clear_pending_events();
9126         assert_eq!(events_1.len(), 0);
9127
9128         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9129         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9130         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9131
9132         let expected_err = "funding tx had wrong script/value or output index";
9133         confirm_transaction_at(&nodes[1], &tx, 1);
9134         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9135                 [nodes[0].node.get_our_node_id()], 100000);
9136         check_added_monitors!(nodes[1], 1);
9137         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9138         assert_eq!(events_2.len(), 1);
9139         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9140                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9141                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9142                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9143                 } else { panic!(); }
9144         } else { panic!(); }
9145         assert_eq!(nodes[1].node.list_channels().len(), 0);
9146
9147         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9148         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9149         // as its not 32 bytes long.
9150         let mut spend_tx = Transaction {
9151                 version: 2i32, lock_time: PackedLockTime::ZERO,
9152                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9153                         previous_output: BitcoinOutPoint {
9154                                 txid: tx.txid(),
9155                                 vout: idx as u32,
9156                         },
9157                         script_sig: Script::new(),
9158                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9159                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9160                 }).collect(),
9161                 output: vec![TxOut {
9162                         value: 1000,
9163                         script_pubkey: Script::new(),
9164                 }]
9165         };
9166         check_spends!(spend_tx, tx);
9167         mine_transaction(&nodes[1], &spend_tx);
9168 }
9169
9170 #[test]
9171 fn test_coinbase_funding_tx() {
9172         // Miners are able to fund channels directly from coinbase transactions, however
9173         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9174         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9175         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9176         //
9177         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9178         // immediately operational after opening.
9179         let chanmon_cfgs = create_chanmon_cfgs(2);
9180         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9181         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9182         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9183
9184         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9185         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9186
9187         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9188         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9189
9190         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9191
9192         // Create the coinbase funding transaction.
9193         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9194
9195         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9196         check_added_monitors!(nodes[0], 0);
9197         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9198
9199         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9200         check_added_monitors!(nodes[1], 1);
9201         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9202
9203         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9204
9205         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9206         check_added_monitors!(nodes[0], 1);
9207
9208         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9209         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9210
9211         // Starting at height 0, we "confirm" the coinbase at height 1.
9212         confirm_transaction_at(&nodes[0], &tx, 1);
9213         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9214         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9215         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9216         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9217         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9218         connect_blocks(&nodes[0], 1);
9219         // There should now be a `channel_ready` which can be handled.
9220         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()));
9221
9222         confirm_transaction_at(&nodes[1], &tx, 1);
9223         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9224         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9225         connect_blocks(&nodes[1], 1);
9226         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9227         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9228 }
9229
9230 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9231         // In the first version of the chain::Confirm interface, after a refactor was made to not
9232         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9233         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9234         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9235         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9236         // spending transaction until height N+1 (or greater). This was due to the way
9237         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9238         // spending transaction at the height the input transaction was confirmed at, not whether we
9239         // should broadcast a spending transaction at the current height.
9240         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9241         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9242         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9243         // until we learned about an additional block.
9244         //
9245         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9246         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9247         let chanmon_cfgs = create_chanmon_cfgs(3);
9248         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9249         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9250         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9251         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9252
9253         create_announced_chan_between_nodes(&nodes, 0, 1);
9254         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9255         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9256         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9257         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9258
9259         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9260         check_closed_broadcast!(nodes[1], true);
9261         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9262         check_added_monitors!(nodes[1], 1);
9263         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9264         assert_eq!(node_txn.len(), 1);
9265
9266         let conf_height = nodes[1].best_block_info().1;
9267         if !test_height_before_timelock {
9268                 connect_blocks(&nodes[1], 24 * 6);
9269         }
9270         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9271                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9272         if test_height_before_timelock {
9273                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9274                 // generate any events or broadcast any transactions
9275                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9276                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9277         } else {
9278                 // We should broadcast an HTLC transaction spending our funding transaction first
9279                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9280                 assert_eq!(spending_txn.len(), 2);
9281                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9282                 check_spends!(spending_txn[1], node_txn[0]);
9283                 // We should also generate a SpendableOutputs event with the to_self output (as its
9284                 // timelock is up).
9285                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9286                 assert_eq!(descriptor_spend_txn.len(), 1);
9287
9288                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9289                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9290                 // additional block built on top of the current chain.
9291                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9292                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9293                 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 }]);
9294                 check_added_monitors!(nodes[1], 1);
9295
9296                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9297                 assert!(updates.update_add_htlcs.is_empty());
9298                 assert!(updates.update_fulfill_htlcs.is_empty());
9299                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9300                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9301                 assert!(updates.update_fee.is_none());
9302                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9303                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9304                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9305         }
9306 }
9307
9308 #[test]
9309 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9310         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9311         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9312 }
9313
9314 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9315         let chanmon_cfgs = create_chanmon_cfgs(2);
9316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9318         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9319
9320         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9321
9322         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9323                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9324         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9325
9326         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9327
9328         {
9329                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9330                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9331                 check_added_monitors!(nodes[0], 1);
9332                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9333                 assert_eq!(events.len(), 1);
9334                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9335                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9336                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9337         }
9338         expect_pending_htlcs_forwardable!(nodes[1]);
9339         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9340
9341         {
9342                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9343                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9344                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9345                 check_added_monitors!(nodes[0], 1);
9346                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9347                 assert_eq!(events.len(), 1);
9348                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9349                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9350                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9351                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9352                 // assume the second is a privacy attack (no longer particularly relevant
9353                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9354                 // the first HTLC delivered above.
9355         }
9356
9357         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9358         nodes[1].node.process_pending_htlc_forwards();
9359
9360         if test_for_second_fail_panic {
9361                 // Now we go fail back the first HTLC from the user end.
9362                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9363
9364                 let expected_destinations = vec![
9365                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9366                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9367                 ];
9368                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9369                 nodes[1].node.process_pending_htlc_forwards();
9370
9371                 check_added_monitors!(nodes[1], 1);
9372                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9373                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9374
9375                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9376                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9377                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9378
9379                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9380                 assert_eq!(failure_events.len(), 4);
9381                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9382                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9383                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9384                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9385         } else {
9386                 // Let the second HTLC fail and claim the first
9387                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9388                 nodes[1].node.process_pending_htlc_forwards();
9389
9390                 check_added_monitors!(nodes[1], 1);
9391                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9392                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9393                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9394
9395                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9396
9397                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9398         }
9399 }
9400
9401 #[test]
9402 fn test_dup_htlc_second_fail_panic() {
9403         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9404         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9405         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9406         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9407         do_test_dup_htlc_second_rejected(true);
9408 }
9409
9410 #[test]
9411 fn test_dup_htlc_second_rejected() {
9412         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9413         // simply reject the second HTLC but are still able to claim the first HTLC.
9414         do_test_dup_htlc_second_rejected(false);
9415 }
9416
9417 #[test]
9418 fn test_inconsistent_mpp_params() {
9419         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9420         // such HTLC and allow the second to stay.
9421         let chanmon_cfgs = create_chanmon_cfgs(4);
9422         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9423         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9424         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9425
9426         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9427         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9428         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9429         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9430
9431         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9432                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9433         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9434         assert_eq!(route.paths.len(), 2);
9435         route.paths.sort_by(|path_a, _| {
9436                 // Sort the path so that the path through nodes[1] comes first
9437                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9438                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9439         });
9440
9441         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9442
9443         let cur_height = nodes[0].best_block_info().1;
9444         let payment_id = PaymentId([42; 32]);
9445
9446         let session_privs = {
9447                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9448                 // ultimately have, just not right away.
9449                 let mut dup_route = route.clone();
9450                 dup_route.paths.push(route.paths[1].clone());
9451                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9452                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9453         };
9454         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9455                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9456                 &None, session_privs[0]).unwrap();
9457         check_added_monitors!(nodes[0], 1);
9458
9459         {
9460                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9461                 assert_eq!(events.len(), 1);
9462                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9463         }
9464         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9465
9466         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9467                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9468         check_added_monitors!(nodes[0], 1);
9469
9470         {
9471                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9472                 assert_eq!(events.len(), 1);
9473                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9474
9475                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9476                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9477
9478                 expect_pending_htlcs_forwardable!(nodes[2]);
9479                 check_added_monitors!(nodes[2], 1);
9480
9481                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9482                 assert_eq!(events.len(), 1);
9483                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9484
9485                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9486                 check_added_monitors!(nodes[3], 0);
9487                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9488
9489                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9490                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9491                 // post-payment_secrets) and fail back the new HTLC.
9492         }
9493         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9494         nodes[3].node.process_pending_htlc_forwards();
9495         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9496         nodes[3].node.process_pending_htlc_forwards();
9497
9498         check_added_monitors!(nodes[3], 1);
9499
9500         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9501         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9502         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9503
9504         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 }]);
9505         check_added_monitors!(nodes[2], 1);
9506
9507         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9508         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9509         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9510
9511         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9512
9513         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9514                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9515                 &None, session_privs[2]).unwrap();
9516         check_added_monitors!(nodes[0], 1);
9517
9518         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9519         assert_eq!(events.len(), 1);
9520         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9521
9522         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9523         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9524 }
9525
9526 #[test]
9527 fn test_double_partial_claim() {
9528         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9529         // time out, the sender resends only some of the MPP parts, then the user processes the
9530         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9531         // amount.
9532         let chanmon_cfgs = create_chanmon_cfgs(4);
9533         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9534         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9535         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9536
9537         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9538         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9539         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9540         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9541
9542         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9543         assert_eq!(route.paths.len(), 2);
9544         route.paths.sort_by(|path_a, _| {
9545                 // Sort the path so that the path through nodes[1] comes first
9546                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9547                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9548         });
9549
9550         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9551         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9552         // amount of time to respond to.
9553
9554         // Connect some blocks to time out the payment
9555         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9556         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9557
9558         let failed_destinations = vec![
9559                 HTLCDestination::FailedPayment { payment_hash },
9560                 HTLCDestination::FailedPayment { payment_hash },
9561         ];
9562         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9563
9564         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9565
9566         // nodes[1] now retries one of the two paths...
9567         nodes[0].node.send_payment_with_route(&route, payment_hash,
9568                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9569         check_added_monitors!(nodes[0], 2);
9570
9571         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9572         assert_eq!(events.len(), 2);
9573         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9574         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9575
9576         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9577         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9578         nodes[3].node.claim_funds(payment_preimage);
9579         check_added_monitors!(nodes[3], 0);
9580         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9581 }
9582
9583 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9584 #[derive(Clone, Copy, PartialEq)]
9585 enum ExposureEvent {
9586         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9587         AtHTLCForward,
9588         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9589         AtHTLCReception,
9590         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9591         AtUpdateFeeOutbound,
9592 }
9593
9594 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9595         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9596         // policy.
9597         //
9598         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9599         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9600         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9601         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9602         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9603         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9604         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9605         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9606
9607         let chanmon_cfgs = create_chanmon_cfgs(2);
9608         let mut config = test_default_channel_config();
9609         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9610                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9611                 // to get roughly the same initial value as the default setting when this test was
9612                 // originally written.
9613                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9614         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9617         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9618
9619         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9620         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9621         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9622         open_channel.max_accepted_htlcs = 60;
9623         if on_holder_tx {
9624                 open_channel.dust_limit_satoshis = 546;
9625         }
9626         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9627         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9628         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9629
9630         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9631
9632         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9633
9634         if on_holder_tx {
9635                 let mut node_0_per_peer_lock;
9636                 let mut node_0_peer_state_lock;
9637                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9638                         ChannelPhase::UnfundedOutboundV1(chan) => {
9639                                 chan.context.holder_dust_limit_satoshis = 546;
9640                         },
9641                         _ => panic!("Unexpected ChannelPhase variant"),
9642                 }
9643         }
9644
9645         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9646         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()));
9647         check_added_monitors!(nodes[1], 1);
9648         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9649
9650         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()));
9651         check_added_monitors!(nodes[0], 1);
9652         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9653
9654         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9655         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9656         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9657
9658         // Fetch a route in advance as we will be unable to once we're unable to send.
9659         let (mut route, payment_hash, _, payment_secret) =
9660                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9661
9662         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9663                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9664                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9665                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9666                 (chan.context().get_dust_buffer_feerate(None) as u64,
9667                 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9668         };
9669         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;
9670         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9671
9672         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;
9673         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9674
9675         let dust_htlc_on_counterparty_tx: u64 = 4;
9676         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9677
9678         if on_holder_tx {
9679                 if dust_outbound_balance {
9680                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9681                         // Outbound dust balance: 4372 sats
9682                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9683                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9684                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9685                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9686                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9687                         }
9688                 } else {
9689                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9690                         // Inbound dust balance: 4372 sats
9691                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9692                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9693                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9694                         }
9695                 }
9696         } else {
9697                 if dust_outbound_balance {
9698                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9699                         // Outbound dust balance: 5000 sats
9700                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9701                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9702                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9703                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9704                         }
9705                 } else {
9706                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9707                         // Inbound dust balance: 5000 sats
9708                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9709                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9710                         }
9711                 }
9712         }
9713
9714         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9715                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9716                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9717                 // With default dust exposure: 5000 sats
9718                 if on_holder_tx {
9719                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9720                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9721                                 ), true, APIError::ChannelUnavailable { .. }, {});
9722                 } else {
9723                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9724                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9725                                 ), true, APIError::ChannelUnavailable { .. }, {});
9726                 }
9727         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9728                 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 });
9729                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9730                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9731                 check_added_monitors!(nodes[1], 1);
9732                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9733                 assert_eq!(events.len(), 1);
9734                 let payment_event = SendEvent::from_event(events.remove(0));
9735                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9736                 // With default dust exposure: 5000 sats
9737                 if on_holder_tx {
9738                         // Outbound dust balance: 6399 sats
9739                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9740                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9741                         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);
9742                 } else {
9743                         // Outbound dust balance: 5200 sats
9744                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9745                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9746                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9747                                         max_dust_htlc_exposure_msat), 1);
9748                 }
9749         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9750                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9751                 // For the multiplier dust exposure limit, since it scales with feerate,
9752                 // we need to add a lot of HTLCs that will become dust at the new feerate
9753                 // to cross the threshold.
9754                 for _ in 0..20 {
9755                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9756                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9757                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9758                 }
9759                 {
9760                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9761                         *feerate_lock = *feerate_lock * 10;
9762                 }
9763                 nodes[0].node.timer_tick_occurred();
9764                 check_added_monitors!(nodes[0], 1);
9765                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9766         }
9767
9768         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9769         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9770         added_monitors.clear();
9771 }
9772
9773 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9774         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9775         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9776         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9777         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9778         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9779         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9780         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9781         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9782         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9783         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9784         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9785         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9786 }
9787
9788 #[test]
9789 fn test_max_dust_htlc_exposure() {
9790         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9791         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9792 }
9793
9794 #[test]
9795 fn test_non_final_funding_tx() {
9796         let chanmon_cfgs = create_chanmon_cfgs(2);
9797         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9798         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9799         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9800
9801         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9802         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9803         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9804         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9805         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9806
9807         let best_height = nodes[0].node.best_block.read().unwrap().height();
9808
9809         let chan_id = *nodes[0].network_chan_count.borrow();
9810         let events = nodes[0].node.get_and_clear_pending_events();
9811         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9812         assert_eq!(events.len(), 1);
9813         let mut tx = match events[0] {
9814                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9815                         // Timelock the transaction _beyond_ the best client height + 1.
9816                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9817                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9818                         }]}
9819                 },
9820                 _ => panic!("Unexpected event"),
9821         };
9822         // Transaction should fail as it's evaluated as non-final for propagation.
9823         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9824                 Err(APIError::APIMisuseError { err }) => {
9825                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9826                 },
9827                 _ => panic!()
9828         }
9829
9830         // However, transaction should be accepted if it's in a +1 headroom from best block.
9831         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9832         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9833         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9834 }
9835
9836 #[test]
9837 fn accept_busted_but_better_fee() {
9838         // If a peer sends us a fee update that is too low, but higher than our previous channel
9839         // feerate, we should accept it. In the future we may want to consider closing the channel
9840         // later, but for now we only accept the update.
9841         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9842         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9843         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9844         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9845
9846         create_chan_between_nodes(&nodes[0], &nodes[1]);
9847
9848         // Set nodes[1] to expect 5,000 sat/kW.
9849         {
9850                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9851                 *feerate_lock = 5000;
9852         }
9853
9854         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9855         {
9856                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9857                 *feerate_lock = 1000;
9858         }
9859         nodes[0].node.timer_tick_occurred();
9860         check_added_monitors!(nodes[0], 1);
9861
9862         let events = nodes[0].node.get_and_clear_pending_msg_events();
9863         assert_eq!(events.len(), 1);
9864         match events[0] {
9865                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9866                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9867                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9868                 },
9869                 _ => panic!("Unexpected event"),
9870         };
9871
9872         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9873         // it.
9874         {
9875                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9876                 *feerate_lock = 2000;
9877         }
9878         nodes[0].node.timer_tick_occurred();
9879         check_added_monitors!(nodes[0], 1);
9880
9881         let events = nodes[0].node.get_and_clear_pending_msg_events();
9882         assert_eq!(events.len(), 1);
9883         match events[0] {
9884                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9885                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9886                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9887                 },
9888                 _ => panic!("Unexpected event"),
9889         };
9890
9891         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9892         // channel.
9893         {
9894                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9895                 *feerate_lock = 1000;
9896         }
9897         nodes[0].node.timer_tick_occurred();
9898         check_added_monitors!(nodes[0], 1);
9899
9900         let events = nodes[0].node.get_and_clear_pending_msg_events();
9901         assert_eq!(events.len(), 1);
9902         match events[0] {
9903                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9904                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9905                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9906                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9907                                 [nodes[0].node.get_our_node_id()], 100000);
9908                         check_closed_broadcast!(nodes[1], true);
9909                         check_added_monitors!(nodes[1], 1);
9910                 },
9911                 _ => panic!("Unexpected event"),
9912         };
9913 }
9914
9915 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9916         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9917         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9918         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9919         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9920         let min_final_cltv_expiry_delta = 120;
9921         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9922                 min_final_cltv_expiry_delta - 2 };
9923         let recv_value = 100_000;
9924
9925         create_chan_between_nodes(&nodes[0], &nodes[1]);
9926
9927         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9928         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9929                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9930                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9931                 (payment_hash, payment_preimage, payment_secret)
9932         } else {
9933                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9934                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9935         };
9936         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9937         nodes[0].node.send_payment_with_route(&route, payment_hash,
9938                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9939         check_added_monitors!(nodes[0], 1);
9940         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9941         assert_eq!(events.len(), 1);
9942         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9943         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9944         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9945         expect_pending_htlcs_forwardable!(nodes[1]);
9946
9947         if valid_delta {
9948                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9949                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9950
9951                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9952         } else {
9953                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9954
9955                 check_added_monitors!(nodes[1], 1);
9956
9957                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9958                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9959                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9960
9961                 expect_payment_failed!(nodes[0], payment_hash, true);
9962         }
9963 }
9964
9965 #[test]
9966 fn test_payment_with_custom_min_cltv_expiry_delta() {
9967         do_payment_with_custom_min_final_cltv_expiry(false, false);
9968         do_payment_with_custom_min_final_cltv_expiry(false, true);
9969         do_payment_with_custom_min_final_cltv_expiry(true, false);
9970         do_payment_with_custom_min_final_cltv_expiry(true, true);
9971 }
9972
9973 #[test]
9974 fn test_disconnects_peer_awaiting_response_ticks() {
9975         // Tests that nodes which are awaiting on a response critical for channel responsiveness
9976         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9977         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9978         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9979         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9980         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9981
9982         // Asserts a disconnect event is queued to the user.
9983         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9984                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9985                         if let MessageSendEvent::HandleError { action, .. } = event {
9986                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9987                                         Some(())
9988                                 } else {
9989                                         None
9990                                 }
9991                         } else {
9992                                 None
9993                         }
9994                 );
9995                 assert_eq!(disconnect_event.is_some(), should_disconnect);
9996         };
9997
9998         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9999         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10000         let check_disconnect = |node: &Node| {
10001                 // No disconnect without any timer ticks.
10002                 check_disconnect_event(node, false);
10003
10004                 // No disconnect with 1 timer tick less than required.
10005                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10006                         node.node.timer_tick_occurred();
10007                         check_disconnect_event(node, false);
10008                 }
10009
10010                 // Disconnect after reaching the required ticks.
10011                 node.node.timer_tick_occurred();
10012                 check_disconnect_event(node, true);
10013
10014                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10015                 node.node.timer_tick_occurred();
10016                 check_disconnect_event(node, true);
10017         };
10018
10019         create_chan_between_nodes(&nodes[0], &nodes[1]);
10020
10021         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10022         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10023         nodes[0].node.timer_tick_occurred();
10024         check_added_monitors!(&nodes[0], 1);
10025         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10026         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10027         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10028         check_added_monitors!(&nodes[1], 1);
10029
10030         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10031         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10032         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10033         check_added_monitors!(&nodes[0], 1);
10034         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10035         check_added_monitors(&nodes[0], 1);
10036
10037         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10038         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10039         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10040         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10041         check_disconnect(&nodes[1]);
10042
10043         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10044         //
10045         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10046         // final `RevokeAndACK` to Bob to complete it.
10047         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10048         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10049         let bob_init = msgs::Init {
10050                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10051         };
10052         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10053         let alice_init = msgs::Init {
10054                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10055         };
10056         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10057
10058         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10059         // received Bob's yet, so she should disconnect him after reaching
10060         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10061         let alice_channel_reestablish = get_event_msg!(
10062                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10063         );
10064         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10065         check_disconnect(&nodes[0]);
10066
10067         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10068         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10069                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10070                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10071                         Some(msg.clone())
10072                 } else {
10073                         None
10074                 }
10075         ).unwrap();
10076         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10077
10078         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10079         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10080                 nodes[0].node.timer_tick_occurred();
10081                 check_disconnect_event(&nodes[0], false);
10082         }
10083
10084         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10085         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10086         check_disconnect(&nodes[1]);
10087
10088         // Finally, have Bob process the last message.
10089         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10090         check_added_monitors(&nodes[1], 1);
10091
10092         // At this point, neither node should attempt to disconnect each other, since they aren't
10093         // waiting on any messages.
10094         for node in &nodes {
10095                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10096                         node.node.timer_tick_occurred();
10097                         check_disconnect_event(node, false);
10098                 }
10099         }
10100 }
10101
10102 #[test]
10103 fn test_remove_expired_outbound_unfunded_channels() {
10104         let chanmon_cfgs = create_chanmon_cfgs(2);
10105         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10106         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10107         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10108
10109         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10110         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10111         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10112         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10113         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10114
10115         let events = nodes[0].node.get_and_clear_pending_events();
10116         assert_eq!(events.len(), 1);
10117         match events[0] {
10118                 Event::FundingGenerationReady { .. } => (),
10119                 _ => panic!("Unexpected event"),
10120         };
10121
10122         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10123         let check_outbound_channel_existence = |should_exist: bool| {
10124                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10125                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10126                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10127         };
10128
10129         // Channel should exist without any timer ticks.
10130         check_outbound_channel_existence(true);
10131
10132         // Channel should exist with 1 timer tick less than required.
10133         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10134                 nodes[0].node.timer_tick_occurred();
10135                 check_outbound_channel_existence(true)
10136         }
10137
10138         // Remove channel after reaching the required ticks.
10139         nodes[0].node.timer_tick_occurred();
10140         check_outbound_channel_existence(false);
10141
10142         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10143         assert_eq!(msg_events.len(), 1);
10144         match msg_events[0] {
10145                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10146                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10147                 },
10148                 _ => panic!("Unexpected event"),
10149         }
10150         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10151 }
10152
10153 #[test]
10154 fn test_remove_expired_inbound_unfunded_channels() {
10155         let chanmon_cfgs = create_chanmon_cfgs(2);
10156         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10157         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10158         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10159
10160         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10161         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10162         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10163         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10164         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10165
10166         let events = nodes[0].node.get_and_clear_pending_events();
10167         assert_eq!(events.len(), 1);
10168         match events[0] {
10169                 Event::FundingGenerationReady { .. } => (),
10170                 _ => panic!("Unexpected event"),
10171         };
10172
10173         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10174         let check_inbound_channel_existence = |should_exist: bool| {
10175                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10176                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10177                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10178         };
10179
10180         // Channel should exist without any timer ticks.
10181         check_inbound_channel_existence(true);
10182
10183         // Channel should exist with 1 timer tick less than required.
10184         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10185                 nodes[1].node.timer_tick_occurred();
10186                 check_inbound_channel_existence(true)
10187         }
10188
10189         // Remove channel after reaching the required ticks.
10190         nodes[1].node.timer_tick_occurred();
10191         check_inbound_channel_existence(false);
10192
10193         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10194         assert_eq!(msg_events.len(), 1);
10195         match msg_events[0] {
10196                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10197                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10198                 },
10199                 _ => panic!("Unexpected event"),
10200         }
10201         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10202 }
10203
10204 fn do_test_multi_post_event_actions(do_reload: bool) {
10205         // Tests handling multiple post-Event actions at once.
10206         // There is specific code in ChannelManager to handle channels where multiple post-Event
10207         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10208         //
10209         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10210         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10211         // - one from an RAA and one from an inbound commitment_signed.
10212         let chanmon_cfgs = create_chanmon_cfgs(3);
10213         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10214         let (persister, chain_monitor);
10215         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10216         let nodes_0_deserialized;
10217         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10218
10219         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10220         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10221
10222         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10223         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10224
10225         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10226         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10227
10228         nodes[1].node.claim_funds(our_payment_preimage);
10229         check_added_monitors!(nodes[1], 1);
10230         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10231
10232         nodes[2].node.claim_funds(payment_preimage_2);
10233         check_added_monitors!(nodes[2], 1);
10234         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10235
10236         for dest in &[1, 2] {
10237                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10238                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10239                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10240                 check_added_monitors(&nodes[0], 0);
10241         }
10242
10243         let (route, payment_hash_3, _, payment_secret_3) =
10244                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10245         let payment_id = PaymentId(payment_hash_3.0);
10246         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10247                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10248         check_added_monitors(&nodes[1], 1);
10249
10250         let send_event = SendEvent::from_node(&nodes[1]);
10251         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10252         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10253         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10254
10255         if do_reload {
10256                 let nodes_0_serialized = nodes[0].node.encode();
10257                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10258                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10259                 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);
10260
10261                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10262                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10263
10264                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10265                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10266         }
10267
10268         let events = nodes[0].node.get_and_clear_pending_events();
10269         assert_eq!(events.len(), 4);
10270         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10271                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10272         } else { panic!(); }
10273         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10274                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10275         } else { panic!(); }
10276         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10277         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10278
10279         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10280         // completion, we'll respond to nodes[1] with an RAA + CS.
10281         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10282         check_added_monitors(&nodes[0], 3);
10283 }
10284
10285 #[test]
10286 fn test_multi_post_event_actions() {
10287         do_test_multi_post_event_actions(true);
10288         do_test_multi_post_event_actions(false);
10289 }