Consistently clean up when failing in `internal_funding_created`
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::locktime::absolute::LockTime;
42 use bitcoin::blockdata::script::{Builder, ScriptBuf};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{Sequence, Transaction, TxIn, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
51
52 use regex;
53
54 use crate::io;
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex, RwLock};
61
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
64
65 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
66
67 #[test]
68 fn test_insane_channel_opens() {
69         // Stand up a network of 2 nodes
70         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
71         let mut cfg = UserConfig::default();
72         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
73         let chanmon_cfgs = create_chanmon_cfgs(2);
74         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
75         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
76         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
77
78         // Instantiate channel parameters where we push the maximum msats given our
79         // funding satoshis
80         let channel_value_sat = 31337; // same as funding satoshis
81         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
82         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
83
84         // Have node0 initiate a channel to node1 with aforementioned parameters
85         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
86
87         // Extract the channel open message from node0 to node1
88         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
89
90         // Test helper that asserts we get the correct error string given a mutator
91         // that supposedly makes the channel open message insane
92         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
93                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
94                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
95                 assert_eq!(msg_events.len(), 1);
96                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
97                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
98                         match action {
99                                 &ErrorAction::SendErrorMessage { .. } => {
100                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
101                                 },
102                                 _ => panic!("unexpected event!"),
103                         }
104                 } else { assert!(false); }
105         };
106
107         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
108
109         // Test all mutations that would make the channel open message insane
110         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
111         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
112
113         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
114
115         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
116
117         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
118
119         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 });
120
121         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 });
122
123         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
124
125         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 }
127
128 #[test]
129 fn test_funding_exceeds_no_wumbo_limit() {
130         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
131         // them.
132         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
133         let chanmon_cfgs = create_chanmon_cfgs(2);
134         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
135         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
136         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
137         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
138
139         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
140                 Err(APIError::APIMisuseError { err }) => {
141                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
142                 },
143                 _ => panic!()
144         }
145 }
146
147 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
148         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
149         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
150         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
151         // in normal testing, we test it explicitly here.
152         let chanmon_cfgs = create_chanmon_cfgs(2);
153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
155         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
156         let default_config = UserConfig::default();
157
158         // Have node0 initiate a channel to node1 with aforementioned parameters
159         let mut push_amt = 100_000_000;
160         let feerate_per_kw = 253;
161         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
162         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
163         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
164
165         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None, None).unwrap();
166         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
167         if !send_from_initiator {
168                 open_channel_message.channel_reserve_satoshis = 0;
169                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
170         }
171         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
172
173         // Extract the channel accept message from node1 to node0
174         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
175         if send_from_initiator {
176                 accept_channel_message.channel_reserve_satoshis = 0;
177                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
178         }
179         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
180         {
181                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
182                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
183                 let mut sender_node_per_peer_lock;
184                 let mut sender_node_peer_state_lock;
185
186                 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
187                 match channel_phase {
188                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
189                                 let chan_context = channel_phase.context_mut();
190                                 chan_context.holder_selected_channel_reserve_satoshis = 0;
191                                 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
192                         },
193                         ChannelPhase::Funded(_) => assert!(false),
194                 }
195         }
196
197         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
198         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
199         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
200
201         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
202         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
203         if send_from_initiator {
204                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
205                         // Note that for outbound channels we have to consider the commitment tx fee and the
206                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
207                         // well as an additional HTLC.
208                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
209         } else {
210                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
211         }
212 }
213
214 #[test]
215 fn test_counterparty_no_reserve() {
216         do_test_counterparty_no_reserve(true);
217         do_test_counterparty_no_reserve(false);
218 }
219
220 #[test]
221 fn test_async_inbound_update_fee() {
222         let chanmon_cfgs = create_chanmon_cfgs(2);
223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
225         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
226         create_announced_chan_between_nodes(&nodes, 0, 1);
227
228         // balancing
229         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
230
231         // A                                        B
232         // update_fee                            ->
233         // send (1) commitment_signed            -.
234         //                                       <- update_add_htlc/commitment_signed
235         // send (2) RAA (awaiting remote revoke) -.
236         // (1) commitment_signed is delivered    ->
237         //                                       .- send (3) RAA (awaiting remote revoke)
238         // (2) RAA is delivered                  ->
239         //                                       .- send (4) commitment_signed
240         //                                       <- (3) RAA is delivered
241         // send (5) commitment_signed            -.
242         //                                       <- (4) commitment_signed is delivered
243         // send (6) RAA                          -.
244         // (5) commitment_signed is delivered    ->
245         //                                       <- RAA
246         // (6) RAA is delivered                  ->
247
248         // First nodes[0] generates an update_fee
249         {
250                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
251                 *feerate_lock += 20;
252         }
253         nodes[0].node.timer_tick_occurred();
254         check_added_monitors!(nodes[0], 1);
255
256         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
257         assert_eq!(events_0.len(), 1);
258         let (update_msg, commitment_signed) = match events_0[0] { // (1)
259                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
260                         (update_fee.as_ref(), commitment_signed)
261                 },
262                 _ => panic!("Unexpected event"),
263         };
264
265         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
266
267         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
268         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
269         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
270                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
271         check_added_monitors!(nodes[1], 1);
272
273         let payment_event = {
274                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275                 assert_eq!(events_1.len(), 1);
276                 SendEvent::from_event(events_1.remove(0))
277         };
278         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279         assert_eq!(payment_event.msgs.len(), 1);
280
281         // ...now when the messages get delivered everyone should be happy
282         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286         check_added_monitors!(nodes[0], 1);
287
288         // deliver(1), generate (3):
289         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
290         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
291         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
292         check_added_monitors!(nodes[1], 1);
293
294         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
295         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
296         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
298         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
299         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
300         assert!(bs_update.update_fee.is_none()); // (4)
301         check_added_monitors!(nodes[1], 1);
302
303         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
304         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
305         assert!(as_update.update_add_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
307         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
308         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
309         assert!(as_update.update_fee.is_none()); // (5)
310         check_added_monitors!(nodes[0], 1);
311
312         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
313         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
314         // only (6) so get_event_msg's assert(len == 1) passes
315         check_added_monitors!(nodes[0], 1);
316
317         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
318         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
319         check_added_monitors!(nodes[1], 1);
320
321         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
322         check_added_monitors!(nodes[0], 1);
323
324         let events_2 = nodes[0].node.get_and_clear_pending_events();
325         assert_eq!(events_2.len(), 1);
326         match events_2[0] {
327                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
328                 _ => panic!("Unexpected event"),
329         }
330
331         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
332         check_added_monitors!(nodes[1], 1);
333 }
334
335 #[test]
336 fn test_update_fee_unordered_raa() {
337         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
338         // crash in an earlier version of the update_fee patch)
339         let chanmon_cfgs = create_chanmon_cfgs(2);
340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
342         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
343         create_announced_chan_between_nodes(&nodes, 0, 1);
344
345         // balancing
346         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
347
348         // First nodes[0] generates an update_fee
349         {
350                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
351                 *feerate_lock += 20;
352         }
353         nodes[0].node.timer_tick_occurred();
354         check_added_monitors!(nodes[0], 1);
355
356         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
357         assert_eq!(events_0.len(), 1);
358         let update_msg = match events_0[0] { // (1)
359                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
360                         update_fee.as_ref()
361                 },
362                 _ => panic!("Unexpected event"),
363         };
364
365         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
366
367         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
368         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
369         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
370                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
371         check_added_monitors!(nodes[1], 1);
372
373         let payment_event = {
374                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
375                 assert_eq!(events_1.len(), 1);
376                 SendEvent::from_event(events_1.remove(0))
377         };
378         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
379         assert_eq!(payment_event.msgs.len(), 1);
380
381         // ...now when the messages get delivered everyone should be happy
382         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
383         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
384         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
385         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
386         check_added_monitors!(nodes[0], 1);
387
388         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
389         check_added_monitors!(nodes[1], 1);
390
391         // We can't continue, sadly, because our (1) now has a bogus signature
392 }
393
394 #[test]
395 fn test_multi_flight_update_fee() {
396         let chanmon_cfgs = create_chanmon_cfgs(2);
397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
399         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
400         create_announced_chan_between_nodes(&nodes, 0, 1);
401
402         // A                                        B
403         // update_fee/commitment_signed          ->
404         //                                       .- send (1) RAA and (2) commitment_signed
405         // update_fee (never committed)          ->
406         // (3) update_fee                        ->
407         // We have to manually generate the above update_fee, it is allowed by the protocol but we
408         // don't track which updates correspond to which revoke_and_ack responses so we're in
409         // AwaitingRAA mode and will not generate the update_fee yet.
410         //                                       <- (1) RAA delivered
411         // (3) is generated and send (4) CS      -.
412         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
413         // know the per_commitment_point to use for it.
414         //                                       <- (2) commitment_signed delivered
415         // revoke_and_ack                        ->
416         //                                          B should send no response here
417         // (4) commitment_signed delivered       ->
418         //                                       <- RAA/commitment_signed delivered
419         // revoke_and_ack                        ->
420
421         // First nodes[0] generates an update_fee
422         let initial_feerate;
423         {
424                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
425                 initial_feerate = *feerate_lock;
426                 *feerate_lock = initial_feerate + 20;
427         }
428         nodes[0].node.timer_tick_occurred();
429         check_added_monitors!(nodes[0], 1);
430
431         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
432         assert_eq!(events_0.len(), 1);
433         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
434                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
435                         (update_fee.as_ref().unwrap(), commitment_signed)
436                 },
437                 _ => panic!("Unexpected event"),
438         };
439
440         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
441         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
442         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
443         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
444         check_added_monitors!(nodes[1], 1);
445
446         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
447         // transaction:
448         {
449                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
450                 *feerate_lock = initial_feerate + 40;
451         }
452         nodes[0].node.timer_tick_occurred();
453         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
454         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
455
456         // Create the (3) update_fee message that nodes[0] will generate before it does...
457         let mut update_msg_2 = msgs::UpdateFee {
458                 channel_id: update_msg_1.channel_id.clone(),
459                 feerate_per_kw: (initial_feerate + 30) as u32,
460         };
461
462         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
463
464         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
465         // Deliver (3)
466         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
467
468         // Deliver (1), generating (3) and (4)
469         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
470         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
471         check_added_monitors!(nodes[0], 1);
472         assert!(as_second_update.update_add_htlcs.is_empty());
473         assert!(as_second_update.update_fulfill_htlcs.is_empty());
474         assert!(as_second_update.update_fail_htlcs.is_empty());
475         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
476         // Check that the update_fee newly generated matches what we delivered:
477         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
478         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
479
480         // Deliver (2) commitment_signed
481         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
482         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
483         check_added_monitors!(nodes[0], 1);
484         // No commitment_signed so get_event_msg's assert(len == 1) passes
485
486         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
487         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
488         check_added_monitors!(nodes[1], 1);
489
490         // Delever (4)
491         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
492         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
493         check_added_monitors!(nodes[1], 1);
494
495         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
496         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
497         check_added_monitors!(nodes[0], 1);
498
499         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
500         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
501         // No commitment_signed so get_event_msg's assert(len == 1) passes
502         check_added_monitors!(nodes[0], 1);
503
504         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
505         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
506         check_added_monitors!(nodes[1], 1);
507 }
508
509 fn do_test_sanity_on_in_flight_opens(steps: u8) {
510         // Previously, we had issues deserializing channels when we hadn't connected the first block
511         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
512         // serialization round-trips and simply do steps towards opening a channel and then drop the
513         // Node objects.
514
515         let chanmon_cfgs = create_chanmon_cfgs(2);
516         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
517         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
518         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
519
520         if steps & 0b1000_0000 != 0{
521                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
522                 connect_block(&nodes[0], &block);
523                 connect_block(&nodes[1], &block);
524         }
525
526         if steps & 0x0f == 0 { return; }
527         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
528         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
529
530         if steps & 0x0f == 1 { return; }
531         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
532         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
533
534         if steps & 0x0f == 2 { return; }
535         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
536
537         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
538
539         if steps & 0x0f == 3 { return; }
540         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
541         check_added_monitors!(nodes[0], 0);
542         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
543
544         if steps & 0x0f == 4 { return; }
545         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
546         {
547                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
548                 assert_eq!(added_monitors.len(), 1);
549                 assert_eq!(added_monitors[0].0, funding_output);
550                 added_monitors.clear();
551         }
552         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
553
554         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
555
556         if steps & 0x0f == 5 { return; }
557         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
558         {
559                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
560                 assert_eq!(added_monitors.len(), 1);
561                 assert_eq!(added_monitors[0].0, funding_output);
562                 added_monitors.clear();
563         }
564
565         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
566         let events_4 = nodes[0].node.get_and_clear_pending_events();
567         assert_eq!(events_4.len(), 0);
568
569         if steps & 0x0f == 6 { return; }
570         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
571
572         if steps & 0x0f == 7 { return; }
573         confirm_transaction_at(&nodes[0], &tx, 2);
574         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
575         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
576         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
577 }
578
579 #[test]
580 fn test_sanity_on_in_flight_opens() {
581         do_test_sanity_on_in_flight_opens(0);
582         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(1);
584         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(2);
586         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(3);
588         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(4);
590         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
591         do_test_sanity_on_in_flight_opens(5);
592         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
593         do_test_sanity_on_in_flight_opens(6);
594         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
595         do_test_sanity_on_in_flight_opens(7);
596         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
597         do_test_sanity_on_in_flight_opens(8);
598         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
599 }
600
601 #[test]
602 fn test_update_fee_vanilla() {
603         let chanmon_cfgs = create_chanmon_cfgs(2);
604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
607         create_announced_chan_between_nodes(&nodes, 0, 1);
608
609         {
610                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
611                 *feerate_lock += 25;
612         }
613         nodes[0].node.timer_tick_occurred();
614         check_added_monitors!(nodes[0], 1);
615
616         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
617         assert_eq!(events_0.len(), 1);
618         let (update_msg, commitment_signed) = match events_0[0] {
619                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
620                         (update_fee.as_ref(), commitment_signed)
621                 },
622                 _ => panic!("Unexpected event"),
623         };
624         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
625
626         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
627         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
628         check_added_monitors!(nodes[1], 1);
629
630         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
631         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
632         check_added_monitors!(nodes[0], 1);
633
634         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
635         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
636         // No commitment_signed so get_event_msg's assert(len == 1) passes
637         check_added_monitors!(nodes[0], 1);
638
639         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
640         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
641         check_added_monitors!(nodes[1], 1);
642 }
643
644 #[test]
645 fn test_update_fee_that_funder_cannot_afford() {
646         let chanmon_cfgs = create_chanmon_cfgs(2);
647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
649         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
650         let channel_value = 5000;
651         let push_sats = 700;
652         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
653         let channel_id = chan.2;
654         let secp_ctx = Secp256k1::new();
655         let default_config = UserConfig::default();
656         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
657
658         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
659
660         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
661         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
662         // calculate two different feerates here - the expected local limit as well as the expected
663         // remote limit.
664         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(&channel_type_features) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
665         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
666         {
667                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
668                 *feerate_lock = feerate;
669         }
670         nodes[0].node.timer_tick_occurred();
671         check_added_monitors!(nodes[0], 1);
672         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
673
674         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
675
676         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
677
678         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
679         {
680                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
681
682                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
683                 assert_eq!(commitment_tx.output.len(), 2);
684                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
685                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
686                 actual_fee = channel_value - actual_fee;
687                 assert_eq!(total_fee, actual_fee);
688         }
689
690         {
691                 // Increment the feerate by a small constant, accounting for rounding errors
692                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
693                 *feerate_lock += 4;
694         }
695         nodes[0].node.timer_tick_occurred();
696         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
697         check_added_monitors!(nodes[0], 0);
698
699         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
700
701         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
702         // needed to sign the new commitment tx and (2) sign the new commitment tx.
703         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
704                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
705                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
706                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
707                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
708                 ).flatten().unwrap();
709                 let chan_signer = local_chan.get_signer();
710                 let pubkeys = chan_signer.as_ref().pubkeys();
711                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
712                  pubkeys.funding_pubkey)
713         };
714         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
715                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
716                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
717                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
718                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
719                 ).flatten().unwrap();
720                 let chan_signer = remote_chan.get_signer();
721                 let pubkeys = chan_signer.as_ref().pubkeys();
722                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
723                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
724                  pubkeys.funding_pubkey)
725         };
726
727         // Assemble the set of keys we can use for signatures for our commitment_signed message.
728         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
729                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
730
731         let res = {
732                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
733                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
734                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
735                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
736                 ).flatten().unwrap();
737                 let local_chan_signer = local_chan.get_signer();
738                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
739                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
740                         INITIAL_COMMITMENT_NUMBER - 1,
741                         push_sats,
742                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
743                         local_funding, remote_funding,
744                         commit_tx_keys.clone(),
745                         non_buffer_feerate + 4,
746                         &mut htlcs,
747                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
748                 );
749                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
750         };
751
752         let commit_signed_msg = msgs::CommitmentSigned {
753                 channel_id: chan.2,
754                 signature: res.0,
755                 htlc_signatures: res.1,
756                 #[cfg(taproot)]
757                 partial_signature_with_nonce: None,
758         };
759
760         let update_fee = msgs::UpdateFee {
761                 channel_id: chan.2,
762                 feerate_per_kw: non_buffer_feerate + 4,
763         };
764
765         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
766
767         //While producing the commitment_signed response after handling a received update_fee request the
768         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
769         //Should produce and error.
770         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
771         nodes[1].logger.assert_log("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee".to_string(), 1);
772         check_added_monitors!(nodes[1], 1);
773         check_closed_broadcast!(nodes[1], true);
774         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
775                 [nodes[0].node.get_our_node_id()], channel_value);
776 }
777
778 #[test]
779 fn test_update_fee_with_fundee_update_add_htlc() {
780         let chanmon_cfgs = create_chanmon_cfgs(2);
781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
783         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
784         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
785
786         // balancing
787         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
788
789         {
790                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
791                 *feerate_lock += 20;
792         }
793         nodes[0].node.timer_tick_occurred();
794         check_added_monitors!(nodes[0], 1);
795
796         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
797         assert_eq!(events_0.len(), 1);
798         let (update_msg, commitment_signed) = match events_0[0] {
799                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
800                         (update_fee.as_ref(), commitment_signed)
801                 },
802                 _ => panic!("Unexpected event"),
803         };
804         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
805         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
806         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807         check_added_monitors!(nodes[1], 1);
808
809         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
810
811         // nothing happens since node[1] is in AwaitingRemoteRevoke
812         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
813                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
814         {
815                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
816                 assert_eq!(added_monitors.len(), 0);
817                 added_monitors.clear();
818         }
819         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
820         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
821         // node[1] has nothing to do
822
823         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
824         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
825         check_added_monitors!(nodes[0], 1);
826
827         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
828         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
829         // No commitment_signed so get_event_msg's assert(len == 1) passes
830         check_added_monitors!(nodes[0], 1);
831         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
832         check_added_monitors!(nodes[1], 1);
833         // AwaitingRemoteRevoke ends here
834
835         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
837         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
838         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
839         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
840         assert_eq!(commitment_update.update_fee.is_none(), true);
841
842         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
843         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
844         check_added_monitors!(nodes[0], 1);
845         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
846
847         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
848         check_added_monitors!(nodes[1], 1);
849         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
850
851         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
852         check_added_monitors!(nodes[1], 1);
853         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
854         // No commitment_signed so get_event_msg's assert(len == 1) passes
855
856         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
857         check_added_monitors!(nodes[0], 1);
858         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
859
860         expect_pending_htlcs_forwardable!(nodes[0]);
861
862         let events = nodes[0].node.get_and_clear_pending_events();
863         assert_eq!(events.len(), 1);
864         match events[0] {
865                 Event::PaymentClaimable { .. } => { },
866                 _ => panic!("Unexpected event"),
867         };
868
869         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
870
871         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
872         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
873         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
874         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
875         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
876 }
877
878 #[test]
879 fn test_update_fee() {
880         let chanmon_cfgs = create_chanmon_cfgs(2);
881         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
882         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
883         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
884         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
885         let channel_id = chan.2;
886
887         // A                                        B
888         // (1) update_fee/commitment_signed      ->
889         //                                       <- (2) revoke_and_ack
890         //                                       .- send (3) commitment_signed
891         // (4) update_fee/commitment_signed      ->
892         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
893         //                                       <- (3) commitment_signed delivered
894         // send (6) revoke_and_ack               -.
895         //                                       <- (5) deliver revoke_and_ack
896         // (6) deliver revoke_and_ack            ->
897         //                                       .- send (7) commitment_signed in response to (4)
898         //                                       <- (7) deliver commitment_signed
899         // revoke_and_ack                        ->
900
901         // Create and deliver (1)...
902         let feerate;
903         {
904                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905                 feerate = *feerate_lock;
906                 *feerate_lock = feerate + 20;
907         }
908         nodes[0].node.timer_tick_occurred();
909         check_added_monitors!(nodes[0], 1);
910
911         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
912         assert_eq!(events_0.len(), 1);
913         let (update_msg, commitment_signed) = match events_0[0] {
914                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
915                         (update_fee.as_ref(), commitment_signed)
916                 },
917                 _ => panic!("Unexpected event"),
918         };
919         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920
921         // Generate (2) and (3):
922         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
923         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
924         check_added_monitors!(nodes[1], 1);
925
926         // Deliver (2):
927         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929         check_added_monitors!(nodes[0], 1);
930
931         // Create and deliver (4)...
932         {
933                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
934                 *feerate_lock = feerate + 30;
935         }
936         nodes[0].node.timer_tick_occurred();
937         check_added_monitors!(nodes[0], 1);
938         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
939         assert_eq!(events_0.len(), 1);
940         let (update_msg, commitment_signed) = match events_0[0] {
941                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
942                         (update_fee.as_ref(), commitment_signed)
943                 },
944                 _ => panic!("Unexpected event"),
945         };
946
947         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
948         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
949         check_added_monitors!(nodes[1], 1);
950         // ... creating (5)
951         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
952         // No commitment_signed so get_event_msg's assert(len == 1) passes
953
954         // Handle (3), creating (6):
955         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
956         check_added_monitors!(nodes[0], 1);
957         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
958         // No commitment_signed so get_event_msg's assert(len == 1) passes
959
960         // Deliver (5):
961         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
962         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
963         check_added_monitors!(nodes[0], 1);
964
965         // Deliver (6), creating (7):
966         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
967         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
968         assert!(commitment_update.update_add_htlcs.is_empty());
969         assert!(commitment_update.update_fulfill_htlcs.is_empty());
970         assert!(commitment_update.update_fail_htlcs.is_empty());
971         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
972         assert!(commitment_update.update_fee.is_none());
973         check_added_monitors!(nodes[1], 1);
974
975         // Deliver (7)
976         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
977         check_added_monitors!(nodes[0], 1);
978         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
979         // No commitment_signed so get_event_msg's assert(len == 1) passes
980
981         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
982         check_added_monitors!(nodes[1], 1);
983         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
984
985         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
986         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
987         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
988         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
989         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
990 }
991
992 #[test]
993 fn fake_network_test() {
994         // Simple test which builds a network of ChannelManagers, connects them to each other, and
995         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
996         let chanmon_cfgs = create_chanmon_cfgs(4);
997         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
998         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
999         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1000
1001         // Create some initial channels
1002         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1003         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1004         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1005
1006         // Rebalance the network a bit by relaying one payment through all the channels...
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1008         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1009         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1010         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1011
1012         // Send some more payments
1013         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1014         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1015         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1016
1017         // Test failure packets
1018         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1019         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1020
1021         // Add a new channel that skips 3
1022         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1023
1024         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1025         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1026         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1027         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1028         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1029         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1030         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1031
1032         // Do some rebalance loop payments, simultaneously
1033         let mut hops = Vec::with_capacity(3);
1034         hops.push(RouteHop {
1035                 pubkey: nodes[2].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_2.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1041                 maybe_announced_channel: true,
1042         });
1043         hops.push(RouteHop {
1044                 pubkey: nodes[3].node.get_our_node_id(),
1045                 node_features: NodeFeatures::empty(),
1046                 short_channel_id: chan_3.0.contents.short_channel_id,
1047                 channel_features: ChannelFeatures::empty(),
1048                 fee_msat: 0,
1049                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1050                 maybe_announced_channel: true,
1051         });
1052         hops.push(RouteHop {
1053                 pubkey: nodes[1].node.get_our_node_id(),
1054                 node_features: nodes[1].node.node_features(),
1055                 short_channel_id: chan_4.0.contents.short_channel_id,
1056                 channel_features: nodes[1].node.channel_features(),
1057                 fee_msat: 1000000,
1058                 cltv_expiry_delta: TEST_FINAL_CLTV,
1059                 maybe_announced_channel: true,
1060         });
1061         hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1062         hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1063         let payment_preimage_1 = send_along_route(&nodes[1],
1064                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1065                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1066
1067         let mut hops = Vec::with_capacity(3);
1068         hops.push(RouteHop {
1069                 pubkey: nodes[3].node.get_our_node_id(),
1070                 node_features: NodeFeatures::empty(),
1071                 short_channel_id: chan_4.0.contents.short_channel_id,
1072                 channel_features: ChannelFeatures::empty(),
1073                 fee_msat: 0,
1074                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1075                 maybe_announced_channel: true,
1076         });
1077         hops.push(RouteHop {
1078                 pubkey: nodes[2].node.get_our_node_id(),
1079                 node_features: NodeFeatures::empty(),
1080                 short_channel_id: chan_3.0.contents.short_channel_id,
1081                 channel_features: ChannelFeatures::empty(),
1082                 fee_msat: 0,
1083                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1084                 maybe_announced_channel: true,
1085         });
1086         hops.push(RouteHop {
1087                 pubkey: nodes[1].node.get_our_node_id(),
1088                 node_features: nodes[1].node.node_features(),
1089                 short_channel_id: chan_2.0.contents.short_channel_id,
1090                 channel_features: nodes[1].node.channel_features(),
1091                 fee_msat: 1000000,
1092                 cltv_expiry_delta: TEST_FINAL_CLTV,
1093                 maybe_announced_channel: true,
1094         });
1095         hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1096         hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1097         let payment_hash_2 = send_along_route(&nodes[1],
1098                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1099                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1100
1101         // Claim the rebalances...
1102         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1103         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1104
1105         // Close down the channels...
1106         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1107         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1108         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1109         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1110         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1111         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1112         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1113         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1114         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1115         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1116         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1117         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1118 }
1119
1120 #[test]
1121 fn holding_cell_htlc_counting() {
1122         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1123         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1124         // commitment dance rounds.
1125         let chanmon_cfgs = create_chanmon_cfgs(3);
1126         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1127         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1128         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1129         create_announced_chan_between_nodes(&nodes, 0, 1);
1130         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1131
1132         // Fetch a route in advance as we will be unable to once we're unable to send.
1133         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1134
1135         let mut payments = Vec::new();
1136         for _ in 0..50 {
1137                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1138                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1139                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1140                 payments.push((payment_preimage, payment_hash));
1141         }
1142         check_added_monitors!(nodes[1], 1);
1143
1144         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1145         assert_eq!(events.len(), 1);
1146         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1147         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1148
1149         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1150         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1151         // another HTLC.
1152         {
1153                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1154                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1155                         ), true, APIError::ChannelUnavailable { .. }, {});
1156                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1157         }
1158
1159         // This should also be true if we try to forward a payment.
1160         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1161         {
1162                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1163                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1164                 check_added_monitors!(nodes[0], 1);
1165         }
1166
1167         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1168         assert_eq!(events.len(), 1);
1169         let payment_event = SendEvent::from_event(events.pop().unwrap());
1170         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1171
1172         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1173         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1174         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1175         // fails), the second will process the resulting failure and fail the HTLC backward.
1176         expect_pending_htlcs_forwardable!(nodes[1]);
1177         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1178         check_added_monitors!(nodes[1], 1);
1179
1180         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1181         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1182         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1183
1184         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1185
1186         // Now forward all the pending HTLCs and claim them back
1187         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1188         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1189         check_added_monitors!(nodes[2], 1);
1190
1191         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1192         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1193         check_added_monitors!(nodes[1], 1);
1194         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1195
1196         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1197         check_added_monitors!(nodes[1], 1);
1198         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1199
1200         for ref update in as_updates.update_add_htlcs.iter() {
1201                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1202         }
1203         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1204         check_added_monitors!(nodes[2], 1);
1205         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1206         check_added_monitors!(nodes[2], 1);
1207         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1208
1209         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1210         check_added_monitors!(nodes[1], 1);
1211         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1212         check_added_monitors!(nodes[1], 1);
1213         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1214
1215         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1216         check_added_monitors!(nodes[2], 1);
1217
1218         expect_pending_htlcs_forwardable!(nodes[2]);
1219
1220         let events = nodes[2].node.get_and_clear_pending_events();
1221         assert_eq!(events.len(), payments.len());
1222         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1223                 match event {
1224                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1225                                 assert_eq!(*payment_hash, *hash);
1226                         },
1227                         _ => panic!("Unexpected event"),
1228                 };
1229         }
1230
1231         for (preimage, _) in payments.drain(..) {
1232                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1233         }
1234
1235         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1236 }
1237
1238 #[test]
1239 fn duplicate_htlc_test() {
1240         // Test that we accept duplicate payment_hash HTLCs across the network and that
1241         // claiming/failing them are all separate and don't affect each other
1242         let chanmon_cfgs = create_chanmon_cfgs(6);
1243         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1244         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1245         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1246
1247         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1248         create_announced_chan_between_nodes(&nodes, 0, 3);
1249         create_announced_chan_between_nodes(&nodes, 1, 3);
1250         create_announced_chan_between_nodes(&nodes, 2, 3);
1251         create_announced_chan_between_nodes(&nodes, 3, 4);
1252         create_announced_chan_between_nodes(&nodes, 3, 5);
1253
1254         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1255
1256         *nodes[0].network_payment_count.borrow_mut() -= 1;
1257         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1258
1259         *nodes[0].network_payment_count.borrow_mut() -= 1;
1260         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1261
1262         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1263         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1264         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1265 }
1266
1267 #[test]
1268 fn test_duplicate_htlc_different_direction_onchain() {
1269         // Test that ChannelMonitor doesn't generate 2 preimage txn
1270         // when we have 2 HTLCs with same preimage that go across a node
1271         // in opposite directions, even with the same payment secret.
1272         let chanmon_cfgs = create_chanmon_cfgs(2);
1273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1276
1277         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1278
1279         // balancing
1280         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1281
1282         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1283
1284         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1285         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1286         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1287
1288         // Provide preimage to node 0 by claiming payment
1289         nodes[0].node.claim_funds(payment_preimage);
1290         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1291         check_added_monitors!(nodes[0], 1);
1292
1293         // Broadcast node 1 commitment txn
1294         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1295
1296         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1297         let mut has_both_htlcs = 0; // check htlcs match ones committed
1298         for outp in remote_txn[0].output.iter() {
1299                 if outp.value == 800_000 / 1000 {
1300                         has_both_htlcs += 1;
1301                 } else if outp.value == 900_000 / 1000 {
1302                         has_both_htlcs += 1;
1303                 }
1304         }
1305         assert_eq!(has_both_htlcs, 2);
1306
1307         mine_transaction(&nodes[0], &remote_txn[0]);
1308         check_added_monitors!(nodes[0], 1);
1309         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1310         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1311
1312         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1313         assert_eq!(claim_txn.len(), 3);
1314
1315         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1316         check_spends!(claim_txn[1], remote_txn[0]);
1317         check_spends!(claim_txn[2], remote_txn[0]);
1318         let preimage_tx = &claim_txn[0];
1319         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1320                 (&claim_txn[1], &claim_txn[2])
1321         } else {
1322                 (&claim_txn[2], &claim_txn[1])
1323         };
1324
1325         assert_eq!(preimage_tx.input.len(), 1);
1326         assert_eq!(preimage_bump_tx.input.len(), 1);
1327
1328         assert_eq!(preimage_tx.input.len(), 1);
1329         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1330         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1331
1332         assert_eq!(timeout_tx.input.len(), 1);
1333         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1334         check_spends!(timeout_tx, remote_txn[0]);
1335         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1336
1337         let events = nodes[0].node.get_and_clear_pending_msg_events();
1338         assert_eq!(events.len(), 3);
1339         for e in events {
1340                 match e {
1341                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1342                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1343                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1344                                 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1345                         },
1346                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1347                                 assert!(update_add_htlcs.is_empty());
1348                                 assert!(update_fail_htlcs.is_empty());
1349                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1350                                 assert!(update_fail_malformed_htlcs.is_empty());
1351                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1352                         },
1353                         _ => panic!("Unexpected event"),
1354                 }
1355         }
1356 }
1357
1358 #[test]
1359 fn test_basic_channel_reserve() {
1360         let chanmon_cfgs = create_chanmon_cfgs(2);
1361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1365
1366         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1367         let channel_reserve = chan_stat.channel_reserve_msat;
1368
1369         // The 2* and +1 are for the fee spike reserve.
1370         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, &get_channel_type_features!(nodes[0], nodes[1], chan.2));
1371         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1372         let (mut route, our_payment_hash, _, our_payment_secret) =
1373                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1374         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1375         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1376                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1377         match err {
1378                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1379                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1380                         else { panic!("Unexpected error variant"); }
1381                 },
1382                 _ => panic!("Unexpected error variant"),
1383         }
1384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1385
1386         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1387 }
1388
1389 #[test]
1390 fn test_fee_spike_violation_fails_htlc() {
1391         let chanmon_cfgs = create_chanmon_cfgs(2);
1392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1395         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1396
1397         let (mut route, payment_hash, _, payment_secret) =
1398                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1399         route.paths[0].hops[0].fee_msat += 1;
1400         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1401         let secp_ctx = Secp256k1::new();
1402         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1403
1404         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1405
1406         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1407         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1408                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1409         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1410         let msg = msgs::UpdateAddHTLC {
1411                 channel_id: chan.2,
1412                 htlc_id: 0,
1413                 amount_msat: htlc_msat,
1414                 payment_hash: payment_hash,
1415                 cltv_expiry: htlc_cltv,
1416                 onion_routing_packet: onion_packet,
1417                 skimmed_fee_msat: None,
1418                 blinding_point: None,
1419         };
1420
1421         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1422
1423         // Now manually create the commitment_signed message corresponding to the update_add
1424         // nodes[0] just sent. In the code for construction of this message, "local" refers
1425         // to the sender of the message, and "remote" refers to the receiver.
1426
1427         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1428
1429         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1430
1431         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1432         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1433         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1434                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1435                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1436                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1437                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1438                 ).flatten().unwrap();
1439                 let chan_signer = local_chan.get_signer();
1440                 // Make the signer believe we validated another commitment, so we can release the secret
1441                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1442
1443                 let pubkeys = chan_signer.as_ref().pubkeys();
1444                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1445                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1446                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1447                  chan_signer.as_ref().pubkeys().funding_pubkey)
1448         };
1449         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1450                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1451                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1452                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1453                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1454                 ).flatten().unwrap();
1455                 let chan_signer = remote_chan.get_signer();
1456                 let pubkeys = chan_signer.as_ref().pubkeys();
1457                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1458                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1459                  chan_signer.as_ref().pubkeys().funding_pubkey)
1460         };
1461
1462         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1463         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1464                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1465
1466         // Build the remote commitment transaction so we can sign it, and then later use the
1467         // signature for the commitment_signed message.
1468         let local_chan_balance = 1313;
1469
1470         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1471                 offered: false,
1472                 amount_msat: 3460001,
1473                 cltv_expiry: htlc_cltv,
1474                 payment_hash,
1475                 transaction_output_index: Some(1),
1476         };
1477
1478         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1479
1480         let res = {
1481                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1482                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1483                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1484                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1485                 ).flatten().unwrap();
1486                 let local_chan_signer = local_chan.get_signer();
1487                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1488                         commitment_number,
1489                         95000,
1490                         local_chan_balance,
1491                         local_funding, remote_funding,
1492                         commit_tx_keys.clone(),
1493                         feerate_per_kw,
1494                         &mut vec![(accepted_htlc_info, ())],
1495                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1496                 );
1497                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
1498         };
1499
1500         let commit_signed_msg = msgs::CommitmentSigned {
1501                 channel_id: chan.2,
1502                 signature: res.0,
1503                 htlc_signatures: res.1,
1504                 #[cfg(taproot)]
1505                 partial_signature_with_nonce: None,
1506         };
1507
1508         // Send the commitment_signed message to the nodes[1].
1509         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1510         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1511
1512         // Send the RAA to nodes[1].
1513         let raa_msg = msgs::RevokeAndACK {
1514                 channel_id: chan.2,
1515                 per_commitment_secret: local_secret,
1516                 next_per_commitment_point: next_local_point,
1517                 #[cfg(taproot)]
1518                 next_local_nonce: None,
1519         };
1520         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1521
1522         let events = nodes[1].node.get_and_clear_pending_msg_events();
1523         assert_eq!(events.len(), 1);
1524         // Make sure the HTLC failed in the way we expect.
1525         match events[0] {
1526                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1527                         assert_eq!(update_fail_htlcs.len(), 1);
1528                         update_fail_htlcs[0].clone()
1529                 },
1530                 _ => panic!("Unexpected event"),
1531         };
1532         nodes[1].logger.assert_log("lightning::ln::channel",
1533                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1534
1535         check_added_monitors!(nodes[1], 2);
1536 }
1537
1538 #[test]
1539 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1540         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1541         // Set the fee rate for the channel very high, to the point where the fundee
1542         // sending any above-dust amount would result in a channel reserve violation.
1543         // In this test we check that we would be prevented from sending an HTLC in
1544         // this situation.
1545         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1548         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1549         let default_config = UserConfig::default();
1550         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1551
1552         let mut push_amt = 100_000_000;
1553         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1554
1555         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1556
1557         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1558
1559         // Fetch a route in advance as we will be unable to once we're unable to send.
1560         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1561         // Sending exactly enough to hit the reserve amount should be accepted
1562         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1564         }
1565
1566         // However one more HTLC should be significantly over the reserve amount and fail.
1567         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1568                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1569                 ), true, APIError::ChannelUnavailable { .. }, {});
1570         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1571 }
1572
1573 #[test]
1574 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1575         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1576         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1579         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1580         let default_config = UserConfig::default();
1581         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1582
1583         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1584         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1585         // transaction fee with 0 HTLCs (183 sats)).
1586         let mut push_amt = 100_000_000;
1587         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1588         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1589         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1590
1591         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1592         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1593                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1594         }
1595
1596         let (mut route, payment_hash, _, payment_secret) =
1597                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1598         route.paths[0].hops[0].fee_msat = 700_000;
1599         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1600         let secp_ctx = Secp256k1::new();
1601         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1602         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1603         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1604         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1605                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1606         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1607         let msg = msgs::UpdateAddHTLC {
1608                 channel_id: chan.2,
1609                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1610                 amount_msat: htlc_msat,
1611                 payment_hash: payment_hash,
1612                 cltv_expiry: htlc_cltv,
1613                 onion_routing_packet: onion_packet,
1614                 skimmed_fee_msat: None,
1615                 blinding_point: None,
1616         };
1617
1618         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1619         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1620         nodes[0].logger.assert_log("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1621         assert_eq!(nodes[0].node.list_channels().len(), 0);
1622         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1623         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1624         check_added_monitors!(nodes[0], 1);
1625         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() },
1626                 [nodes[1].node.get_our_node_id()], 100000);
1627 }
1628
1629 #[test]
1630 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1631         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1632         // calculating our commitment transaction fee (this was previously broken).
1633         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1634         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1635
1636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1639         let default_config = UserConfig::default();
1640         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1641
1642         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1643         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1644         // transaction fee with 0 HTLCs (183 sats)).
1645         let mut push_amt = 100_000_000;
1646         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1647         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1648         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1649
1650         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1651                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1652         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1653         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1654         // commitment transaction fee.
1655         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1656
1657         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1658         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1659                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1660         }
1661
1662         // One more than the dust amt should fail, however.
1663         let (mut route, our_payment_hash, _, our_payment_secret) =
1664                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1665         route.paths[0].hops[0].fee_msat += 1;
1666         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1667                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1668                 ), true, APIError::ChannelUnavailable { .. }, {});
1669 }
1670
1671 #[test]
1672 fn test_chan_init_feerate_unaffordability() {
1673         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1674         // channel reserve and feerate requirements.
1675         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1676         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680         let default_config = UserConfig::default();
1681         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1682
1683         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1684         // HTLC.
1685         let mut push_amt = 100_000_000;
1686         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1687         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1688                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1689
1690         // During open, we don't have a "counterparty channel reserve" to check against, so that
1691         // requirement only comes into play on the open_channel handling side.
1692         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1693         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1694         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1695         open_channel_msg.push_msat += 1;
1696         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1697
1698         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1699         assert_eq!(msg_events.len(), 1);
1700         match msg_events[0] {
1701                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1702                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1703                 },
1704                 _ => panic!("Unexpected event"),
1705         }
1706 }
1707
1708 #[test]
1709 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1710         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1711         // calculating our counterparty's commitment transaction fee (this was previously broken).
1712         let chanmon_cfgs = create_chanmon_cfgs(2);
1713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1715         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1716         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1717
1718         let payment_amt = 46000; // Dust amount
1719         // In the previous code, these first four payments would succeed.
1720         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1722         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1723         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1724
1725         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1726         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1728         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1729         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1730         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1731
1732         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1733         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1734         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1735         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1736 }
1737
1738 #[test]
1739 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1740         let chanmon_cfgs = create_chanmon_cfgs(3);
1741         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1742         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1743         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1744         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1745         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1746
1747         let feemsat = 239;
1748         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1749         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1750         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1751         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1752
1753         // Add a 2* and +1 for the fee spike reserve.
1754         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1755         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1756         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1757
1758         // Add a pending HTLC.
1759         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1760         let payment_event_1 = {
1761                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1762                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1763                 check_added_monitors!(nodes[0], 1);
1764
1765                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1766                 assert_eq!(events.len(), 1);
1767                 SendEvent::from_event(events.remove(0))
1768         };
1769         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1770
1771         // Attempt to trigger a channel reserve violation --> payment failure.
1772         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1773         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1774         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1775         let mut route_2 = route_1.clone();
1776         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1777
1778         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1779         let secp_ctx = Secp256k1::new();
1780         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1781         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1782         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1783         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1784                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1785         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1786         let msg = msgs::UpdateAddHTLC {
1787                 channel_id: chan.2,
1788                 htlc_id: 1,
1789                 amount_msat: htlc_msat + 1,
1790                 payment_hash: our_payment_hash_1,
1791                 cltv_expiry: htlc_cltv,
1792                 onion_routing_packet: onion_packet,
1793                 skimmed_fee_msat: None,
1794                 blinding_point: None,
1795         };
1796
1797         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1798         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1799         nodes[1].logger.assert_log("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1800         assert_eq!(nodes[1].node.list_channels().len(), 1);
1801         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1802         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1803         check_added_monitors!(nodes[1], 1);
1804         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1805                 [nodes[0].node.get_our_node_id()], 100000);
1806 }
1807
1808 #[test]
1809 fn test_inbound_outbound_capacity_is_not_zero() {
1810         let chanmon_cfgs = create_chanmon_cfgs(2);
1811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1814         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1815         let channels0 = node_chanmgrs[0].list_channels();
1816         let channels1 = node_chanmgrs[1].list_channels();
1817         let default_config = UserConfig::default();
1818         assert_eq!(channels0.len(), 1);
1819         assert_eq!(channels1.len(), 1);
1820
1821         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1822         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1823         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1824
1825         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1826         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1827 }
1828
1829 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1830         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1831 }
1832
1833 #[test]
1834 fn test_channel_reserve_holding_cell_htlcs() {
1835         let chanmon_cfgs = create_chanmon_cfgs(3);
1836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837         // When this test was written, the default base fee floated based on the HTLC count.
1838         // It is now fixed, so we simply set the fee to the expected value here.
1839         let mut config = test_default_channel_config();
1840         config.channel_config.forwarding_fee_base_msat = 239;
1841         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1842         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1843         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1844         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1845
1846         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1847         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1848
1849         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1850         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1851
1852         macro_rules! expect_forward {
1853                 ($node: expr) => {{
1854                         let mut events = $node.node.get_and_clear_pending_msg_events();
1855                         assert_eq!(events.len(), 1);
1856                         check_added_monitors!($node, 1);
1857                         let payment_event = SendEvent::from_event(events.remove(0));
1858                         payment_event
1859                 }}
1860         }
1861
1862         let feemsat = 239; // set above
1863         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1864         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1865         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1866
1867         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1868
1869         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1870         {
1871                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1872                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1873                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1874                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1875                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1876
1877                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1878                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1879                         ), true, APIError::ChannelUnavailable { .. }, {});
1880                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1881         }
1882
1883         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1884         // nodes[0]'s wealth
1885         loop {
1886                 let amt_msat = recv_value_0 + total_fee_msat;
1887                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1888                 // Also, ensure that each payment has enough to be over the dust limit to
1889                 // ensure it'll be included in each commit tx fee calculation.
1890                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1891                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1892                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1893                         break;
1894                 }
1895
1896                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1897                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1898                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1899                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1900                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1901
1902                 let (stat01_, stat11_, stat12_, stat22_) = (
1903                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1904                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1905                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1906                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1907                 );
1908
1909                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1910                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1911                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1912                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1913                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1914         }
1915
1916         // adding pending output.
1917         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1918         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1919         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1920         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1921         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1922         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1923         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1924         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1925         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1926         // policy.
1927         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1928         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1929         let amt_msat_1 = recv_value_1 + total_fee_msat;
1930
1931         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1932         let payment_event_1 = {
1933                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1934                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1935                 check_added_monitors!(nodes[0], 1);
1936
1937                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1938                 assert_eq!(events.len(), 1);
1939                 SendEvent::from_event(events.remove(0))
1940         };
1941         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1942
1943         // channel reserve test with htlc pending output > 0
1944         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1945         {
1946                 let mut route = route_1.clone();
1947                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1948                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1949                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1950                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1951                         ), true, APIError::ChannelUnavailable { .. }, {});
1952                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1953         }
1954
1955         // split the rest to test holding cell
1956         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1957         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1958         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1959         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1960         {
1961                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1962                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1963         }
1964
1965         // now see if they go through on both sides
1966         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1967         // but this will stuck in the holding cell
1968         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1969                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1970         check_added_monitors!(nodes[0], 0);
1971         let events = nodes[0].node.get_and_clear_pending_events();
1972         assert_eq!(events.len(), 0);
1973
1974         // test with outbound holding cell amount > 0
1975         {
1976                 let (mut route, our_payment_hash, _, our_payment_secret) =
1977                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1978                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1979                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1980                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1981                         ), true, APIError::ChannelUnavailable { .. }, {});
1982                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1983         }
1984
1985         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1986         // this will also stuck in the holding cell
1987         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1988                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1989         check_added_monitors!(nodes[0], 0);
1990         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1991         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1992
1993         // flush the pending htlc
1994         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1995         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1996         check_added_monitors!(nodes[1], 1);
1997
1998         // the pending htlc should be promoted to committed
1999         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2000         check_added_monitors!(nodes[0], 1);
2001         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2002
2003         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2004         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2005         // No commitment_signed so get_event_msg's assert(len == 1) passes
2006         check_added_monitors!(nodes[0], 1);
2007
2008         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2009         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2010         check_added_monitors!(nodes[1], 1);
2011
2012         expect_pending_htlcs_forwardable!(nodes[1]);
2013
2014         let ref payment_event_11 = expect_forward!(nodes[1]);
2015         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2016         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2017
2018         expect_pending_htlcs_forwardable!(nodes[2]);
2019         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2020
2021         // flush the htlcs in the holding cell
2022         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2023         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2024         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2025         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2026         expect_pending_htlcs_forwardable!(nodes[1]);
2027
2028         let ref payment_event_3 = expect_forward!(nodes[1]);
2029         assert_eq!(payment_event_3.msgs.len(), 2);
2030         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2031         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2032
2033         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2034         expect_pending_htlcs_forwardable!(nodes[2]);
2035
2036         let events = nodes[2].node.get_and_clear_pending_events();
2037         assert_eq!(events.len(), 2);
2038         match events[0] {
2039                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2040                         assert_eq!(our_payment_hash_21, *payment_hash);
2041                         assert_eq!(recv_value_21, amount_msat);
2042                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2043                         assert_eq!(via_channel_id, Some(chan_2.2));
2044                         match &purpose {
2045                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2046                                         assert!(payment_preimage.is_none());
2047                                         assert_eq!(our_payment_secret_21, *payment_secret);
2048                                 },
2049                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2050                         }
2051                 },
2052                 _ => panic!("Unexpected event"),
2053         }
2054         match events[1] {
2055                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2056                         assert_eq!(our_payment_hash_22, *payment_hash);
2057                         assert_eq!(recv_value_22, amount_msat);
2058                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2059                         assert_eq!(via_channel_id, Some(chan_2.2));
2060                         match &purpose {
2061                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2062                                         assert!(payment_preimage.is_none());
2063                                         assert_eq!(our_payment_secret_22, *payment_secret);
2064                                 },
2065                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2066                         }
2067                 },
2068                 _ => panic!("Unexpected event"),
2069         }
2070
2071         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2072         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2073         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2074
2075         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2076         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2077         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2078
2079         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2080         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2081         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2082         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2083         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2084
2085         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2086         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2087 }
2088
2089 #[test]
2090 fn channel_reserve_in_flight_removes() {
2091         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2092         // can send to its counterparty, but due to update ordering, the other side may not yet have
2093         // considered those HTLCs fully removed.
2094         // This tests that we don't count HTLCs which will not be included in the next remote
2095         // commitment transaction towards the reserve value (as it implies no commitment transaction
2096         // will be generated which violates the remote reserve value).
2097         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2098         // To test this we:
2099         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2100         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2101         //    you only consider the value of the first HTLC, it may not),
2102         //  * start routing a third HTLC from A to B,
2103         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2104         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2105         //  * deliver the first fulfill from B
2106         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2107         //    claim,
2108         //  * deliver A's response CS and RAA.
2109         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2110         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2111         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2112         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2113         let chanmon_cfgs = create_chanmon_cfgs(2);
2114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2116         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2117         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2118
2119         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2120         // Route the first two HTLCs.
2121         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2122         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2123         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2124
2125         // Start routing the third HTLC (this is just used to get everyone in the right state).
2126         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2127         let send_1 = {
2128                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2129                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2130                 check_added_monitors!(nodes[0], 1);
2131                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2132                 assert_eq!(events.len(), 1);
2133                 SendEvent::from_event(events.remove(0))
2134         };
2135
2136         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2137         // initial fulfill/CS.
2138         nodes[1].node.claim_funds(payment_preimage_1);
2139         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2140         check_added_monitors!(nodes[1], 1);
2141         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2142
2143         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2144         // remove the second HTLC when we send the HTLC back from B to A.
2145         nodes[1].node.claim_funds(payment_preimage_2);
2146         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2147         check_added_monitors!(nodes[1], 1);
2148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2149
2150         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2151         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2152         check_added_monitors!(nodes[0], 1);
2153         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2154         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2155
2156         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2157         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2158         check_added_monitors!(nodes[1], 1);
2159         // B is already AwaitingRAA, so cant generate a CS here
2160         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2161
2162         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2163         check_added_monitors!(nodes[1], 1);
2164         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2165
2166         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2167         check_added_monitors!(nodes[0], 1);
2168         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2169
2170         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2171         check_added_monitors!(nodes[1], 1);
2172         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2173
2174         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2175         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2176         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2177         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2178         // on-chain as necessary).
2179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2180         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2181         check_added_monitors!(nodes[0], 1);
2182         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2183         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2184
2185         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2186         check_added_monitors!(nodes[1], 1);
2187         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2188
2189         expect_pending_htlcs_forwardable!(nodes[1]);
2190         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2191
2192         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2193         // resolve the second HTLC from A's point of view.
2194         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2195         check_added_monitors!(nodes[0], 1);
2196         expect_payment_path_successful!(nodes[0]);
2197         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2198
2199         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2200         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2201         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2202         let send_2 = {
2203                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2204                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2205                 check_added_monitors!(nodes[1], 1);
2206                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2207                 assert_eq!(events.len(), 1);
2208                 SendEvent::from_event(events.remove(0))
2209         };
2210
2211         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2212         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2213         check_added_monitors!(nodes[0], 1);
2214         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2215
2216         // Now just resolve all the outstanding messages/HTLCs for completeness...
2217
2218         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2219         check_added_monitors!(nodes[1], 1);
2220         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2221
2222         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2223         check_added_monitors!(nodes[1], 1);
2224
2225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2226         check_added_monitors!(nodes[0], 1);
2227         expect_payment_path_successful!(nodes[0]);
2228         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2229
2230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2231         check_added_monitors!(nodes[1], 1);
2232         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2233
2234         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2235         check_added_monitors!(nodes[0], 1);
2236
2237         expect_pending_htlcs_forwardable!(nodes[0]);
2238         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2239
2240         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2241         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2242 }
2243
2244 #[test]
2245 fn channel_monitor_network_test() {
2246         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2247         // tests that ChannelMonitor is able to recover from various states.
2248         let chanmon_cfgs = create_chanmon_cfgs(5);
2249         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2250         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2251         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2252
2253         // Create some initial channels
2254         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2255         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2256         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2257         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2258
2259         // Make sure all nodes are at the same starting height
2260         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2261         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2262         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2263         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2264         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2265
2266         // Rebalance the network a bit by relaying one payment through all the channels...
2267         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2268         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2269         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2270         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2271
2272         // Simple case with no pending HTLCs:
2273         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2274         check_added_monitors!(nodes[1], 1);
2275         check_closed_broadcast!(nodes[1], true);
2276         {
2277                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2278                 assert_eq!(node_txn.len(), 1);
2279                 mine_transaction(&nodes[0], &node_txn[0]);
2280                 check_added_monitors!(nodes[0], 1);
2281                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2282         }
2283         check_closed_broadcast!(nodes[0], true);
2284         assert_eq!(nodes[0].node.list_channels().len(), 0);
2285         assert_eq!(nodes[1].node.list_channels().len(), 1);
2286         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2287         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2288
2289         // One pending HTLC is discarded by the force-close:
2290         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2291
2292         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2293         // broadcasted until we reach the timelock time).
2294         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2295         check_closed_broadcast!(nodes[1], true);
2296         check_added_monitors!(nodes[1], 1);
2297         {
2298                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2299                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2300                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2301                 mine_transaction(&nodes[2], &node_txn[0]);
2302                 check_added_monitors!(nodes[2], 1);
2303                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2304         }
2305         check_closed_broadcast!(nodes[2], true);
2306         assert_eq!(nodes[1].node.list_channels().len(), 0);
2307         assert_eq!(nodes[2].node.list_channels().len(), 1);
2308         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2309         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2310
2311         macro_rules! claim_funds {
2312                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2313                         {
2314                                 $node.node.claim_funds($preimage);
2315                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2316                                 check_added_monitors!($node, 1);
2317
2318                                 let events = $node.node.get_and_clear_pending_msg_events();
2319                                 assert_eq!(events.len(), 1);
2320                                 match events[0] {
2321                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2322                                                 assert!(update_add_htlcs.is_empty());
2323                                                 assert!(update_fail_htlcs.is_empty());
2324                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2325                                         },
2326                                         _ => panic!("Unexpected event"),
2327                                 };
2328                         }
2329                 }
2330         }
2331
2332         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2333         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2334         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2335         check_added_monitors!(nodes[2], 1);
2336         check_closed_broadcast!(nodes[2], true);
2337         let node2_commitment_txid;
2338         {
2339                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2340                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2341                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2342                 node2_commitment_txid = node_txn[0].txid();
2343
2344                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2345                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2346                 mine_transaction(&nodes[3], &node_txn[0]);
2347                 check_added_monitors!(nodes[3], 1);
2348                 check_preimage_claim(&nodes[3], &node_txn);
2349         }
2350         check_closed_broadcast!(nodes[3], true);
2351         assert_eq!(nodes[2].node.list_channels().len(), 0);
2352         assert_eq!(nodes[3].node.list_channels().len(), 1);
2353         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2354         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2355
2356         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2357         // confusing us in the following tests.
2358         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2359
2360         // One pending HTLC to time out:
2361         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2362         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2363         // buffer space).
2364
2365         let (close_chan_update_1, close_chan_update_2) = {
2366                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2367                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2368                 assert_eq!(events.len(), 2);
2369                 let close_chan_update_1 = match events[0] {
2370                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2371                                 msg.clone()
2372                         },
2373                         _ => panic!("Unexpected event"),
2374                 };
2375                 match events[1] {
2376                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2377                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2378                         },
2379                         _ => panic!("Unexpected event"),
2380                 }
2381                 check_added_monitors!(nodes[3], 1);
2382
2383                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2384                 {
2385                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2386                         node_txn.retain(|tx| {
2387                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2388                                         false
2389                                 } else { true }
2390                         });
2391                 }
2392
2393                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2394
2395                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2396                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2397
2398                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2399                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2400                 assert_eq!(events.len(), 2);
2401                 let close_chan_update_2 = match events[0] {
2402                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2403                                 msg.clone()
2404                         },
2405                         _ => panic!("Unexpected event"),
2406                 };
2407                 match events[1] {
2408                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2409                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2410                         },
2411                         _ => panic!("Unexpected event"),
2412                 }
2413                 check_added_monitors!(nodes[4], 1);
2414                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2415                 check_closed_event!(nodes[4], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2416
2417                 mine_transaction(&nodes[4], &node_txn[0]);
2418                 check_preimage_claim(&nodes[4], &node_txn);
2419                 (close_chan_update_1, close_chan_update_2)
2420         };
2421         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2422         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2423         assert_eq!(nodes[3].node.list_channels().len(), 0);
2424         assert_eq!(nodes[4].node.list_channels().len(), 0);
2425
2426         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2427                 Ok(ChannelMonitorUpdateStatus::Completed));
2428         check_closed_event!(nodes[3], 1, ClosureReason::HolderForceClosed, [nodes[4].node.get_our_node_id()], 100000);
2429 }
2430
2431 #[test]
2432 fn test_justice_tx_htlc_timeout() {
2433         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2434         let mut alice_config = UserConfig::default();
2435         alice_config.channel_handshake_config.announced_channel = true;
2436         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2437         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2438         let mut bob_config = UserConfig::default();
2439         bob_config.channel_handshake_config.announced_channel = true;
2440         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2441         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2442         let user_cfgs = [Some(alice_config), Some(bob_config)];
2443         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2444         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2445         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2446         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2447         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2448         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2449         // Create some new channels:
2450         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2451
2452         // A pending HTLC which will be revoked:
2453         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2454         // Get the will-be-revoked local txn from nodes[0]
2455         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2456         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2457         assert_eq!(revoked_local_txn[0].input.len(), 1);
2458         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2459         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2460         assert_eq!(revoked_local_txn[1].input.len(), 1);
2461         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2462         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2463         // Revoke the old state
2464         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2465
2466         {
2467                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2468                 {
2469                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2470                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2471                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2472                         check_spends!(node_txn[0], revoked_local_txn[0]);
2473                         node_txn.swap_remove(0);
2474                 }
2475                 check_added_monitors!(nodes[1], 1);
2476                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2477                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2478
2479                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2480                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2481                 // Verify broadcast of revoked HTLC-timeout
2482                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2483                 check_added_monitors!(nodes[0], 1);
2484                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2485                 // Broadcast revoked HTLC-timeout on node 1
2486                 mine_transaction(&nodes[1], &node_txn[1]);
2487                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2488         }
2489         get_announce_close_broadcast_events(&nodes, 0, 1);
2490         assert_eq!(nodes[0].node.list_channels().len(), 0);
2491         assert_eq!(nodes[1].node.list_channels().len(), 0);
2492 }
2493
2494 #[test]
2495 fn test_justice_tx_htlc_success() {
2496         // Test justice txn built on revoked HTLC-Success tx, against both sides
2497         let mut alice_config = UserConfig::default();
2498         alice_config.channel_handshake_config.announced_channel = true;
2499         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2500         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2501         let mut bob_config = UserConfig::default();
2502         bob_config.channel_handshake_config.announced_channel = true;
2503         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2504         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2505         let user_cfgs = [Some(alice_config), Some(bob_config)];
2506         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2507         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2508         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2511         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2512         // Create some new channels:
2513         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2514
2515         // A pending HTLC which will be revoked:
2516         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2517         // Get the will-be-revoked local txn from B
2518         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2519         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2520         assert_eq!(revoked_local_txn[0].input.len(), 1);
2521         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2522         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2523         // Revoke the old state
2524         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2525         {
2526                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2527                 {
2528                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2529                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2530                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2531
2532                         check_spends!(node_txn[0], revoked_local_txn[0]);
2533                         node_txn.swap_remove(0);
2534                 }
2535                 check_added_monitors!(nodes[0], 1);
2536                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2537
2538                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2539                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2540                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2541                 check_added_monitors!(nodes[1], 1);
2542                 mine_transaction(&nodes[0], &node_txn[1]);
2543                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2544                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2545         }
2546         get_announce_close_broadcast_events(&nodes, 0, 1);
2547         assert_eq!(nodes[0].node.list_channels().len(), 0);
2548         assert_eq!(nodes[1].node.list_channels().len(), 0);
2549 }
2550
2551 #[test]
2552 fn revoked_output_claim() {
2553         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2554         // transaction is broadcast by its counterparty
2555         let chanmon_cfgs = create_chanmon_cfgs(2);
2556         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2557         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2558         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2559         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2560         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2561         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2562         assert_eq!(revoked_local_txn.len(), 1);
2563         // Only output is the full channel value back to nodes[0]:
2564         assert_eq!(revoked_local_txn[0].output.len(), 1);
2565         // Send a payment through, updating everyone's latest commitment txn
2566         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2567
2568         // Inform nodes[1] that nodes[0] broadcast a stale tx
2569         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2570         check_added_monitors!(nodes[1], 1);
2571         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2572         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2573         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2574
2575         check_spends!(node_txn[0], revoked_local_txn[0]);
2576
2577         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2578         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2579         get_announce_close_broadcast_events(&nodes, 0, 1);
2580         check_added_monitors!(nodes[0], 1);
2581         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2582 }
2583
2584 #[test]
2585 fn test_forming_justice_tx_from_monitor_updates() {
2586         do_test_forming_justice_tx_from_monitor_updates(true);
2587         do_test_forming_justice_tx_from_monitor_updates(false);
2588 }
2589
2590 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2591         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2592         // is properly formed and can be broadcasted/confirmed successfully in the event
2593         // that a revoked commitment transaction is broadcasted
2594         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2595         let chanmon_cfgs = create_chanmon_cfgs(2);
2596         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2597         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2598         let persisters = vec![WatchtowerPersister::new(destination_script0),
2599                 WatchtowerPersister::new(destination_script1)];
2600         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2601         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2602         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2603         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2604         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2605
2606         if !broadcast_initial_commitment {
2607                 // Send a payment to move the channel forward
2608                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2609         }
2610
2611         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2612         // We'll keep this commitment transaction to broadcast once it's revoked.
2613         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2614         assert_eq!(revoked_local_txn.len(), 1);
2615         let revoked_commitment_tx = &revoked_local_txn[0];
2616
2617         // Send another payment, now revoking the previous commitment tx
2618         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2619
2620         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2621         check_spends!(justice_tx, revoked_commitment_tx);
2622
2623         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2624         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2625
2626         check_added_monitors!(nodes[1], 1);
2627         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2628                 &[nodes[0].node.get_our_node_id()], 100_000);
2629         get_announce_close_broadcast_events(&nodes, 1, 0);
2630
2631         check_added_monitors!(nodes[0], 1);
2632         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2633                 &[nodes[1].node.get_our_node_id()], 100_000);
2634
2635         // Check that the justice tx has sent the revoked output value to nodes[1]
2636         let monitor = get_monitor!(nodes[1], channel_id);
2637         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2638                 match balance {
2639                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2640                         _ => panic!("Unexpected balance type"),
2641                 }
2642         });
2643         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2644         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2645         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2646         assert_eq!(total_claimable_balance, expected_claimable_balance);
2647 }
2648
2649
2650 #[test]
2651 fn claim_htlc_outputs_shared_tx() {
2652         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2653         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2654         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2655         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2656         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2657         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2658
2659         // Create some new channel:
2660         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2661
2662         // Rebalance the network to generate htlc in the two directions
2663         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2664         // 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
2665         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2666         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2667
2668         // Get the will-be-revoked local txn from node[0]
2669         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2670         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2671         assert_eq!(revoked_local_txn[0].input.len(), 1);
2672         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2673         assert_eq!(revoked_local_txn[1].input.len(), 1);
2674         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2675         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2676         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2677
2678         //Revoke the old state
2679         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2680
2681         {
2682                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2683                 check_added_monitors!(nodes[0], 1);
2684                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2685                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2686                 check_added_monitors!(nodes[1], 1);
2687                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2688                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2689                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2690
2691                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2692                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2693
2694                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2695                 check_spends!(node_txn[0], revoked_local_txn[0]);
2696
2697                 let mut witness_lens = BTreeSet::new();
2698                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2699                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2700                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2701                 assert_eq!(witness_lens.len(), 3);
2702                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2703                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2704                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2705
2706                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2707                 // ANTI_REORG_DELAY confirmations.
2708                 mine_transaction(&nodes[1], &node_txn[0]);
2709                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2710                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2711         }
2712         get_announce_close_broadcast_events(&nodes, 0, 1);
2713         assert_eq!(nodes[0].node.list_channels().len(), 0);
2714         assert_eq!(nodes[1].node.list_channels().len(), 0);
2715 }
2716
2717 #[test]
2718 fn claim_htlc_outputs_single_tx() {
2719         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2720         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2721         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2722         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2723         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2724         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2725
2726         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2727
2728         // Rebalance the network to generate htlc in the two directions
2729         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2730         // 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
2731         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2732         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2733         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2734
2735         // Get the will-be-revoked local txn from node[0]
2736         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2737
2738         //Revoke the old state
2739         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2740
2741         {
2742                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2743                 check_added_monitors!(nodes[0], 1);
2744                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2745                 check_added_monitors!(nodes[1], 1);
2746                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2747                 let mut events = nodes[0].node.get_and_clear_pending_events();
2748                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2749                 match events.last().unwrap() {
2750                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2751                         _ => panic!("Unexpected event"),
2752                 }
2753
2754                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2755                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2756
2757                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2758
2759                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2760                 assert_eq!(node_txn[0].input.len(), 1);
2761                 check_spends!(node_txn[0], chan_1.3);
2762                 assert_eq!(node_txn[1].input.len(), 1);
2763                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2764                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2765                 check_spends!(node_txn[1], node_txn[0]);
2766
2767                 // Filter out any non justice transactions.
2768                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2769                 assert!(node_txn.len() > 3);
2770
2771                 assert_eq!(node_txn[0].input.len(), 1);
2772                 assert_eq!(node_txn[1].input.len(), 1);
2773                 assert_eq!(node_txn[2].input.len(), 1);
2774
2775                 check_spends!(node_txn[0], revoked_local_txn[0]);
2776                 check_spends!(node_txn[1], revoked_local_txn[0]);
2777                 check_spends!(node_txn[2], revoked_local_txn[0]);
2778
2779                 let mut witness_lens = BTreeSet::new();
2780                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2781                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2782                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2783                 assert_eq!(witness_lens.len(), 3);
2784                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2785                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2786                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2787
2788                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2789                 // ANTI_REORG_DELAY confirmations.
2790                 mine_transaction(&nodes[1], &node_txn[0]);
2791                 mine_transaction(&nodes[1], &node_txn[1]);
2792                 mine_transaction(&nodes[1], &node_txn[2]);
2793                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2794                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2795         }
2796         get_announce_close_broadcast_events(&nodes, 0, 1);
2797         assert_eq!(nodes[0].node.list_channels().len(), 0);
2798         assert_eq!(nodes[1].node.list_channels().len(), 0);
2799 }
2800
2801 #[test]
2802 fn test_htlc_on_chain_success() {
2803         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2804         // the preimage backward accordingly. So here we test that ChannelManager is
2805         // broadcasting the right event to other nodes in payment path.
2806         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2807         // A --------------------> B ----------------------> C (preimage)
2808         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2809         // commitment transaction was broadcast.
2810         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2811         // towards B.
2812         // B should be able to claim via preimage if A then broadcasts its local tx.
2813         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2814         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2815         // PaymentSent event).
2816
2817         let chanmon_cfgs = create_chanmon_cfgs(3);
2818         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2819         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2820         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2821
2822         // Create some initial channels
2823         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2824         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2825
2826         // Ensure all nodes are at the same height
2827         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2828         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2829         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2830         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2831
2832         // Rebalance the network a bit by relaying one payment through all the channels...
2833         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2834         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2835
2836         let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2837         let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2838
2839         // Broadcast legit commitment tx from C on B's chain
2840         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2841         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2842         assert_eq!(commitment_tx.len(), 1);
2843         check_spends!(commitment_tx[0], chan_2.3);
2844         nodes[2].node.claim_funds(our_payment_preimage);
2845         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2846         nodes[2].node.claim_funds(our_payment_preimage_2);
2847         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2848         check_added_monitors!(nodes[2], 2);
2849         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2850         assert!(updates.update_add_htlcs.is_empty());
2851         assert!(updates.update_fail_htlcs.is_empty());
2852         assert!(updates.update_fail_malformed_htlcs.is_empty());
2853         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2854
2855         mine_transaction(&nodes[2], &commitment_tx[0]);
2856         check_closed_broadcast!(nodes[2], true);
2857         check_added_monitors!(nodes[2], 1);
2858         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2859         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2860         assert_eq!(node_txn.len(), 2);
2861         check_spends!(node_txn[0], commitment_tx[0]);
2862         check_spends!(node_txn[1], commitment_tx[0]);
2863         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2864         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2865         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2866         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2867         assert_eq!(node_txn[0].lock_time, LockTime::ZERO);
2868         assert_eq!(node_txn[1].lock_time, LockTime::ZERO);
2869
2870         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2871         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()]));
2872         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2873         {
2874                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2875                 assert_eq!(added_monitors.len(), 1);
2876                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2877                 added_monitors.clear();
2878         }
2879         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2880         assert_eq!(forwarded_events.len(), 3);
2881         match forwarded_events[0] {
2882                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2883                 _ => panic!("Unexpected event"),
2884         }
2885         let chan_id = Some(chan_1.2);
2886         match forwarded_events[1] {
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         match forwarded_events[2] {
2897                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2898                         assert_eq!(fee_earned_msat, Some(1000));
2899                         assert_eq!(prev_channel_id, chan_id);
2900                         assert_eq!(claim_from_onchain_tx, true);
2901                         assert_eq!(next_channel_id, Some(chan_2.2));
2902                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2903                 },
2904                 _ => panic!()
2905         }
2906         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2907         {
2908                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2909                 assert_eq!(added_monitors.len(), 2);
2910                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2911                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2912                 added_monitors.clear();
2913         }
2914         assert_eq!(events.len(), 3);
2915
2916         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2917         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2918
2919         match nodes_2_event {
2920                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2921                 _ => panic!("Unexpected event"),
2922         }
2923
2924         match nodes_0_event {
2925                 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, .. } } => {
2926                         assert!(update_add_htlcs.is_empty());
2927                         assert!(update_fail_htlcs.is_empty());
2928                         assert_eq!(update_fulfill_htlcs.len(), 1);
2929                         assert!(update_fail_malformed_htlcs.is_empty());
2930                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2931                 },
2932                 _ => panic!("Unexpected event"),
2933         };
2934
2935         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2936         match events[0] {
2937                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2938                 _ => panic!("Unexpected event"),
2939         }
2940
2941         macro_rules! check_tx_local_broadcast {
2942                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2943                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2944                         assert_eq!(node_txn.len(), 2);
2945                         // Node[1]: 2 * HTLC-timeout tx
2946                         // Node[0]: 2 * HTLC-timeout tx
2947                         check_spends!(node_txn[0], $commitment_tx);
2948                         check_spends!(node_txn[1], $commitment_tx);
2949                         assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2950                         assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2951                         if $htlc_offered {
2952                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2953                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2954                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2955                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2956                         } else {
2957                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2958                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2959                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2960                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2961                         }
2962                         node_txn.clear();
2963                 } }
2964         }
2965         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2966         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2967
2968         // Broadcast legit commitment tx from A on B's chain
2969         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2970         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2971         check_spends!(node_a_commitment_tx[0], chan_1.3);
2972         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2973         check_closed_broadcast!(nodes[1], true);
2974         check_added_monitors!(nodes[1], 1);
2975         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2976         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2977         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2978         let commitment_spend =
2979                 if node_txn.len() == 1 {
2980                         &node_txn[0]
2981                 } else {
2982                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2983                         // FullBlockViaListen
2984                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2985                                 check_spends!(node_txn[1], commitment_tx[0]);
2986                                 check_spends!(node_txn[2], commitment_tx[0]);
2987                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2988                                 &node_txn[0]
2989                         } else {
2990                                 check_spends!(node_txn[0], commitment_tx[0]);
2991                                 check_spends!(node_txn[1], commitment_tx[0]);
2992                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2993                                 &node_txn[2]
2994                         }
2995                 };
2996
2997         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2998         assert_eq!(commitment_spend.input.len(), 2);
2999         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3000         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3001         assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3002         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3003         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3004         // we already checked the same situation with A.
3005
3006         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3007         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3008         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3009         check_closed_broadcast!(nodes[0], true);
3010         check_added_monitors!(nodes[0], 1);
3011         let events = nodes[0].node.get_and_clear_pending_events();
3012         assert_eq!(events.len(), 5);
3013         let mut first_claimed = false;
3014         for event in events {
3015                 match event {
3016                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3017                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3018                                         assert!(!first_claimed);
3019                                         first_claimed = true;
3020                                 } else {
3021                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3022                                         assert_eq!(payment_hash, payment_hash_2);
3023                                 }
3024                         },
3025                         Event::PaymentPathSuccessful { .. } => {},
3026                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3027                         _ => panic!("Unexpected event"),
3028                 }
3029         }
3030         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3031 }
3032
3033 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3034         // Test that in case of a unilateral close onchain, we detect the state of output and
3035         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3036         // broadcasting the right event to other nodes in payment path.
3037         // A ------------------> B ----------------------> C (timeout)
3038         //    B's commitment tx                 C's commitment tx
3039         //            \                                  \
3040         //         B's HTLC timeout tx               B's timeout tx
3041
3042         let chanmon_cfgs = create_chanmon_cfgs(3);
3043         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3044         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3045         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3046         *nodes[0].connect_style.borrow_mut() = connect_style;
3047         *nodes[1].connect_style.borrow_mut() = connect_style;
3048         *nodes[2].connect_style.borrow_mut() = connect_style;
3049
3050         // Create some intial channels
3051         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3052         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3053
3054         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3055         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3056         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3057
3058         let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3059
3060         // Broadcast legit commitment tx from C on B's chain
3061         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3062         check_spends!(commitment_tx[0], chan_2.3);
3063         nodes[2].node.fail_htlc_backwards(&payment_hash);
3064         check_added_monitors!(nodes[2], 0);
3065         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3066         check_added_monitors!(nodes[2], 1);
3067
3068         let events = nodes[2].node.get_and_clear_pending_msg_events();
3069         assert_eq!(events.len(), 1);
3070         match events[0] {
3071                 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, .. } } => {
3072                         assert!(update_add_htlcs.is_empty());
3073                         assert!(!update_fail_htlcs.is_empty());
3074                         assert!(update_fulfill_htlcs.is_empty());
3075                         assert!(update_fail_malformed_htlcs.is_empty());
3076                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3077                 },
3078                 _ => panic!("Unexpected event"),
3079         };
3080         mine_transaction(&nodes[2], &commitment_tx[0]);
3081         check_closed_broadcast!(nodes[2], true);
3082         check_added_monitors!(nodes[2], 1);
3083         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3084         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3085         assert_eq!(node_txn.len(), 0);
3086
3087         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3088         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3089         mine_transaction(&nodes[1], &commitment_tx[0]);
3090         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3091                 , [nodes[2].node.get_our_node_id()], 100000);
3092         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3093         let timeout_tx = {
3094                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3095                 if nodes[1].connect_style.borrow().skips_blocks() {
3096                         assert_eq!(txn.len(), 1);
3097                 } else {
3098                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3099                 }
3100                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3101                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3102                 txn.remove(0)
3103         };
3104
3105         mine_transaction(&nodes[1], &timeout_tx);
3106         check_added_monitors!(nodes[1], 1);
3107         check_closed_broadcast!(nodes[1], true);
3108
3109         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3110
3111         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 }]);
3112         check_added_monitors!(nodes[1], 1);
3113         let events = nodes[1].node.get_and_clear_pending_msg_events();
3114         assert_eq!(events.len(), 1);
3115         match events[0] {
3116                 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, .. } } => {
3117                         assert!(update_add_htlcs.is_empty());
3118                         assert!(!update_fail_htlcs.is_empty());
3119                         assert!(update_fulfill_htlcs.is_empty());
3120                         assert!(update_fail_malformed_htlcs.is_empty());
3121                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3122                 },
3123                 _ => panic!("Unexpected event"),
3124         };
3125
3126         // Broadcast legit commitment tx from B on A's chain
3127         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3128         check_spends!(commitment_tx[0], chan_1.3);
3129
3130         mine_transaction(&nodes[0], &commitment_tx[0]);
3131         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3132
3133         check_closed_broadcast!(nodes[0], true);
3134         check_added_monitors!(nodes[0], 1);
3135         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3136         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3137         assert_eq!(node_txn.len(), 1);
3138         check_spends!(node_txn[0], commitment_tx[0]);
3139         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3140 }
3141
3142 #[test]
3143 fn test_htlc_on_chain_timeout() {
3144         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3145         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3146         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3147 }
3148
3149 #[test]
3150 fn test_simple_commitment_revoked_fail_backward() {
3151         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3152         // and fail backward accordingly.
3153
3154         let chanmon_cfgs = create_chanmon_cfgs(3);
3155         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3156         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3157         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3158
3159         // Create some initial channels
3160         create_announced_chan_between_nodes(&nodes, 0, 1);
3161         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3162
3163         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3164         // Get the will-be-revoked local txn from nodes[2]
3165         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3166         // Revoke the old state
3167         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3168
3169         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3170
3171         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3172         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3173         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3174         check_added_monitors!(nodes[1], 1);
3175         check_closed_broadcast!(nodes[1], true);
3176
3177         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 }]);
3178         check_added_monitors!(nodes[1], 1);
3179         let events = nodes[1].node.get_and_clear_pending_msg_events();
3180         assert_eq!(events.len(), 1);
3181         match events[0] {
3182                 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, .. } } => {
3183                         assert!(update_add_htlcs.is_empty());
3184                         assert_eq!(update_fail_htlcs.len(), 1);
3185                         assert!(update_fulfill_htlcs.is_empty());
3186                         assert!(update_fail_malformed_htlcs.is_empty());
3187                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3188
3189                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3190                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3191                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3192                 },
3193                 _ => panic!("Unexpected event"),
3194         }
3195 }
3196
3197 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3198         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3199         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3200         // commitment transaction anymore.
3201         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3202         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3203         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3204         // technically disallowed and we should probably handle it reasonably.
3205         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3206         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3207         // transactions:
3208         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3209         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3210         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3211         //   and once they revoke the previous commitment transaction (allowing us to send a new
3212         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3213         let chanmon_cfgs = create_chanmon_cfgs(3);
3214         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3215         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3216         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3217
3218         // Create some initial channels
3219         create_announced_chan_between_nodes(&nodes, 0, 1);
3220         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3221
3222         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3223         // Get the will-be-revoked local txn from nodes[2]
3224         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3225         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3226         // Revoke the old state
3227         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3228
3229         let value = if use_dust {
3230                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3231                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3232                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3233                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3234         } else { 3000000 };
3235
3236         let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3237         let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3238         let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3239
3240         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3241         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3242         check_added_monitors!(nodes[2], 1);
3243         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3244         assert!(updates.update_add_htlcs.is_empty());
3245         assert!(updates.update_fulfill_htlcs.is_empty());
3246         assert!(updates.update_fail_malformed_htlcs.is_empty());
3247         assert_eq!(updates.update_fail_htlcs.len(), 1);
3248         assert!(updates.update_fee.is_none());
3249         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3250         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3251         // Drop the last RAA from 3 -> 2
3252
3253         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3254         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3255         check_added_monitors!(nodes[2], 1);
3256         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3257         assert!(updates.update_add_htlcs.is_empty());
3258         assert!(updates.update_fulfill_htlcs.is_empty());
3259         assert!(updates.update_fail_malformed_htlcs.is_empty());
3260         assert_eq!(updates.update_fail_htlcs.len(), 1);
3261         assert!(updates.update_fee.is_none());
3262         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3263         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3264         check_added_monitors!(nodes[1], 1);
3265         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3266         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3267         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3268         check_added_monitors!(nodes[2], 1);
3269
3270         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3271         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3272         check_added_monitors!(nodes[2], 1);
3273         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3274         assert!(updates.update_add_htlcs.is_empty());
3275         assert!(updates.update_fulfill_htlcs.is_empty());
3276         assert!(updates.update_fail_malformed_htlcs.is_empty());
3277         assert_eq!(updates.update_fail_htlcs.len(), 1);
3278         assert!(updates.update_fee.is_none());
3279         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3280         // At this point first_payment_hash has dropped out of the latest two commitment
3281         // transactions that nodes[1] is tracking...
3282         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3283         check_added_monitors!(nodes[1], 1);
3284         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3285         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3286         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3287         check_added_monitors!(nodes[2], 1);
3288
3289         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3290         // on nodes[2]'s RAA.
3291         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3292         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3293                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3294         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3295         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3296         check_added_monitors!(nodes[1], 0);
3297
3298         if deliver_bs_raa {
3299                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3300                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3301                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3302                 check_added_monitors!(nodes[1], 1);
3303                 let events = nodes[1].node.get_and_clear_pending_events();
3304                 assert_eq!(events.len(), 2);
3305                 match events[0] {
3306                         Event::PendingHTLCsForwardable { .. } => { },
3307                         _ => panic!("Unexpected event"),
3308                 };
3309                 match events[1] {
3310                         Event::HTLCHandlingFailed { .. } => { },
3311                         _ => panic!("Unexpected event"),
3312                 }
3313                 // Deliberately don't process the pending fail-back so they all fail back at once after
3314                 // block connection just like the !deliver_bs_raa case
3315         }
3316
3317         let mut failed_htlcs = HashSet::new();
3318         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3319
3320         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3321         check_added_monitors!(nodes[1], 1);
3322         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3323
3324         let events = nodes[1].node.get_and_clear_pending_events();
3325         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3326         match events[0] {
3327                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3328                 _ => panic!("Unexepected event"),
3329         }
3330         match events[1] {
3331                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3332                         assert_eq!(*payment_hash, fourth_payment_hash);
3333                 },
3334                 _ => panic!("Unexpected event"),
3335         }
3336         match events[2] {
3337                 Event::PaymentFailed { ref payment_hash, .. } => {
3338                         assert_eq!(*payment_hash, fourth_payment_hash);
3339                 },
3340                 _ => panic!("Unexpected event"),
3341         }
3342
3343         nodes[1].node.process_pending_htlc_forwards();
3344         check_added_monitors!(nodes[1], 1);
3345
3346         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3347         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3348
3349         if deliver_bs_raa {
3350                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3351                 match nodes_2_event {
3352                         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, .. } } => {
3353                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3354                                 assert_eq!(update_add_htlcs.len(), 1);
3355                                 assert!(update_fulfill_htlcs.is_empty());
3356                                 assert!(update_fail_htlcs.is_empty());
3357                                 assert!(update_fail_malformed_htlcs.is_empty());
3358                         },
3359                         _ => panic!("Unexpected event"),
3360                 }
3361         }
3362
3363         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3364         match nodes_2_event {
3365                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3366                         assert_eq!(channel_id, chan_2.2);
3367                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3368                 },
3369                 _ => panic!("Unexpected event"),
3370         }
3371
3372         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3373         match nodes_0_event {
3374                 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, .. } } => {
3375                         assert!(update_add_htlcs.is_empty());
3376                         assert_eq!(update_fail_htlcs.len(), 3);
3377                         assert!(update_fulfill_htlcs.is_empty());
3378                         assert!(update_fail_malformed_htlcs.is_empty());
3379                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3380
3381                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3382                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3383                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3384
3385                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3386
3387                         let events = nodes[0].node.get_and_clear_pending_events();
3388                         assert_eq!(events.len(), 6);
3389                         match events[0] {
3390                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3391                                         assert!(failed_htlcs.insert(payment_hash.0));
3392                                         // If we delivered B's RAA we got an unknown preimage error, not something
3393                                         // that we should update our routing table for.
3394                                         if !deliver_bs_raa {
3395                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3396                                         }
3397                                 },
3398                                 _ => panic!("Unexpected event"),
3399                         }
3400                         match events[1] {
3401                                 Event::PaymentFailed { ref payment_hash, .. } => {
3402                                         assert_eq!(*payment_hash, first_payment_hash);
3403                                 },
3404                                 _ => panic!("Unexpected event"),
3405                         }
3406                         match events[2] {
3407                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3408                                         assert!(failed_htlcs.insert(payment_hash.0));
3409                                 },
3410                                 _ => panic!("Unexpected event"),
3411                         }
3412                         match events[3] {
3413                                 Event::PaymentFailed { ref payment_hash, .. } => {
3414                                         assert_eq!(*payment_hash, second_payment_hash);
3415                                 },
3416                                 _ => panic!("Unexpected event"),
3417                         }
3418                         match events[4] {
3419                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3420                                         assert!(failed_htlcs.insert(payment_hash.0));
3421                                 },
3422                                 _ => panic!("Unexpected event"),
3423                         }
3424                         match events[5] {
3425                                 Event::PaymentFailed { ref payment_hash, .. } => {
3426                                         assert_eq!(*payment_hash, third_payment_hash);
3427                                 },
3428                                 _ => panic!("Unexpected event"),
3429                         }
3430                 },
3431                 _ => panic!("Unexpected event"),
3432         }
3433
3434         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3435         match events[0] {
3436                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3437                 _ => panic!("Unexpected event"),
3438         }
3439
3440         assert!(failed_htlcs.contains(&first_payment_hash.0));
3441         assert!(failed_htlcs.contains(&second_payment_hash.0));
3442         assert!(failed_htlcs.contains(&third_payment_hash.0));
3443 }
3444
3445 #[test]
3446 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3447         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3448         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3449         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3450         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3451 }
3452
3453 #[test]
3454 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3455         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3456         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3457         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3458         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3459 }
3460
3461 #[test]
3462 fn fail_backward_pending_htlc_upon_channel_failure() {
3463         let chanmon_cfgs = create_chanmon_cfgs(2);
3464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3466         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3467         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3468
3469         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3470         {
3471                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3472                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3473                         PaymentId(payment_hash.0)).unwrap();
3474                 check_added_monitors!(nodes[0], 1);
3475
3476                 let payment_event = {
3477                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3478                         assert_eq!(events.len(), 1);
3479                         SendEvent::from_event(events.remove(0))
3480                 };
3481                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3482                 assert_eq!(payment_event.msgs.len(), 1);
3483         }
3484
3485         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3486         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3487         {
3488                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3489                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3490                 check_added_monitors!(nodes[0], 0);
3491
3492                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3493         }
3494
3495         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3496         {
3497                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3498
3499                 let secp_ctx = Secp256k1::new();
3500                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3501                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3502                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3503                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3504                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3505                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3506
3507                 // Send a 0-msat update_add_htlc to fail the channel.
3508                 let update_add_htlc = msgs::UpdateAddHTLC {
3509                         channel_id: chan.2,
3510                         htlc_id: 0,
3511                         amount_msat: 0,
3512                         payment_hash,
3513                         cltv_expiry,
3514                         onion_routing_packet,
3515                         skimmed_fee_msat: None,
3516                         blinding_point: None,
3517                 };
3518                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3519         }
3520         let events = nodes[0].node.get_and_clear_pending_events();
3521         assert_eq!(events.len(), 3);
3522         // Check that Alice fails backward the pending HTLC from the second payment.
3523         match events[0] {
3524                 Event::PaymentPathFailed { payment_hash, .. } => {
3525                         assert_eq!(payment_hash, failed_payment_hash);
3526                 },
3527                 _ => panic!("Unexpected event"),
3528         }
3529         match events[1] {
3530                 Event::PaymentFailed { payment_hash, .. } => {
3531                         assert_eq!(payment_hash, failed_payment_hash);
3532                 },
3533                 _ => panic!("Unexpected event"),
3534         }
3535         match events[2] {
3536                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3537                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3538                 },
3539                 _ => panic!("Unexpected event {:?}", events[1]),
3540         }
3541         check_closed_broadcast!(nodes[0], true);
3542         check_added_monitors!(nodes[0], 1);
3543 }
3544
3545 #[test]
3546 fn test_htlc_ignore_latest_remote_commitment() {
3547         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3548         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3549         let chanmon_cfgs = create_chanmon_cfgs(2);
3550         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3551         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3552         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3553         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3554                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3555                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3556                 // connect_style.
3557                 return;
3558         }
3559         create_announced_chan_between_nodes(&nodes, 0, 1);
3560
3561         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3562         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3563         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3564         check_closed_broadcast!(nodes[0], true);
3565         check_added_monitors!(nodes[0], 1);
3566         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3567
3568         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3569         assert_eq!(node_txn.len(), 3);
3570         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3571
3572         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3573         connect_block(&nodes[1], &block);
3574         check_closed_broadcast!(nodes[1], true);
3575         check_added_monitors!(nodes[1], 1);
3576         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3577
3578         // Duplicate the connect_block call since this may happen due to other listeners
3579         // registering new transactions
3580         connect_block(&nodes[1], &block);
3581 }
3582
3583 #[test]
3584 fn test_force_close_fail_back() {
3585         // Check which HTLCs are failed-backwards on channel force-closure
3586         let chanmon_cfgs = create_chanmon_cfgs(3);
3587         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3588         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3589         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3590         create_announced_chan_between_nodes(&nodes, 0, 1);
3591         create_announced_chan_between_nodes(&nodes, 1, 2);
3592
3593         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3594
3595         let mut payment_event = {
3596                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3597                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3598                 check_added_monitors!(nodes[0], 1);
3599
3600                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3601                 assert_eq!(events.len(), 1);
3602                 SendEvent::from_event(events.remove(0))
3603         };
3604
3605         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3606         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3607
3608         expect_pending_htlcs_forwardable!(nodes[1]);
3609
3610         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3611         assert_eq!(events_2.len(), 1);
3612         payment_event = SendEvent::from_event(events_2.remove(0));
3613         assert_eq!(payment_event.msgs.len(), 1);
3614
3615         check_added_monitors!(nodes[1], 1);
3616         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3617         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3618         check_added_monitors!(nodes[2], 1);
3619         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3620
3621         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3622         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3623         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3624
3625         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3626         check_closed_broadcast!(nodes[2], true);
3627         check_added_monitors!(nodes[2], 1);
3628         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3629         let tx = {
3630                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3631                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3632                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3633                 // back to nodes[1] upon timeout otherwise.
3634                 assert_eq!(node_txn.len(), 1);
3635                 node_txn.remove(0)
3636         };
3637
3638         mine_transaction(&nodes[1], &tx);
3639
3640         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3641         check_closed_broadcast!(nodes[1], true);
3642         check_added_monitors!(nodes[1], 1);
3643         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3644
3645         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3646         {
3647                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3648                         .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);
3649         }
3650         mine_transaction(&nodes[2], &tx);
3651         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3652         assert_eq!(node_txn.len(), 1);
3653         assert_eq!(node_txn[0].input.len(), 1);
3654         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3655         assert_eq!(node_txn[0].lock_time, LockTime::ZERO); // Must be an HTLC-Success
3656         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3657
3658         check_spends!(node_txn[0], tx);
3659 }
3660
3661 #[test]
3662 fn test_dup_events_on_peer_disconnect() {
3663         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3664         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3665         // as we used to generate the event immediately upon receipt of the payment preimage in the
3666         // update_fulfill_htlc message.
3667
3668         let chanmon_cfgs = create_chanmon_cfgs(2);
3669         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3670         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3671         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3672         create_announced_chan_between_nodes(&nodes, 0, 1);
3673
3674         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3675
3676         nodes[1].node.claim_funds(payment_preimage);
3677         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3678         check_added_monitors!(nodes[1], 1);
3679         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3680         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3681         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3682
3683         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3684         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3685
3686         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3687         reconnect_args.pending_htlc_claims.0 = 1;
3688         reconnect_nodes(reconnect_args);
3689         expect_payment_path_successful!(nodes[0]);
3690 }
3691
3692 #[test]
3693 fn test_peer_disconnected_before_funding_broadcasted() {
3694         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3695         // before the funding transaction has been broadcasted.
3696         let chanmon_cfgs = create_chanmon_cfgs(2);
3697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3699         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3700
3701         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3702         // broadcasted, even though it's created by `nodes[0]`.
3703         let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
3704         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3705         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3706         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3707         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3708
3709         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3710         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3711
3712         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3713
3714         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3715         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3716
3717         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3718         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3719         // broadcasted.
3720         {
3721                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3722         }
3723
3724         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3725         // disconnected before the funding transaction was broadcasted.
3726         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3727         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3728
3729         check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3730                 , [nodes[1].node.get_our_node_id()], 1000000);
3731         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3732                 , [nodes[0].node.get_our_node_id()], 1000000);
3733 }
3734
3735 #[test]
3736 fn test_simple_peer_disconnect() {
3737         // Test that we can reconnect when there are no lost messages
3738         let chanmon_cfgs = create_chanmon_cfgs(3);
3739         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3740         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3741         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3742         create_announced_chan_between_nodes(&nodes, 0, 1);
3743         create_announced_chan_between_nodes(&nodes, 1, 2);
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         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3748         reconnect_args.send_channel_ready = (true, true);
3749         reconnect_nodes(reconnect_args);
3750
3751         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3752         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3753         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3754         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3755
3756         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3757         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3758         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3759
3760         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3761         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3762         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3763         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3764
3765         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3766         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3767
3768         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3769         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3770
3771         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3772         reconnect_args.pending_cell_htlc_fails.0 = 1;
3773         reconnect_args.pending_cell_htlc_claims.0 = 1;
3774         reconnect_nodes(reconnect_args);
3775         {
3776                 let events = nodes[0].node.get_and_clear_pending_events();
3777                 assert_eq!(events.len(), 4);
3778                 match events[0] {
3779                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3780                                 assert_eq!(payment_preimage, payment_preimage_3);
3781                                 assert_eq!(payment_hash, payment_hash_3);
3782                         },
3783                         _ => panic!("Unexpected event"),
3784                 }
3785                 match events[1] {
3786                         Event::PaymentPathSuccessful { .. } => {},
3787                         _ => panic!("Unexpected event"),
3788                 }
3789                 match events[2] {
3790                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3791                                 assert_eq!(payment_hash, payment_hash_5);
3792                                 assert!(payment_failed_permanently);
3793                         },
3794                         _ => panic!("Unexpected event"),
3795                 }
3796                 match events[3] {
3797                         Event::PaymentFailed { payment_hash, .. } => {
3798                                 assert_eq!(payment_hash, payment_hash_5);
3799                         },
3800                         _ => panic!("Unexpected event"),
3801                 }
3802         }
3803         check_added_monitors(&nodes[0], 1);
3804
3805         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3806         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3807 }
3808
3809 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3810         // Test that we can reconnect when in-flight HTLC updates get dropped
3811         let chanmon_cfgs = create_chanmon_cfgs(2);
3812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3814         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3815
3816         let mut as_channel_ready = None;
3817         let channel_id = if messages_delivered == 0 {
3818                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3819                 as_channel_ready = Some(channel_ready);
3820                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3821                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3822                 // it before the channel_reestablish message.
3823                 chan_id
3824         } else {
3825                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3826         };
3827
3828         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3829
3830         let payment_event = {
3831                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3832                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3833                 check_added_monitors!(nodes[0], 1);
3834
3835                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3836                 assert_eq!(events.len(), 1);
3837                 SendEvent::from_event(events.remove(0))
3838         };
3839         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3840
3841         if messages_delivered < 2 {
3842                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3843         } else {
3844                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3845                 if messages_delivered >= 3 {
3846                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3847                         check_added_monitors!(nodes[1], 1);
3848                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3849
3850                         if messages_delivered >= 4 {
3851                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3852                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3853                                 check_added_monitors!(nodes[0], 1);
3854
3855                                 if messages_delivered >= 5 {
3856                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3857                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3858                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3859                                         check_added_monitors!(nodes[0], 1);
3860
3861                                         if messages_delivered >= 6 {
3862                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3863                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3864                                                 check_added_monitors!(nodes[1], 1);
3865                                         }
3866                                 }
3867                         }
3868                 }
3869         }
3870
3871         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3872         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3873         if messages_delivered < 3 {
3874                 if simulate_broken_lnd {
3875                         // lnd has a long-standing bug where they send a channel_ready prior to a
3876                         // channel_reestablish if you reconnect prior to channel_ready time.
3877                         //
3878                         // Here we simulate that behavior, delivering a channel_ready immediately on
3879                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3880                         // in `reconnect_nodes` but we currently don't fail based on that.
3881                         //
3882                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3883                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3884                 }
3885                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3886                 // received on either side, both sides will need to resend them.
3887                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3888                 reconnect_args.send_channel_ready = (true, true);
3889                 reconnect_args.pending_htlc_adds.1 = 1;
3890                 reconnect_nodes(reconnect_args);
3891         } else if messages_delivered == 3 {
3892                 // nodes[0] still wants its RAA + commitment_signed
3893                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3894                 reconnect_args.pending_responding_commitment_signed.0 = true;
3895                 reconnect_args.pending_raa.0 = true;
3896                 reconnect_nodes(reconnect_args);
3897         } else if messages_delivered == 4 {
3898                 // nodes[0] still wants its commitment_signed
3899                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3900                 reconnect_args.pending_responding_commitment_signed.0 = true;
3901                 reconnect_nodes(reconnect_args);
3902         } else if messages_delivered == 5 {
3903                 // nodes[1] still wants its final RAA
3904                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3905                 reconnect_args.pending_raa.1 = true;
3906                 reconnect_nodes(reconnect_args);
3907         } else if messages_delivered == 6 {
3908                 // Everything was delivered...
3909                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3910         }
3911
3912         let events_1 = nodes[1].node.get_and_clear_pending_events();
3913         if messages_delivered == 0 {
3914                 assert_eq!(events_1.len(), 2);
3915                 match events_1[0] {
3916                         Event::ChannelReady { .. } => { },
3917                         _ => panic!("Unexpected event"),
3918                 };
3919                 match events_1[1] {
3920                         Event::PendingHTLCsForwardable { .. } => { },
3921                         _ => panic!("Unexpected event"),
3922                 };
3923         } else {
3924                 assert_eq!(events_1.len(), 1);
3925                 match events_1[0] {
3926                         Event::PendingHTLCsForwardable { .. } => { },
3927                         _ => panic!("Unexpected event"),
3928                 };
3929         }
3930
3931         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3932         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3933         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3934
3935         nodes[1].node.process_pending_htlc_forwards();
3936
3937         let events_2 = nodes[1].node.get_and_clear_pending_events();
3938         assert_eq!(events_2.len(), 1);
3939         match events_2[0] {
3940                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3941                         assert_eq!(payment_hash_1, *payment_hash);
3942                         assert_eq!(amount_msat, 1_000_000);
3943                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3944                         assert_eq!(via_channel_id, Some(channel_id));
3945                         match &purpose {
3946                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3947                                         assert!(payment_preimage.is_none());
3948                                         assert_eq!(payment_secret_1, *payment_secret);
3949                                 },
3950                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3951                         }
3952                 },
3953                 _ => panic!("Unexpected event"),
3954         }
3955
3956         nodes[1].node.claim_funds(payment_preimage_1);
3957         check_added_monitors!(nodes[1], 1);
3958         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3959
3960         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3961         assert_eq!(events_3.len(), 1);
3962         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3963                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3964                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3965                         assert!(updates.update_add_htlcs.is_empty());
3966                         assert!(updates.update_fail_htlcs.is_empty());
3967                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3968                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3969                         assert!(updates.update_fee.is_none());
3970                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3971                 },
3972                 _ => panic!("Unexpected event"),
3973         };
3974
3975         if messages_delivered >= 1 {
3976                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3977
3978                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3979                 assert_eq!(events_4.len(), 1);
3980                 match events_4[0] {
3981                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3982                                 assert_eq!(payment_preimage_1, *payment_preimage);
3983                                 assert_eq!(payment_hash_1, *payment_hash);
3984                         },
3985                         _ => panic!("Unexpected event"),
3986                 }
3987
3988                 if messages_delivered >= 2 {
3989                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3990                         check_added_monitors!(nodes[0], 1);
3991                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3992
3993                         if messages_delivered >= 3 {
3994                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3995                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3996                                 check_added_monitors!(nodes[1], 1);
3997
3998                                 if messages_delivered >= 4 {
3999                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4000                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4001                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4002                                         check_added_monitors!(nodes[1], 1);
4003
4004                                         if messages_delivered >= 5 {
4005                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4006                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4007                                                 check_added_monitors!(nodes[0], 1);
4008                                         }
4009                                 }
4010                         }
4011                 }
4012         }
4013
4014         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4015         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4016         if messages_delivered < 2 {
4017                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4018                 reconnect_args.pending_htlc_claims.0 = 1;
4019                 reconnect_nodes(reconnect_args);
4020                 if messages_delivered < 1 {
4021                         expect_payment_sent!(nodes[0], payment_preimage_1);
4022                 } else {
4023                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4024                 }
4025         } else if messages_delivered == 2 {
4026                 // nodes[0] still wants its RAA + commitment_signed
4027                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4028                 reconnect_args.pending_responding_commitment_signed.1 = true;
4029                 reconnect_args.pending_raa.1 = true;
4030                 reconnect_nodes(reconnect_args);
4031         } else if messages_delivered == 3 {
4032                 // nodes[0] still wants its commitment_signed
4033                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4034                 reconnect_args.pending_responding_commitment_signed.1 = true;
4035                 reconnect_nodes(reconnect_args);
4036         } else if messages_delivered == 4 {
4037                 // nodes[1] still wants its final RAA
4038                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4039                 reconnect_args.pending_raa.0 = true;
4040                 reconnect_nodes(reconnect_args);
4041         } else if messages_delivered == 5 {
4042                 // Everything was delivered...
4043                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4044         }
4045
4046         if messages_delivered == 1 || messages_delivered == 2 {
4047                 expect_payment_path_successful!(nodes[0]);
4048         }
4049         if messages_delivered <= 5 {
4050                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4051                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4052         }
4053         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4054
4055         if messages_delivered > 2 {
4056                 expect_payment_path_successful!(nodes[0]);
4057         }
4058
4059         // Channel should still work fine...
4060         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4061         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4062         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4063 }
4064
4065 #[test]
4066 fn test_drop_messages_peer_disconnect_a() {
4067         do_test_drop_messages_peer_disconnect(0, true);
4068         do_test_drop_messages_peer_disconnect(0, false);
4069         do_test_drop_messages_peer_disconnect(1, false);
4070         do_test_drop_messages_peer_disconnect(2, false);
4071 }
4072
4073 #[test]
4074 fn test_drop_messages_peer_disconnect_b() {
4075         do_test_drop_messages_peer_disconnect(3, false);
4076         do_test_drop_messages_peer_disconnect(4, false);
4077         do_test_drop_messages_peer_disconnect(5, false);
4078         do_test_drop_messages_peer_disconnect(6, false);
4079 }
4080
4081 #[test]
4082 fn test_channel_ready_without_best_block_updated() {
4083         // Previously, if we were offline when a funding transaction was locked in, and then we came
4084         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4085         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4086         // channel_ready immediately instead.
4087         let chanmon_cfgs = create_chanmon_cfgs(2);
4088         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4089         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4090         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4091         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4092
4093         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4094
4095         let conf_height = nodes[0].best_block_info().1 + 1;
4096         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4097         let block_txn = [funding_tx];
4098         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4099         let conf_block_header = nodes[0].get_block_header(conf_height);
4100         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4101
4102         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4103         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4104         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4105 }
4106
4107 #[test]
4108 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4109         let chanmon_cfgs = create_chanmon_cfgs(2);
4110         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4111         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4112         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4113
4114         // Let channel_manager get ahead of chain_monitor by 1 block.
4115         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4116         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4117         let height_1 = nodes[0].best_block_info().1 + 1;
4118         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4119
4120         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4121         nodes[0].node.block_connected(&block_1, height_1);
4122
4123         // Create channel, and it gets added to chain_monitor in funding_created.
4124         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4125
4126         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4127         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4128         // was running ahead of chain_monitor at the time of funding_created.
4129         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4130         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4131         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4132         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4133
4134         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4135         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4136         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4137 }
4138
4139 #[test]
4140 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4141         let chanmon_cfgs = create_chanmon_cfgs(2);
4142         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4143         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4144         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4145
4146         // Let chain_monitor get ahead of channel_manager by 1 block.
4147         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4148         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4149         let height_1 = nodes[0].best_block_info().1 + 1;
4150         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4151
4152         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4153         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4154
4155         // Create channel, and it gets added to chain_monitor in funding_created.
4156         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4157
4158         // channel_manager can't really skip block_1, it should get it eventually.
4159         nodes[0].node.block_connected(&block_1, height_1);
4160
4161         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4162         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4163         // running behind at the time of funding_created.
4164         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4165         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4166         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4167         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4168
4169         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4170         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4171         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4172 }
4173
4174 #[test]
4175 fn test_drop_messages_peer_disconnect_dual_htlc() {
4176         // Test that we can handle reconnecting when both sides of a channel have pending
4177         // commitment_updates when we disconnect.
4178         let chanmon_cfgs = create_chanmon_cfgs(2);
4179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4181         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4182         create_announced_chan_between_nodes(&nodes, 0, 1);
4183
4184         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4185
4186         // Now try to send a second payment which will fail to send
4187         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4188         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4189                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4190         check_added_monitors!(nodes[0], 1);
4191
4192         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4193         assert_eq!(events_1.len(), 1);
4194         match events_1[0] {
4195                 MessageSendEvent::UpdateHTLCs { .. } => {},
4196                 _ => panic!("Unexpected event"),
4197         }
4198
4199         nodes[1].node.claim_funds(payment_preimage_1);
4200         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4201         check_added_monitors!(nodes[1], 1);
4202
4203         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4204         assert_eq!(events_2.len(), 1);
4205         match events_2[0] {
4206                 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 } } => {
4207                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4208                         assert!(update_add_htlcs.is_empty());
4209                         assert_eq!(update_fulfill_htlcs.len(), 1);
4210                         assert!(update_fail_htlcs.is_empty());
4211                         assert!(update_fail_malformed_htlcs.is_empty());
4212                         assert!(update_fee.is_none());
4213
4214                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4215                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4216                         assert_eq!(events_3.len(), 1);
4217                         match events_3[0] {
4218                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4219                                         assert_eq!(*payment_preimage, payment_preimage_1);
4220                                         assert_eq!(*payment_hash, payment_hash_1);
4221                                 },
4222                                 _ => panic!("Unexpected event"),
4223                         }
4224
4225                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4226                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4227                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4228                         check_added_monitors!(nodes[0], 1);
4229                 },
4230                 _ => panic!("Unexpected event"),
4231         }
4232
4233         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4234         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4235
4236         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4237                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4238         }, true).unwrap();
4239         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4240         assert_eq!(reestablish_1.len(), 1);
4241         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4242                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4243         }, false).unwrap();
4244         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4245         assert_eq!(reestablish_2.len(), 1);
4246
4247         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4248         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4249         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4250         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4251
4252         assert!(as_resp.0.is_none());
4253         assert!(bs_resp.0.is_none());
4254
4255         assert!(bs_resp.1.is_none());
4256         assert!(bs_resp.2.is_none());
4257
4258         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4259
4260         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4261         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4262         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4263         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4264         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4265         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4266         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4267         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4268         // No commitment_signed so get_event_msg's assert(len == 1) passes
4269         check_added_monitors!(nodes[1], 1);
4270
4271         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4272         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4273         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4274         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4275         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4276         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4277         assert!(bs_second_commitment_signed.update_fee.is_none());
4278         check_added_monitors!(nodes[1], 1);
4279
4280         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4281         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4282         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4283         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4284         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4285         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4286         assert!(as_commitment_signed.update_fee.is_none());
4287         check_added_monitors!(nodes[0], 1);
4288
4289         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4290         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4291         // No commitment_signed so get_event_msg's assert(len == 1) passes
4292         check_added_monitors!(nodes[0], 1);
4293
4294         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4295         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4296         // No commitment_signed so get_event_msg's assert(len == 1) passes
4297         check_added_monitors!(nodes[1], 1);
4298
4299         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4300         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4301         check_added_monitors!(nodes[1], 1);
4302
4303         expect_pending_htlcs_forwardable!(nodes[1]);
4304
4305         let events_5 = nodes[1].node.get_and_clear_pending_events();
4306         assert_eq!(events_5.len(), 1);
4307         match events_5[0] {
4308                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4309                         assert_eq!(payment_hash_2, *payment_hash);
4310                         match &purpose {
4311                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4312                                         assert!(payment_preimage.is_none());
4313                                         assert_eq!(payment_secret_2, *payment_secret);
4314                                 },
4315                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4316                         }
4317                 },
4318                 _ => panic!("Unexpected event"),
4319         }
4320
4321         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4322         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4323         check_added_monitors!(nodes[0], 1);
4324
4325         expect_payment_path_successful!(nodes[0]);
4326         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4327 }
4328
4329 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4330         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4331         // to avoid our counterparty failing the channel.
4332         let chanmon_cfgs = create_chanmon_cfgs(2);
4333         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4334         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4335         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4336
4337         create_announced_chan_between_nodes(&nodes, 0, 1);
4338
4339         let our_payment_hash = if send_partial_mpp {
4340                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4341                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4342                 // indicates there are more HTLCs coming.
4343                 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.
4344                 let payment_id = PaymentId([42; 32]);
4345                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4346                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4347                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4348                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4349                         &None, session_privs[0]).unwrap();
4350                 check_added_monitors!(nodes[0], 1);
4351                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4352                 assert_eq!(events.len(), 1);
4353                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4354                 // hop should *not* yet generate any PaymentClaimable event(s).
4355                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4356                 our_payment_hash
4357         } else {
4358                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4359         };
4360
4361         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4362         connect_block(&nodes[0], &block);
4363         connect_block(&nodes[1], &block);
4364         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4365         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4366                 block.header.prev_blockhash = block.block_hash();
4367                 connect_block(&nodes[0], &block);
4368                 connect_block(&nodes[1], &block);
4369         }
4370
4371         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4372
4373         check_added_monitors!(nodes[1], 1);
4374         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4375         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4376         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4377         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4378         assert!(htlc_timeout_updates.update_fee.is_none());
4379
4380         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4381         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4382         // 100_000 msat as u64, followed by the height at which we failed back above
4383         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4384         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4385         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4386 }
4387
4388 #[test]
4389 fn test_htlc_timeout() {
4390         do_test_htlc_timeout(true);
4391         do_test_htlc_timeout(false);
4392 }
4393
4394 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4395         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4396         let chanmon_cfgs = create_chanmon_cfgs(3);
4397         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4398         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4399         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4400         create_announced_chan_between_nodes(&nodes, 0, 1);
4401         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4402
4403         // Make sure all nodes are at the same starting height
4404         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4405         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4406         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4407
4408         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4409         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4410         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4411                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4412         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4413         check_added_monitors!(nodes[1], 1);
4414
4415         // Now attempt to route a second payment, which should be placed in the holding cell
4416         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4417         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4418         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4419                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4420         if forwarded_htlc {
4421                 check_added_monitors!(nodes[0], 1);
4422                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4423                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4424                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4425                 expect_pending_htlcs_forwardable!(nodes[1]);
4426         }
4427         check_added_monitors!(nodes[1], 0);
4428
4429         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4430         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4431         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4432         connect_blocks(&nodes[1], 1);
4433
4434         if forwarded_htlc {
4435                 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 }]);
4436                 check_added_monitors!(nodes[1], 1);
4437                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4438                 assert_eq!(fail_commit.len(), 1);
4439                 match fail_commit[0] {
4440                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4441                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4442                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4443                         },
4444                         _ => unreachable!(),
4445                 }
4446                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4447         } else {
4448                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4449         }
4450 }
4451
4452 #[test]
4453 fn test_holding_cell_htlc_add_timeouts() {
4454         do_test_holding_cell_htlc_add_timeouts(false);
4455         do_test_holding_cell_htlc_add_timeouts(true);
4456 }
4457
4458 macro_rules! check_spendable_outputs {
4459         ($node: expr, $keysinterface: expr) => {
4460                 {
4461                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4462                         let mut txn = Vec::new();
4463                         let mut all_outputs = Vec::new();
4464                         let secp_ctx = Secp256k1::new();
4465                         for event in events.drain(..) {
4466                                 match event {
4467                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4468                                                 for outp in outputs.drain(..) {
4469                                                         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());
4470                                                         all_outputs.push(outp);
4471                                                 }
4472                                         },
4473                                         _ => panic!("Unexpected event"),
4474                                 };
4475                         }
4476                         if all_outputs.len() > 1 {
4477                                 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) {
4478                                         txn.push(tx);
4479                                 }
4480                         }
4481                         txn
4482                 }
4483         }
4484 }
4485
4486 #[test]
4487 fn test_claim_sizeable_push_msat() {
4488         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4489         let chanmon_cfgs = create_chanmon_cfgs(2);
4490         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4491         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4492         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4493
4494         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4495         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4496         check_closed_broadcast!(nodes[1], true);
4497         check_added_monitors!(nodes[1], 1);
4498         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4499         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4500         assert_eq!(node_txn.len(), 1);
4501         check_spends!(node_txn[0], chan.3);
4502         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
4503
4504         mine_transaction(&nodes[1], &node_txn[0]);
4505         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4506
4507         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4508         assert_eq!(spend_txn.len(), 1);
4509         assert_eq!(spend_txn[0].input.len(), 1);
4510         check_spends!(spend_txn[0], node_txn[0]);
4511         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4512 }
4513
4514 #[test]
4515 fn test_claim_on_remote_sizeable_push_msat() {
4516         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4517         // to_remote output is encumbered by a P2WPKH
4518         let chanmon_cfgs = create_chanmon_cfgs(2);
4519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4521         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4522
4523         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4524         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4525         check_closed_broadcast!(nodes[0], true);
4526         check_added_monitors!(nodes[0], 1);
4527         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4528
4529         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4530         assert_eq!(node_txn.len(), 1);
4531         check_spends!(node_txn[0], chan.3);
4532         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
4533
4534         mine_transaction(&nodes[1], &node_txn[0]);
4535         check_closed_broadcast!(nodes[1], true);
4536         check_added_monitors!(nodes[1], 1);
4537         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4538         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4539
4540         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4541         assert_eq!(spend_txn.len(), 1);
4542         check_spends!(spend_txn[0], node_txn[0]);
4543 }
4544
4545 #[test]
4546 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4547         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4548         // to_remote output is encumbered by a P2WPKH
4549
4550         let chanmon_cfgs = create_chanmon_cfgs(2);
4551         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4552         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4553         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4554
4555         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4556         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4557         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4558         assert_eq!(revoked_local_txn[0].input.len(), 1);
4559         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4560
4561         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4562         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4563         check_closed_broadcast!(nodes[1], true);
4564         check_added_monitors!(nodes[1], 1);
4565         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4566
4567         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4568         mine_transaction(&nodes[1], &node_txn[0]);
4569         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4570
4571         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4572         assert_eq!(spend_txn.len(), 3);
4573         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4574         check_spends!(spend_txn[1], node_txn[0]);
4575         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4576 }
4577
4578 #[test]
4579 fn test_static_spendable_outputs_preimage_tx() {
4580         let chanmon_cfgs = create_chanmon_cfgs(2);
4581         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4582         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4583         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4584
4585         // Create some initial channels
4586         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4587
4588         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4589
4590         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4591         assert_eq!(commitment_tx[0].input.len(), 1);
4592         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4593
4594         // Settle A's commitment tx on B's chain
4595         nodes[1].node.claim_funds(payment_preimage);
4596         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4597         check_added_monitors!(nodes[1], 1);
4598         mine_transaction(&nodes[1], &commitment_tx[0]);
4599         check_added_monitors!(nodes[1], 1);
4600         let events = nodes[1].node.get_and_clear_pending_msg_events();
4601         match events[0] {
4602                 MessageSendEvent::UpdateHTLCs { .. } => {},
4603                 _ => panic!("Unexpected event"),
4604         }
4605         match events[1] {
4606                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4607                 _ => panic!("Unexepected event"),
4608         }
4609
4610         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4611         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4612         assert_eq!(node_txn.len(), 1);
4613         check_spends!(node_txn[0], commitment_tx[0]);
4614         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4615
4616         mine_transaction(&nodes[1], &node_txn[0]);
4617         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4618         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4619
4620         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4621         assert_eq!(spend_txn.len(), 1);
4622         check_spends!(spend_txn[0], node_txn[0]);
4623 }
4624
4625 #[test]
4626 fn test_static_spendable_outputs_timeout_tx() {
4627         let chanmon_cfgs = create_chanmon_cfgs(2);
4628         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4629         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4630         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4631
4632         // Create some initial channels
4633         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4634
4635         // Rebalance the network a bit by relaying one payment through all the channels ...
4636         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4637
4638         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4639
4640         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4641         assert_eq!(commitment_tx[0].input.len(), 1);
4642         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4643
4644         // Settle A's commitment tx on B' chain
4645         mine_transaction(&nodes[1], &commitment_tx[0]);
4646         check_added_monitors!(nodes[1], 1);
4647         let events = nodes[1].node.get_and_clear_pending_msg_events();
4648         match events[0] {
4649                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4650                 _ => panic!("Unexpected event"),
4651         }
4652         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4653
4654         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4655         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4656         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4657         check_spends!(node_txn[0],  commitment_tx[0].clone());
4658         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4659
4660         mine_transaction(&nodes[1], &node_txn[0]);
4661         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4662         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4663         expect_payment_failed!(nodes[1], our_payment_hash, false);
4664
4665         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4666         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4667         check_spends!(spend_txn[0], commitment_tx[0]);
4668         check_spends!(spend_txn[1], node_txn[0]);
4669         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4670 }
4671
4672 #[test]
4673 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4674         let chanmon_cfgs = create_chanmon_cfgs(2);
4675         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4676         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4677         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4678
4679         // Create some initial channels
4680         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4681
4682         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4683         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4684         assert_eq!(revoked_local_txn[0].input.len(), 1);
4685         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4686
4687         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4688
4689         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4690         check_closed_broadcast!(nodes[1], true);
4691         check_added_monitors!(nodes[1], 1);
4692         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4693
4694         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4695         assert_eq!(node_txn.len(), 1);
4696         assert_eq!(node_txn[0].input.len(), 2);
4697         check_spends!(node_txn[0], revoked_local_txn[0]);
4698
4699         mine_transaction(&nodes[1], &node_txn[0]);
4700         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4701
4702         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4703         assert_eq!(spend_txn.len(), 1);
4704         check_spends!(spend_txn[0], node_txn[0]);
4705 }
4706
4707 #[test]
4708 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4709         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4710         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4714
4715         // Create some initial channels
4716         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4717
4718         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4719         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4720         assert_eq!(revoked_local_txn[0].input.len(), 1);
4721         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4722
4723         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4724
4725         // A will generate HTLC-Timeout from revoked commitment tx
4726         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4727         check_closed_broadcast!(nodes[0], true);
4728         check_added_monitors!(nodes[0], 1);
4729         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4730         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4731
4732         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4733         assert_eq!(revoked_htlc_txn.len(), 1);
4734         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4735         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4736         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4737         assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4738
4739         // B will generate justice tx from A's revoked commitment/HTLC tx
4740         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4741         check_closed_broadcast!(nodes[1], true);
4742         check_added_monitors!(nodes[1], 1);
4743         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4744
4745         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4746         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4747         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4748         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4749         // transactions next...
4750         assert_eq!(node_txn[0].input.len(), 3);
4751         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4752
4753         assert_eq!(node_txn[1].input.len(), 2);
4754         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4755         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4756                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4757         } else {
4758                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4759                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4760         }
4761
4762         mine_transaction(&nodes[1], &node_txn[1]);
4763         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4764
4765         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4766         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4767         assert_eq!(spend_txn.len(), 1);
4768         assert_eq!(spend_txn[0].input.len(), 1);
4769         check_spends!(spend_txn[0], node_txn[1]);
4770 }
4771
4772 #[test]
4773 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4774         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4775         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4778         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4779
4780         // Create some initial channels
4781         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4782
4783         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4784         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4785         assert_eq!(revoked_local_txn[0].input.len(), 1);
4786         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4787
4788         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4789         assert_eq!(revoked_local_txn[0].output.len(), 2);
4790
4791         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4792
4793         // B will generate HTLC-Success from revoked commitment tx
4794         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4795         check_closed_broadcast!(nodes[1], true);
4796         check_added_monitors!(nodes[1], 1);
4797         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4798         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4799
4800         assert_eq!(revoked_htlc_txn.len(), 1);
4801         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4802         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4803         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4804
4805         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4806         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4807         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4808
4809         // A will generate justice tx from B's revoked commitment/HTLC tx
4810         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4811         check_closed_broadcast!(nodes[0], true);
4812         check_added_monitors!(nodes[0], 1);
4813         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4814
4815         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4816         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4817
4818         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4819         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4820         // transactions next...
4821         assert_eq!(node_txn[0].input.len(), 2);
4822         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4823         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4824                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4825         } else {
4826                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4827                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4828         }
4829
4830         assert_eq!(node_txn[1].input.len(), 1);
4831         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4832
4833         mine_transaction(&nodes[0], &node_txn[1]);
4834         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4835
4836         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4837         // didn't try to generate any new transactions.
4838
4839         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4840         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4841         assert_eq!(spend_txn.len(), 3);
4842         assert_eq!(spend_txn[0].input.len(), 1);
4843         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4844         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4845         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4846         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4847 }
4848
4849 #[test]
4850 fn test_onchain_to_onchain_claim() {
4851         // Test that in case of channel closure, we detect the state of output and claim HTLC
4852         // on downstream peer's remote commitment tx.
4853         // First, have C claim an HTLC against its own latest commitment transaction.
4854         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4855         // channel.
4856         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4857         // gets broadcast.
4858
4859         let chanmon_cfgs = create_chanmon_cfgs(3);
4860         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4861         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4862         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4863
4864         // Create some initial channels
4865         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4866         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4867
4868         // Ensure all nodes are at the same height
4869         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4870         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4871         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4872         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4873
4874         // Rebalance the network a bit by relaying one payment through all the channels ...
4875         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4876         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4877
4878         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4879         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4880         check_spends!(commitment_tx[0], chan_2.3);
4881         nodes[2].node.claim_funds(payment_preimage);
4882         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4883         check_added_monitors!(nodes[2], 1);
4884         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4885         assert!(updates.update_add_htlcs.is_empty());
4886         assert!(updates.update_fail_htlcs.is_empty());
4887         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4888         assert!(updates.update_fail_malformed_htlcs.is_empty());
4889
4890         mine_transaction(&nodes[2], &commitment_tx[0]);
4891         check_closed_broadcast!(nodes[2], true);
4892         check_added_monitors!(nodes[2], 1);
4893         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4894
4895         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4896         assert_eq!(c_txn.len(), 1);
4897         check_spends!(c_txn[0], commitment_tx[0]);
4898         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4899         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4900         assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4901
4902         // 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
4903         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4904         check_added_monitors!(nodes[1], 1);
4905         let events = nodes[1].node.get_and_clear_pending_events();
4906         assert_eq!(events.len(), 2);
4907         match events[0] {
4908                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4909                 _ => panic!("Unexpected event"),
4910         }
4911         match events[1] {
4912                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4913                         assert_eq!(fee_earned_msat, Some(1000));
4914                         assert_eq!(prev_channel_id, Some(chan_1.2));
4915                         assert_eq!(claim_from_onchain_tx, true);
4916                         assert_eq!(next_channel_id, Some(chan_2.2));
4917                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4918                 },
4919                 _ => panic!("Unexpected event"),
4920         }
4921         check_added_monitors!(nodes[1], 1);
4922         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4923         assert_eq!(msg_events.len(), 3);
4924         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4925         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4926
4927         match nodes_2_event {
4928                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4929                 _ => panic!("Unexpected event"),
4930         }
4931
4932         match nodes_0_event {
4933                 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, .. } } => {
4934                         assert!(update_add_htlcs.is_empty());
4935                         assert!(update_fail_htlcs.is_empty());
4936                         assert_eq!(update_fulfill_htlcs.len(), 1);
4937                         assert!(update_fail_malformed_htlcs.is_empty());
4938                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4939                 },
4940                 _ => panic!("Unexpected event"),
4941         };
4942
4943         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4944         match msg_events[0] {
4945                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4946                 _ => panic!("Unexpected event"),
4947         }
4948
4949         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4950         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4951         mine_transaction(&nodes[1], &commitment_tx[0]);
4952         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4953         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4954         // ChannelMonitor: HTLC-Success tx
4955         assert_eq!(b_txn.len(), 1);
4956         check_spends!(b_txn[0], commitment_tx[0]);
4957         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4958         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4959         assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
4960
4961         check_closed_broadcast!(nodes[1], true);
4962         check_added_monitors!(nodes[1], 1);
4963 }
4964
4965 #[test]
4966 fn test_duplicate_payment_hash_one_failure_one_success() {
4967         // Topology : A --> B --> C --> D
4968         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4969         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4970         // we forward one of the payments onwards to D.
4971         let chanmon_cfgs = create_chanmon_cfgs(4);
4972         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4973         // When this test was written, the default base fee floated based on the HTLC count.
4974         // It is now fixed, so we simply set the fee to the expected value here.
4975         let mut config = test_default_channel_config();
4976         config.channel_config.forwarding_fee_base_msat = 196;
4977         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4978                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4979         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4980
4981         create_announced_chan_between_nodes(&nodes, 0, 1);
4982         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4983         create_announced_chan_between_nodes(&nodes, 2, 3);
4984
4985         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4986         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4987         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4988         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4989         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4990
4991         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4992
4993         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4994         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4995         // script push size limit so that the below script length checks match
4996         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4997         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4998                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
4999         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5000         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5001
5002         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5003         assert_eq!(commitment_txn[0].input.len(), 1);
5004         check_spends!(commitment_txn[0], chan_2.3);
5005
5006         mine_transaction(&nodes[1], &commitment_txn[0]);
5007         check_closed_broadcast!(nodes[1], true);
5008         check_added_monitors!(nodes[1], 1);
5009         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5010         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5011
5012         let htlc_timeout_tx;
5013         { // Extract one of the two HTLC-Timeout transaction
5014                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5015                 // ChannelMonitor: timeout tx * 2-or-3
5016                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5017
5018                 check_spends!(node_txn[0], commitment_txn[0]);
5019                 assert_eq!(node_txn[0].input.len(), 1);
5020                 assert_eq!(node_txn[0].output.len(), 1);
5021
5022                 if node_txn.len() > 2 {
5023                         check_spends!(node_txn[1], commitment_txn[0]);
5024                         assert_eq!(node_txn[1].input.len(), 1);
5025                         assert_eq!(node_txn[1].output.len(), 1);
5026                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5027
5028                         check_spends!(node_txn[2], commitment_txn[0]);
5029                         assert_eq!(node_txn[2].input.len(), 1);
5030                         assert_eq!(node_txn[2].output.len(), 1);
5031                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5032                 } else {
5033                         check_spends!(node_txn[1], commitment_txn[0]);
5034                         assert_eq!(node_txn[1].input.len(), 1);
5035                         assert_eq!(node_txn[1].output.len(), 1);
5036                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5037                 }
5038
5039                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5040                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5041                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5042                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5043                 if node_txn.len() > 2 {
5044                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5045                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5046                 } else {
5047                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5048                 }
5049         }
5050
5051         nodes[2].node.claim_funds(our_payment_preimage);
5052         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5053
5054         mine_transaction(&nodes[2], &commitment_txn[0]);
5055         check_added_monitors!(nodes[2], 2);
5056         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5057         let events = nodes[2].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 htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5067         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5068         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5069         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5070         assert_eq!(htlc_success_txn[0].input.len(), 1);
5071         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5072         assert_eq!(htlc_success_txn[1].input.len(), 1);
5073         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5074         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5075         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5076
5077         mine_transaction(&nodes[1], &htlc_timeout_tx);
5078         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5079         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 }]);
5080         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5081         assert!(htlc_updates.update_add_htlcs.is_empty());
5082         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5083         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5084         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5085         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5086         check_added_monitors!(nodes[1], 1);
5087
5088         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5089         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5090         {
5091                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5092         }
5093         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5094
5095         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5096         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5097         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5098         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5099         assert!(updates.update_add_htlcs.is_empty());
5100         assert!(updates.update_fail_htlcs.is_empty());
5101         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5102         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5103         assert!(updates.update_fail_malformed_htlcs.is_empty());
5104         check_added_monitors!(nodes[1], 1);
5105
5106         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5107         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5108         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5109 }
5110
5111 #[test]
5112 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5113         let chanmon_cfgs = create_chanmon_cfgs(2);
5114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5116         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5117
5118         // Create some initial channels
5119         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5120
5121         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5122         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5123         assert_eq!(local_txn.len(), 1);
5124         assert_eq!(local_txn[0].input.len(), 1);
5125         check_spends!(local_txn[0], chan_1.3);
5126
5127         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5128         nodes[1].node.claim_funds(payment_preimage);
5129         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5130         check_added_monitors!(nodes[1], 1);
5131
5132         mine_transaction(&nodes[1], &local_txn[0]);
5133         check_added_monitors!(nodes[1], 1);
5134         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5135         let events = nodes[1].node.get_and_clear_pending_msg_events();
5136         match events[0] {
5137                 MessageSendEvent::UpdateHTLCs { .. } => {},
5138                 _ => panic!("Unexpected event"),
5139         }
5140         match events[1] {
5141                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5142                 _ => panic!("Unexepected event"),
5143         }
5144         let node_tx = {
5145                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5146                 assert_eq!(node_txn.len(), 1);
5147                 assert_eq!(node_txn[0].input.len(), 1);
5148                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5149                 check_spends!(node_txn[0], local_txn[0]);
5150                 node_txn[0].clone()
5151         };
5152
5153         mine_transaction(&nodes[1], &node_tx);
5154         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5155
5156         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5157         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5158         assert_eq!(spend_txn.len(), 1);
5159         assert_eq!(spend_txn[0].input.len(), 1);
5160         check_spends!(spend_txn[0], node_tx);
5161         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5162 }
5163
5164 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5165         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5166         // unrevoked commitment transaction.
5167         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5168         // a remote RAA before they could be failed backwards (and combinations thereof).
5169         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5170         // use the same payment hashes.
5171         // Thus, we use a six-node network:
5172         //
5173         // A \         / E
5174         //    - C - D -
5175         // B /         \ F
5176         // And test where C fails back to A/B when D announces its latest commitment transaction
5177         let chanmon_cfgs = create_chanmon_cfgs(6);
5178         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5179         // When this test was written, the default base fee floated based on the HTLC count.
5180         // It is now fixed, so we simply set the fee to the expected value here.
5181         let mut config = test_default_channel_config();
5182         config.channel_config.forwarding_fee_base_msat = 196;
5183         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5184                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5185         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5186
5187         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5188         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5189         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5190         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5191         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5192
5193         // Rebalance and check output sanity...
5194         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5195         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5196         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5197
5198         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5199                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5200         // 0th HTLC:
5201         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
5202         // 1st HTLC:
5203         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
5204         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5205         // 2nd HTLC:
5206         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
5207         // 3rd HTLC:
5208         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
5209         // 4th HTLC:
5210         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5211         // 5th HTLC:
5212         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5213         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5214         // 6th HTLC:
5215         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());
5216         // 7th HTLC:
5217         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());
5218
5219         // 8th HTLC:
5220         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5221         // 9th HTLC:
5222         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5223         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
5224
5225         // 10th HTLC:
5226         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
5227         // 11th HTLC:
5228         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5229         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());
5230
5231         // Double-check that six of the new HTLC were added
5232         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5233         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5234         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5235         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5236
5237         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5238         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5239         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5240         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5241         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5242         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5243         check_added_monitors!(nodes[4], 0);
5244
5245         let failed_destinations = vec![
5246                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5247                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5248                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5249                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5250         ];
5251         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5252         check_added_monitors!(nodes[4], 1);
5253
5254         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5255         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5256         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5257         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5258         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5259         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5260
5261         // Fail 3rd below-dust and 7th above-dust HTLCs
5262         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5263         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5264         check_added_monitors!(nodes[5], 0);
5265
5266         let failed_destinations_2 = vec![
5267                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5268                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5269         ];
5270         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5271         check_added_monitors!(nodes[5], 1);
5272
5273         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5274         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5275         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5276         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5277
5278         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5279
5280         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5281         let failed_destinations_3 = vec![
5282                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5283                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5284                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5285                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5286                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5287                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5288         ];
5289         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5290         check_added_monitors!(nodes[3], 1);
5291         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5292         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5293         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5294         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5295         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5296         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5297         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5298         if deliver_last_raa {
5299                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5300         } else {
5301                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5302         }
5303
5304         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5305         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5306         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5307         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5308         //
5309         // We now broadcast the latest commitment transaction, which *should* result in failures for
5310         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5311         // the non-broadcast above-dust HTLCs.
5312         //
5313         // Alternatively, we may broadcast the previous commitment transaction, which should only
5314         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5315         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5316
5317         if announce_latest {
5318                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5319         } else {
5320                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5321         }
5322         let events = nodes[2].node.get_and_clear_pending_events();
5323         let close_event = if deliver_last_raa {
5324                 assert_eq!(events.len(), 2 + 6);
5325                 events.last().clone().unwrap()
5326         } else {
5327                 assert_eq!(events.len(), 1);
5328                 events.last().clone().unwrap()
5329         };
5330         match close_event {
5331                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5332                 _ => panic!("Unexpected event"),
5333         }
5334
5335         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5336         check_closed_broadcast!(nodes[2], true);
5337         if deliver_last_raa {
5338                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5339
5340                 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();
5341                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5342         } else {
5343                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5344                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5345                 } else {
5346                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5347                 };
5348
5349                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5350         }
5351         check_added_monitors!(nodes[2], 3);
5352
5353         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5354         assert_eq!(cs_msgs.len(), 2);
5355         let mut a_done = false;
5356         for msg in cs_msgs {
5357                 match msg {
5358                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5359                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5360                                 // should be failed-backwards here.
5361                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5362                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5363                                         for htlc in &updates.update_fail_htlcs {
5364                                                 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 });
5365                                         }
5366                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5367                                         assert!(!a_done);
5368                                         a_done = true;
5369                                         &nodes[0]
5370                                 } else {
5371                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5372                                         for htlc in &updates.update_fail_htlcs {
5373                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5374                                         }
5375                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5376                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5377                                         &nodes[1]
5378                                 };
5379                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5380                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5381                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5382                                 if announce_latest {
5383                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5384                                         if *node_id == nodes[0].node.get_our_node_id() {
5385                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5386                                         }
5387                                 }
5388                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5389                         },
5390                         _ => panic!("Unexpected event"),
5391                 }
5392         }
5393
5394         let as_events = nodes[0].node.get_and_clear_pending_events();
5395         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5396         let mut as_failds = HashSet::new();
5397         let mut as_updates = 0;
5398         for event in as_events.iter() {
5399                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5400                         assert!(as_failds.insert(*payment_hash));
5401                         if *payment_hash != payment_hash_2 {
5402                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5403                         } else {
5404                                 assert!(!payment_failed_permanently);
5405                         }
5406                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5407                                 as_updates += 1;
5408                         }
5409                 } else if let &Event::PaymentFailed { .. } = event {
5410                 } else { panic!("Unexpected event"); }
5411         }
5412         assert!(as_failds.contains(&payment_hash_1));
5413         assert!(as_failds.contains(&payment_hash_2));
5414         if announce_latest {
5415                 assert!(as_failds.contains(&payment_hash_3));
5416                 assert!(as_failds.contains(&payment_hash_5));
5417         }
5418         assert!(as_failds.contains(&payment_hash_6));
5419
5420         let bs_events = nodes[1].node.get_and_clear_pending_events();
5421         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5422         let mut bs_failds = HashSet::new();
5423         let mut bs_updates = 0;
5424         for event in bs_events.iter() {
5425                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5426                         assert!(bs_failds.insert(*payment_hash));
5427                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5428                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5429                         } else {
5430                                 assert!(!payment_failed_permanently);
5431                         }
5432                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5433                                 bs_updates += 1;
5434                         }
5435                 } else if let &Event::PaymentFailed { .. } = event {
5436                 } else { panic!("Unexpected event"); }
5437         }
5438         assert!(bs_failds.contains(&payment_hash_1));
5439         assert!(bs_failds.contains(&payment_hash_2));
5440         if announce_latest {
5441                 assert!(bs_failds.contains(&payment_hash_4));
5442         }
5443         assert!(bs_failds.contains(&payment_hash_5));
5444
5445         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5446         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5447         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5448         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5449         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5450         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5451 }
5452
5453 #[test]
5454 fn test_fail_backwards_latest_remote_announce_a() {
5455         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5456 }
5457
5458 #[test]
5459 fn test_fail_backwards_latest_remote_announce_b() {
5460         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5461 }
5462
5463 #[test]
5464 fn test_fail_backwards_previous_remote_announce() {
5465         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5466         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5467         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5468 }
5469
5470 #[test]
5471 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5472         let chanmon_cfgs = create_chanmon_cfgs(2);
5473         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5474         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5475         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5476
5477         // Create some initial channels
5478         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5479
5480         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5481         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5482         assert_eq!(local_txn[0].input.len(), 1);
5483         check_spends!(local_txn[0], chan_1.3);
5484
5485         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5486         mine_transaction(&nodes[0], &local_txn[0]);
5487         check_closed_broadcast!(nodes[0], true);
5488         check_added_monitors!(nodes[0], 1);
5489         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5490         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5491
5492         let htlc_timeout = {
5493                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5494                 assert_eq!(node_txn.len(), 1);
5495                 assert_eq!(node_txn[0].input.len(), 1);
5496                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5497                 check_spends!(node_txn[0], local_txn[0]);
5498                 node_txn[0].clone()
5499         };
5500
5501         mine_transaction(&nodes[0], &htlc_timeout);
5502         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5503         expect_payment_failed!(nodes[0], our_payment_hash, false);
5504
5505         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5506         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5507         assert_eq!(spend_txn.len(), 3);
5508         check_spends!(spend_txn[0], local_txn[0]);
5509         assert_eq!(spend_txn[1].input.len(), 1);
5510         check_spends!(spend_txn[1], htlc_timeout);
5511         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5512         assert_eq!(spend_txn[2].input.len(), 2);
5513         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5514         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5515                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5516 }
5517
5518 #[test]
5519 fn test_key_derivation_params() {
5520         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5521         // manager rotation to test that `channel_keys_id` returned in
5522         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5523         // then derive a `delayed_payment_key`.
5524
5525         let chanmon_cfgs = create_chanmon_cfgs(3);
5526
5527         // We manually create the node configuration to backup the seed.
5528         let seed = [42; 32];
5529         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5530         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);
5531         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5532         let scorer = RwLock::new(test_utils::TestScorer::new());
5533         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5534         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)) };
5535         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5536         node_cfgs.remove(0);
5537         node_cfgs.insert(0, node);
5538
5539         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5540         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5541
5542         // Create some initial channels
5543         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5544         // for node 0
5545         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5546         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5547         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5548
5549         // Ensure all nodes are at the same height
5550         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5551         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5552         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5553         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5554
5555         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5556         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5557         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5558         assert_eq!(local_txn_1[0].input.len(), 1);
5559         check_spends!(local_txn_1[0], chan_1.3);
5560
5561         // We check funding pubkey are unique
5562         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]));
5563         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]));
5564         if from_0_funding_key_0 == from_1_funding_key_0
5565             || from_0_funding_key_0 == from_1_funding_key_1
5566             || from_0_funding_key_1 == from_1_funding_key_0
5567             || from_0_funding_key_1 == from_1_funding_key_1 {
5568                 panic!("Funding pubkeys aren't unique");
5569         }
5570
5571         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5572         mine_transaction(&nodes[0], &local_txn_1[0]);
5573         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5574         check_closed_broadcast!(nodes[0], true);
5575         check_added_monitors!(nodes[0], 1);
5576         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5577
5578         let htlc_timeout = {
5579                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5580                 assert_eq!(node_txn.len(), 1);
5581                 assert_eq!(node_txn[0].input.len(), 1);
5582                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5583                 check_spends!(node_txn[0], local_txn_1[0]);
5584                 node_txn[0].clone()
5585         };
5586
5587         mine_transaction(&nodes[0], &htlc_timeout);
5588         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5589         expect_payment_failed!(nodes[0], our_payment_hash, false);
5590
5591         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5592         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5593         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5594         assert_eq!(spend_txn.len(), 3);
5595         check_spends!(spend_txn[0], local_txn_1[0]);
5596         assert_eq!(spend_txn[1].input.len(), 1);
5597         check_spends!(spend_txn[1], htlc_timeout);
5598         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5599         assert_eq!(spend_txn[2].input.len(), 2);
5600         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5601         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5602                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5603 }
5604
5605 #[test]
5606 fn test_static_output_closing_tx() {
5607         let chanmon_cfgs = create_chanmon_cfgs(2);
5608         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5609         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5610         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5611
5612         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5613
5614         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5615         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5616
5617         mine_transaction(&nodes[0], &closing_tx);
5618         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5619         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5620
5621         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5622         assert_eq!(spend_txn.len(), 1);
5623         check_spends!(spend_txn[0], closing_tx);
5624
5625         mine_transaction(&nodes[1], &closing_tx);
5626         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5627         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5628
5629         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5630         assert_eq!(spend_txn.len(), 1);
5631         check_spends!(spend_txn[0], closing_tx);
5632 }
5633
5634 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5635         let chanmon_cfgs = create_chanmon_cfgs(2);
5636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5638         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5639         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5640
5641         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5642
5643         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5644         // present in B's local commitment transaction, but none of A's commitment transactions.
5645         nodes[1].node.claim_funds(payment_preimage);
5646         check_added_monitors!(nodes[1], 1);
5647         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5648
5649         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5650         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5651         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5652
5653         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5654         check_added_monitors!(nodes[0], 1);
5655         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5656         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5657         check_added_monitors!(nodes[1], 1);
5658
5659         let starting_block = nodes[1].best_block_info();
5660         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5661         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5662                 connect_block(&nodes[1], &block);
5663                 block.header.prev_blockhash = block.block_hash();
5664         }
5665         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5666         check_closed_broadcast!(nodes[1], true);
5667         check_added_monitors!(nodes[1], 1);
5668         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
5669 }
5670
5671 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5672         let chanmon_cfgs = create_chanmon_cfgs(2);
5673         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5674         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5675         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5676         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5677
5678         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5679         nodes[0].node.send_payment_with_route(&route, payment_hash,
5680                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5681         check_added_monitors!(nodes[0], 1);
5682
5683         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5684
5685         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5686         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5687         // to "time out" the HTLC.
5688
5689         let starting_block = nodes[1].best_block_info();
5690         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5691
5692         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5693                 connect_block(&nodes[0], &block);
5694                 block.header.prev_blockhash = block.block_hash();
5695         }
5696         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5697         check_closed_broadcast!(nodes[0], true);
5698         check_added_monitors!(nodes[0], 1);
5699         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5700 }
5701
5702 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5703         let chanmon_cfgs = create_chanmon_cfgs(3);
5704         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5705         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5706         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5707         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5708
5709         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5710         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5711         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5712         // actually revoked.
5713         let htlc_value = if use_dust { 50000 } else { 3000000 };
5714         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5715         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5716         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5717         check_added_monitors!(nodes[1], 1);
5718
5719         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5720         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5721         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5722         check_added_monitors!(nodes[0], 1);
5723         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5724         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5725         check_added_monitors!(nodes[1], 1);
5726         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5727         check_added_monitors!(nodes[1], 1);
5728         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5729
5730         if check_revoke_no_close {
5731                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5732                 check_added_monitors!(nodes[0], 1);
5733         }
5734
5735         let starting_block = nodes[1].best_block_info();
5736         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5737         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5738                 connect_block(&nodes[0], &block);
5739                 block.header.prev_blockhash = block.block_hash();
5740         }
5741         if !check_revoke_no_close {
5742                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5743                 check_closed_broadcast!(nodes[0], true);
5744                 check_added_monitors!(nodes[0], 1);
5745                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5746         } else {
5747                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5748         }
5749 }
5750
5751 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5752 // There are only a few cases to test here:
5753 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5754 //    broadcastable commitment transactions result in channel closure,
5755 //  * its included in an unrevoked-but-previous remote commitment transaction,
5756 //  * its included in the latest remote or local commitment transactions.
5757 // We test each of the three possible commitment transactions individually and use both dust and
5758 // non-dust HTLCs.
5759 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5760 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5761 // tested for at least one of the cases in other tests.
5762 #[test]
5763 fn htlc_claim_single_commitment_only_a() {
5764         do_htlc_claim_local_commitment_only(true);
5765         do_htlc_claim_local_commitment_only(false);
5766
5767         do_htlc_claim_current_remote_commitment_only(true);
5768         do_htlc_claim_current_remote_commitment_only(false);
5769 }
5770
5771 #[test]
5772 fn htlc_claim_single_commitment_only_b() {
5773         do_htlc_claim_previous_remote_commitment_only(true, false);
5774         do_htlc_claim_previous_remote_commitment_only(false, false);
5775         do_htlc_claim_previous_remote_commitment_only(true, true);
5776         do_htlc_claim_previous_remote_commitment_only(false, true);
5777 }
5778
5779 #[test]
5780 #[should_panic]
5781 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5782         let chanmon_cfgs = create_chanmon_cfgs(2);
5783         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5784         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5785         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5786         // Force duplicate randomness for every get-random call
5787         for node in nodes.iter() {
5788                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5789         }
5790
5791         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5792         let channel_value_satoshis=10000;
5793         let push_msat=10001;
5794         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5795         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5796         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5797         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5798
5799         // Create a second channel with the same random values. This used to panic due to a colliding
5800         // channel_id, but now panics due to a colliding outbound SCID alias.
5801         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5802 }
5803
5804 #[test]
5805 fn bolt2_open_channel_sending_node_checks_part2() {
5806         let chanmon_cfgs = create_chanmon_cfgs(2);
5807         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5808         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5809         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5810
5811         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5812         let channel_value_satoshis=2^24;
5813         let push_msat=10001;
5814         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5815
5816         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5817         let channel_value_satoshis=10000;
5818         // Test when push_msat is equal to 1000 * funding_satoshis.
5819         let push_msat=1000*channel_value_satoshis+1;
5820         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5821
5822         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5823         let channel_value_satoshis=10000;
5824         let push_msat=10001;
5825         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_ok()); //Create a valid channel
5826         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5827         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5828
5829         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5830         // 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
5831         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5832
5833         // 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.
5834         assert!(BREAKDOWN_TIMEOUT>0);
5835         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5836
5837         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5838         let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5839         assert_eq!(node0_to_1_send_open_channel.chain_hash, chain_hash);
5840
5841         // 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.
5842         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5843         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5844         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5845         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5846         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5847 }
5848
5849 #[test]
5850 fn bolt2_open_channel_sane_dust_limit() {
5851         let chanmon_cfgs = create_chanmon_cfgs(2);
5852         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5853         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5854         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5855
5856         let channel_value_satoshis=1000000;
5857         let push_msat=10001;
5858         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5859         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5860         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5861         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5862
5863         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5864         let events = nodes[1].node.get_and_clear_pending_msg_events();
5865         let err_msg = match events[0] {
5866                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5867                         msg.clone()
5868                 },
5869                 _ => panic!("Unexpected event"),
5870         };
5871         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5872 }
5873
5874 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5875 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5876 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5877 // is no longer affordable once it's freed.
5878 #[test]
5879 fn test_fail_holding_cell_htlc_upon_free() {
5880         let chanmon_cfgs = create_chanmon_cfgs(2);
5881         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5882         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5883         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5884         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5885
5886         // First nodes[0] generates an update_fee, setting the channel's
5887         // pending_update_fee.
5888         {
5889                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5890                 *feerate_lock += 20;
5891         }
5892         nodes[0].node.timer_tick_occurred();
5893         check_added_monitors!(nodes[0], 1);
5894
5895         let events = nodes[0].node.get_and_clear_pending_msg_events();
5896         assert_eq!(events.len(), 1);
5897         let (update_msg, commitment_signed) = match events[0] {
5898                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5899                         (update_fee.as_ref(), commitment_signed)
5900                 },
5901                 _ => panic!("Unexpected event"),
5902         };
5903
5904         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5905
5906         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5907         let channel_reserve = chan_stat.channel_reserve_msat;
5908         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5909         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5910
5911         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5912         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5913         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5914
5915         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5916         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5917                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5918         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5919         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5920
5921         // Flush the pending fee update.
5922         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5923         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5924         check_added_monitors!(nodes[1], 1);
5925         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5926         check_added_monitors!(nodes[0], 1);
5927
5928         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5929         // HTLC, but now that the fee has been raised the payment will now fail, causing
5930         // us to surface its failure to the user.
5931         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5932         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5933         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5934
5935         // Check that the payment failed to be sent out.
5936         let events = nodes[0].node.get_and_clear_pending_events();
5937         assert_eq!(events.len(), 2);
5938         match &events[0] {
5939                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5940                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5941                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5942                         assert_eq!(*payment_failed_permanently, false);
5943                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5944                 },
5945                 _ => panic!("Unexpected event"),
5946         }
5947         match &events[1] {
5948                 &Event::PaymentFailed { ref payment_hash, .. } => {
5949                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5950                 },
5951                 _ => panic!("Unexpected event"),
5952         }
5953 }
5954
5955 // Test that if multiple HTLCs are released from the holding cell and one is
5956 // valid but the other is no longer valid upon release, the valid HTLC can be
5957 // successfully completed while the other one fails as expected.
5958 #[test]
5959 fn test_free_and_fail_holding_cell_htlcs() {
5960         let chanmon_cfgs = create_chanmon_cfgs(2);
5961         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5962         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5963         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5964         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5965
5966         // First nodes[0] generates an update_fee, setting the channel's
5967         // pending_update_fee.
5968         {
5969                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5970                 *feerate_lock += 200;
5971         }
5972         nodes[0].node.timer_tick_occurred();
5973         check_added_monitors!(nodes[0], 1);
5974
5975         let events = nodes[0].node.get_and_clear_pending_msg_events();
5976         assert_eq!(events.len(), 1);
5977         let (update_msg, commitment_signed) = match events[0] {
5978                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5979                         (update_fee.as_ref(), commitment_signed)
5980                 },
5981                 _ => panic!("Unexpected event"),
5982         };
5983
5984         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5985
5986         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5987         let channel_reserve = chan_stat.channel_reserve_msat;
5988         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5989         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5990
5991         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5992         let amt_1 = 20000;
5993         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5994         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5995         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5996
5997         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5998         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5999                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6000         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6001         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6002         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6003         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6004                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6005         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6006         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6007
6008         // Flush the pending fee update.
6009         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6010         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6011         check_added_monitors!(nodes[1], 1);
6012         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6013         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6014         check_added_monitors!(nodes[0], 2);
6015
6016         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6017         // but now that the fee has been raised the second payment will now fail, causing us
6018         // to surface its failure to the user. The first payment should succeed.
6019         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6020         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6021         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6022
6023         // Check that the second payment failed to be sent out.
6024         let events = nodes[0].node.get_and_clear_pending_events();
6025         assert_eq!(events.len(), 2);
6026         match &events[0] {
6027                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6028                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6029                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6030                         assert_eq!(*payment_failed_permanently, false);
6031                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6032                 },
6033                 _ => panic!("Unexpected event"),
6034         }
6035         match &events[1] {
6036                 &Event::PaymentFailed { ref payment_hash, .. } => {
6037                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6038                 },
6039                 _ => panic!("Unexpected event"),
6040         }
6041
6042         // Complete the first payment and the RAA from the fee update.
6043         let (payment_event, send_raa_event) = {
6044                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6045                 assert_eq!(msgs.len(), 2);
6046                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6047         };
6048         let raa = match send_raa_event {
6049                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6050                 _ => panic!("Unexpected event"),
6051         };
6052         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6053         check_added_monitors!(nodes[1], 1);
6054         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6055         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6056         let events = nodes[1].node.get_and_clear_pending_events();
6057         assert_eq!(events.len(), 1);
6058         match events[0] {
6059                 Event::PendingHTLCsForwardable { .. } => {},
6060                 _ => panic!("Unexpected event"),
6061         }
6062         nodes[1].node.process_pending_htlc_forwards();
6063         let events = nodes[1].node.get_and_clear_pending_events();
6064         assert_eq!(events.len(), 1);
6065         match events[0] {
6066                 Event::PaymentClaimable { .. } => {},
6067                 _ => panic!("Unexpected event"),
6068         }
6069         nodes[1].node.claim_funds(payment_preimage_1);
6070         check_added_monitors!(nodes[1], 1);
6071         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6072
6073         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6074         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6075         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6076         expect_payment_sent!(nodes[0], payment_preimage_1);
6077 }
6078
6079 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6080 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6081 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6082 // once it's freed.
6083 #[test]
6084 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6085         let chanmon_cfgs = create_chanmon_cfgs(3);
6086         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6087         // Avoid having to include routing fees in calculations
6088         let mut config = test_default_channel_config();
6089         config.channel_config.forwarding_fee_base_msat = 0;
6090         config.channel_config.forwarding_fee_proportional_millionths = 0;
6091         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6092         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6093         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6094         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6095
6096         // First nodes[1] generates an update_fee, setting the channel's
6097         // pending_update_fee.
6098         {
6099                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6100                 *feerate_lock += 20;
6101         }
6102         nodes[1].node.timer_tick_occurred();
6103         check_added_monitors!(nodes[1], 1);
6104
6105         let events = nodes[1].node.get_and_clear_pending_msg_events();
6106         assert_eq!(events.len(), 1);
6107         let (update_msg, commitment_signed) = match events[0] {
6108                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6109                         (update_fee.as_ref(), commitment_signed)
6110                 },
6111                 _ => panic!("Unexpected event"),
6112         };
6113
6114         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6115
6116         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6117         let channel_reserve = chan_stat.channel_reserve_msat;
6118         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6119         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6120
6121         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6122         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6123         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6124         let payment_event = {
6125                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6126                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6127                 check_added_monitors!(nodes[0], 1);
6128
6129                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6130                 assert_eq!(events.len(), 1);
6131
6132                 SendEvent::from_event(events.remove(0))
6133         };
6134         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6135         check_added_monitors!(nodes[1], 0);
6136         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6137         expect_pending_htlcs_forwardable!(nodes[1]);
6138
6139         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6140         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6141
6142         // Flush the pending fee update.
6143         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6144         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6145         check_added_monitors!(nodes[2], 1);
6146         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6147         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6148         check_added_monitors!(nodes[1], 2);
6149
6150         // A final RAA message is generated to finalize the fee update.
6151         let events = nodes[1].node.get_and_clear_pending_msg_events();
6152         assert_eq!(events.len(), 1);
6153
6154         let raa_msg = match &events[0] {
6155                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6156                         msg.clone()
6157                 },
6158                 _ => panic!("Unexpected event"),
6159         };
6160
6161         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6162         check_added_monitors!(nodes[2], 1);
6163         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6164
6165         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6166         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6167         assert_eq!(process_htlc_forwards_event.len(), 2);
6168         match &process_htlc_forwards_event[0] {
6169                 &Event::PendingHTLCsForwardable { .. } => {},
6170                 _ => panic!("Unexpected event"),
6171         }
6172
6173         // In response, we call ChannelManager's process_pending_htlc_forwards
6174         nodes[1].node.process_pending_htlc_forwards();
6175         check_added_monitors!(nodes[1], 1);
6176
6177         // This causes the HTLC to be failed backwards.
6178         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6179         assert_eq!(fail_event.len(), 1);
6180         let (fail_msg, commitment_signed) = match &fail_event[0] {
6181                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6182                         assert_eq!(updates.update_add_htlcs.len(), 0);
6183                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6184                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6185                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6186                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6187                 },
6188                 _ => panic!("Unexpected event"),
6189         };
6190
6191         // Pass the failure messages back to nodes[0].
6192         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6193         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6194
6195         // Complete the HTLC failure+removal process.
6196         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6197         check_added_monitors!(nodes[0], 1);
6198         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6199         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6200         check_added_monitors!(nodes[1], 2);
6201         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6202         assert_eq!(final_raa_event.len(), 1);
6203         let raa = match &final_raa_event[0] {
6204                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6205                 _ => panic!("Unexpected event"),
6206         };
6207         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6208         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6209         check_added_monitors!(nodes[0], 1);
6210 }
6211
6212 #[test]
6213 fn test_payment_route_reaching_same_channel_twice() {
6214         //A route should not go through the same channel twice
6215         //It is enforced when constructing a route.
6216         let chanmon_cfgs = create_chanmon_cfgs(2);
6217         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6218         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6219         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6220         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6221
6222         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6223                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6224         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6225
6226         // Extend the path by itself, essentially simulating route going through same channel twice
6227         let cloned_hops = route.paths[0].hops.clone();
6228         route.paths[0].hops.extend_from_slice(&cloned_hops);
6229
6230         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6231                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6232         ), false, APIError::InvalidRoute { ref err },
6233         assert_eq!(err, &"Path went through the same channel twice"));
6234 }
6235
6236 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6237 // 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.
6238 //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.
6239
6240 #[test]
6241 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6242         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6243         let chanmon_cfgs = create_chanmon_cfgs(2);
6244         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6245         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6246         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6247         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6248
6249         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6250         route.paths[0].hops[0].fee_msat = 100;
6251
6252         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6253                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6254                 ), true, APIError::ChannelUnavailable { .. }, {});
6255         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6256 }
6257
6258 #[test]
6259 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6260         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6261         let chanmon_cfgs = create_chanmon_cfgs(2);
6262         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6263         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6264         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6265         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6266
6267         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6268         route.paths[0].hops[0].fee_msat = 0;
6269         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6270                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6271                 true, APIError::ChannelUnavailable { ref err },
6272                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6273
6274         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6275         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6276 }
6277
6278 #[test]
6279 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6280         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6281         let chanmon_cfgs = create_chanmon_cfgs(2);
6282         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6283         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6284         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6285         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6286
6287         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6288         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6289                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6290         check_added_monitors!(nodes[0], 1);
6291         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6292         updates.update_add_htlcs[0].amount_msat = 0;
6293
6294         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6295         nodes[1].logger.assert_log("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6296         check_closed_broadcast!(nodes[1], true).unwrap();
6297         check_added_monitors!(nodes[1], 1);
6298         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6299                 [nodes[0].node.get_our_node_id()], 100000);
6300 }
6301
6302 #[test]
6303 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6304         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6305         //It is enforced when constructing a route.
6306         let chanmon_cfgs = create_chanmon_cfgs(2);
6307         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6308         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6309         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6310         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6311
6312         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6313                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6314         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6315         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6316         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6317                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6318                 ), true, APIError::InvalidRoute { ref err },
6319                 assert_eq!(err, &"Channel CLTV overflowed?"));
6320 }
6321
6322 #[test]
6323 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6324         //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.
6325         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6326         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6327         let chanmon_cfgs = create_chanmon_cfgs(2);
6328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6330         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6331         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6332         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6333                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6334
6335         // Fetch a route in advance as we will be unable to once we're unable to send.
6336         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6337         for i in 0..max_accepted_htlcs {
6338                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6339                 let payment_event = {
6340                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6341                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6342                         check_added_monitors!(nodes[0], 1);
6343
6344                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6345                         assert_eq!(events.len(), 1);
6346                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6347                                 assert_eq!(htlcs[0].htlc_id, i);
6348                         } else {
6349                                 assert!(false);
6350                         }
6351                         SendEvent::from_event(events.remove(0))
6352                 };
6353                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6354                 check_added_monitors!(nodes[1], 0);
6355                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6356
6357                 expect_pending_htlcs_forwardable!(nodes[1]);
6358                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6359         }
6360         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6361                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6362                 ), true, APIError::ChannelUnavailable { .. }, {});
6363
6364         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6365 }
6366
6367 #[test]
6368 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6369         //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.
6370         let chanmon_cfgs = create_chanmon_cfgs(2);
6371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6374         let channel_value = 100000;
6375         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6376         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6377
6378         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6379
6380         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6381         // Manually create a route over our max in flight (which our router normally automatically
6382         // limits us to.
6383         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6384         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6385                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6386                 ), true, APIError::ChannelUnavailable { .. }, {});
6387         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6388
6389         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6390 }
6391
6392 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6393 #[test]
6394 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6395         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6396         let chanmon_cfgs = create_chanmon_cfgs(2);
6397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6399         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6400         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6401         let htlc_minimum_msat: u64;
6402         {
6403                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6404                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6405                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6406                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6407         }
6408
6409         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6410         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6411                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6412         check_added_monitors!(nodes[0], 1);
6413         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6414         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6415         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6416         assert!(nodes[1].node.list_channels().is_empty());
6417         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6418         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()));
6419         check_added_monitors!(nodes[1], 1);
6420         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6421 }
6422
6423 #[test]
6424 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6425         //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
6426         let chanmon_cfgs = create_chanmon_cfgs(2);
6427         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6428         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6429         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6430         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6431
6432         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6433         let channel_reserve = chan_stat.channel_reserve_msat;
6434         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6435         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6436         // The 2* and +1 are for the fee spike reserve.
6437         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6438
6439         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6440         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6441         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6442                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6443         check_added_monitors!(nodes[0], 1);
6444         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6445
6446         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6447         // at this time channel-initiatee receivers are not required to enforce that senders
6448         // respect the fee_spike_reserve.
6449         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6450         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6451
6452         assert!(nodes[1].node.list_channels().is_empty());
6453         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6454         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6455         check_added_monitors!(nodes[1], 1);
6456         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6457 }
6458
6459 #[test]
6460 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6461         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6462         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6463         let chanmon_cfgs = create_chanmon_cfgs(2);
6464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6466         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6467         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6468
6469         let send_amt = 3999999;
6470         let (mut route, our_payment_hash, _, our_payment_secret) =
6471                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6472         route.paths[0].hops[0].fee_msat = send_amt;
6473         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6474         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6475         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6476         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6477                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6478         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6479
6480         let mut msg = msgs::UpdateAddHTLC {
6481                 channel_id: chan.2,
6482                 htlc_id: 0,
6483                 amount_msat: 1000,
6484                 payment_hash: our_payment_hash,
6485                 cltv_expiry: htlc_cltv,
6486                 onion_routing_packet: onion_packet.clone(),
6487                 skimmed_fee_msat: None,
6488                 blinding_point: None,
6489         };
6490
6491         for i in 0..50 {
6492                 msg.htlc_id = i as u64;
6493                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6494         }
6495         msg.htlc_id = (50) as u64;
6496         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6497
6498         assert!(nodes[1].node.list_channels().is_empty());
6499         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6500         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6501         check_added_monitors!(nodes[1], 1);
6502         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6503 }
6504
6505 #[test]
6506 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6507         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6508         let chanmon_cfgs = create_chanmon_cfgs(2);
6509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6511         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6512         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6513
6514         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6515         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6516                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6517         check_added_monitors!(nodes[0], 1);
6518         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6519         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;
6520         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6521
6522         assert!(nodes[1].node.list_channels().is_empty());
6523         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6524         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6525         check_added_monitors!(nodes[1], 1);
6526         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6527 }
6528
6529 #[test]
6530 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6531         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6532         let chanmon_cfgs = create_chanmon_cfgs(2);
6533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6535         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6536
6537         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6538         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6539         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6540                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6541         check_added_monitors!(nodes[0], 1);
6542         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6543         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6544         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6545
6546         assert!(nodes[1].node.list_channels().is_empty());
6547         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6548         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6549         check_added_monitors!(nodes[1], 1);
6550         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6551 }
6552
6553 #[test]
6554 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6555         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6556         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6557         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6558         let chanmon_cfgs = create_chanmon_cfgs(2);
6559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6561         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6562
6563         create_announced_chan_between_nodes(&nodes, 0, 1);
6564         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6565         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6566                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6567         check_added_monitors!(nodes[0], 1);
6568         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6569         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6570
6571         //Disconnect and Reconnect
6572         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6573         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6574         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6575                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6576         }, true).unwrap();
6577         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6578         assert_eq!(reestablish_1.len(), 1);
6579         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6580                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6581         }, false).unwrap();
6582         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6583         assert_eq!(reestablish_2.len(), 1);
6584         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6585         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6586         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6587         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6588
6589         //Resend HTLC
6590         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6591         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6592         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6593         check_added_monitors!(nodes[1], 1);
6594         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6595
6596         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6597
6598         assert!(nodes[1].node.list_channels().is_empty());
6599         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6600         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6601         check_added_monitors!(nodes[1], 1);
6602         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6603 }
6604
6605 #[test]
6606 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6607         //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.
6608
6609         let chanmon_cfgs = create_chanmon_cfgs(2);
6610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6612         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6613         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6614         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6615         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6616                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6617
6618         check_added_monitors!(nodes[0], 1);
6619         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6620         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6621
6622         let update_msg = msgs::UpdateFulfillHTLC{
6623                 channel_id: chan.2,
6624                 htlc_id: 0,
6625                 payment_preimage: our_payment_preimage,
6626         };
6627
6628         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6629
6630         assert!(nodes[0].node.list_channels().is_empty());
6631         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6632         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()));
6633         check_added_monitors!(nodes[0], 1);
6634         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6635 }
6636
6637 #[test]
6638 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6639         //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.
6640
6641         let chanmon_cfgs = create_chanmon_cfgs(2);
6642         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6643         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6644         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6645         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6646
6647         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6648         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6649                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6650         check_added_monitors!(nodes[0], 1);
6651         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6652         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6653
6654         let update_msg = msgs::UpdateFailHTLC{
6655                 channel_id: chan.2,
6656                 htlc_id: 0,
6657                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6658         };
6659
6660         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6661
6662         assert!(nodes[0].node.list_channels().is_empty());
6663         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6664         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()));
6665         check_added_monitors!(nodes[0], 1);
6666         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6667 }
6668
6669 #[test]
6670 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6671         //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.
6672
6673         let chanmon_cfgs = create_chanmon_cfgs(2);
6674         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6675         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6676         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6677         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6678
6679         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6680         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6681                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6682         check_added_monitors!(nodes[0], 1);
6683         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6684         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6685         let update_msg = msgs::UpdateFailMalformedHTLC{
6686                 channel_id: chan.2,
6687                 htlc_id: 0,
6688                 sha256_of_onion: [1; 32],
6689                 failure_code: 0x8000,
6690         };
6691
6692         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6693
6694         assert!(nodes[0].node.list_channels().is_empty());
6695         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6696         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()));
6697         check_added_monitors!(nodes[0], 1);
6698         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6699 }
6700
6701 #[test]
6702 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6703         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6704
6705         let chanmon_cfgs = create_chanmon_cfgs(2);
6706         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6707         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6708         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6709         create_announced_chan_between_nodes(&nodes, 0, 1);
6710
6711         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6712
6713         nodes[1].node.claim_funds(our_payment_preimage);
6714         check_added_monitors!(nodes[1], 1);
6715         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6716
6717         let events = nodes[1].node.get_and_clear_pending_msg_events();
6718         assert_eq!(events.len(), 1);
6719         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6720                 match events[0] {
6721                         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, .. } } => {
6722                                 assert!(update_add_htlcs.is_empty());
6723                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6724                                 assert!(update_fail_htlcs.is_empty());
6725                                 assert!(update_fail_malformed_htlcs.is_empty());
6726                                 assert!(update_fee.is_none());
6727                                 update_fulfill_htlcs[0].clone()
6728                         },
6729                         _ => panic!("Unexpected event"),
6730                 }
6731         };
6732
6733         update_fulfill_msg.htlc_id = 1;
6734
6735         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6736
6737         assert!(nodes[0].node.list_channels().is_empty());
6738         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6739         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6740         check_added_monitors!(nodes[0], 1);
6741         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6742 }
6743
6744 #[test]
6745 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6746         //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.
6747
6748         let chanmon_cfgs = create_chanmon_cfgs(2);
6749         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6750         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6751         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6752         create_announced_chan_between_nodes(&nodes, 0, 1);
6753
6754         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6755
6756         nodes[1].node.claim_funds(our_payment_preimage);
6757         check_added_monitors!(nodes[1], 1);
6758         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6759
6760         let events = nodes[1].node.get_and_clear_pending_msg_events();
6761         assert_eq!(events.len(), 1);
6762         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6763                 match events[0] {
6764                         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, .. } } => {
6765                                 assert!(update_add_htlcs.is_empty());
6766                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6767                                 assert!(update_fail_htlcs.is_empty());
6768                                 assert!(update_fail_malformed_htlcs.is_empty());
6769                                 assert!(update_fee.is_none());
6770                                 update_fulfill_htlcs[0].clone()
6771                         },
6772                         _ => panic!("Unexpected event"),
6773                 }
6774         };
6775
6776         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6777
6778         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6779
6780         assert!(nodes[0].node.list_channels().is_empty());
6781         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6782         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6783         check_added_monitors!(nodes[0], 1);
6784         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6785 }
6786
6787 #[test]
6788 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6789         //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.
6790
6791         let chanmon_cfgs = create_chanmon_cfgs(2);
6792         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6793         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6794         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6795         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6796
6797         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6798         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6799                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6800         check_added_monitors!(nodes[0], 1);
6801
6802         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6803         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6804
6805         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6806         check_added_monitors!(nodes[1], 0);
6807         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6808
6809         let events = nodes[1].node.get_and_clear_pending_msg_events();
6810
6811         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6812                 match events[0] {
6813                         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, .. } } => {
6814                                 assert!(update_add_htlcs.is_empty());
6815                                 assert!(update_fulfill_htlcs.is_empty());
6816                                 assert!(update_fail_htlcs.is_empty());
6817                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6818                                 assert!(update_fee.is_none());
6819                                 update_fail_malformed_htlcs[0].clone()
6820                         },
6821                         _ => panic!("Unexpected event"),
6822                 }
6823         };
6824         update_msg.failure_code &= !0x8000;
6825         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6826
6827         assert!(nodes[0].node.list_channels().is_empty());
6828         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6829         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6830         check_added_monitors!(nodes[0], 1);
6831         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6832 }
6833
6834 #[test]
6835 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6836         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6837         //    * 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.
6838
6839         let chanmon_cfgs = create_chanmon_cfgs(3);
6840         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6841         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6842         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6843         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6844         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6845
6846         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6847
6848         //First hop
6849         let mut payment_event = {
6850                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6851                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6852                 check_added_monitors!(nodes[0], 1);
6853                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6854                 assert_eq!(events.len(), 1);
6855                 SendEvent::from_event(events.remove(0))
6856         };
6857         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6858         check_added_monitors!(nodes[1], 0);
6859         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6860         expect_pending_htlcs_forwardable!(nodes[1]);
6861         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6862         assert_eq!(events_2.len(), 1);
6863         check_added_monitors!(nodes[1], 1);
6864         payment_event = SendEvent::from_event(events_2.remove(0));
6865         assert_eq!(payment_event.msgs.len(), 1);
6866
6867         //Second Hop
6868         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6869         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6870         check_added_monitors!(nodes[2], 0);
6871         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6872
6873         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6874         assert_eq!(events_3.len(), 1);
6875         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6876                 match events_3[0] {
6877                         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 } } => {
6878                                 assert!(update_add_htlcs.is_empty());
6879                                 assert!(update_fulfill_htlcs.is_empty());
6880                                 assert!(update_fail_htlcs.is_empty());
6881                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6882                                 assert!(update_fee.is_none());
6883                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6884                         },
6885                         _ => panic!("Unexpected event"),
6886                 }
6887         };
6888
6889         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6890
6891         check_added_monitors!(nodes[1], 0);
6892         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6893         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 }]);
6894         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6895         assert_eq!(events_4.len(), 1);
6896
6897         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6898         match events_4[0] {
6899                 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, .. } } => {
6900                         assert!(update_add_htlcs.is_empty());
6901                         assert!(update_fulfill_htlcs.is_empty());
6902                         assert_eq!(update_fail_htlcs.len(), 1);
6903                         assert!(update_fail_malformed_htlcs.is_empty());
6904                         assert!(update_fee.is_none());
6905                 },
6906                 _ => panic!("Unexpected event"),
6907         };
6908
6909         check_added_monitors!(nodes[1], 1);
6910 }
6911
6912 #[test]
6913 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6914         let chanmon_cfgs = create_chanmon_cfgs(3);
6915         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6916         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6917         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6918         create_announced_chan_between_nodes(&nodes, 0, 1);
6919         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6920
6921         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6922
6923         // First hop
6924         let mut payment_event = {
6925                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6926                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6927                 check_added_monitors!(nodes[0], 1);
6928                 SendEvent::from_node(&nodes[0])
6929         };
6930
6931         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6932         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6933         expect_pending_htlcs_forwardable!(nodes[1]);
6934         check_added_monitors!(nodes[1], 1);
6935         payment_event = SendEvent::from_node(&nodes[1]);
6936         assert_eq!(payment_event.msgs.len(), 1);
6937
6938         // Second Hop
6939         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6940         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6941         check_added_monitors!(nodes[2], 0);
6942         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6943
6944         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6945         assert_eq!(events_3.len(), 1);
6946         match events_3[0] {
6947                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6948                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6949                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6950                         update_msg.failure_code |= 0x2000;
6951
6952                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6953                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6954                 },
6955                 _ => panic!("Unexpected event"),
6956         }
6957
6958         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6959                 vec![HTLCDestination::NextHopChannel {
6960                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6961         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6962         assert_eq!(events_4.len(), 1);
6963         check_added_monitors!(nodes[1], 1);
6964
6965         match events_4[0] {
6966                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6967                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6968                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6969                 },
6970                 _ => panic!("Unexpected event"),
6971         }
6972
6973         let events_5 = nodes[0].node.get_and_clear_pending_events();
6974         assert_eq!(events_5.len(), 2);
6975
6976         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6977         // the node originating the error to its next hop.
6978         match events_5[0] {
6979                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6980                 } => {
6981                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6982                         assert!(is_permanent);
6983                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6984                 },
6985                 _ => panic!("Unexpected event"),
6986         }
6987         match events_5[1] {
6988                 Event::PaymentFailed { payment_hash, .. } => {
6989                         assert_eq!(payment_hash, our_payment_hash);
6990                 },
6991                 _ => panic!("Unexpected event"),
6992         }
6993
6994         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6995 }
6996
6997 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6998         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6999         // 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
7000         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7001
7002         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7003         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7004         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7005         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7006         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7007         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7008
7009         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7010                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7011
7012         // We route 2 dust-HTLCs between A and B
7013         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7014         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7015         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7016
7017         // Cache one local commitment tx as previous
7018         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7019
7020         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7021         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7022         check_added_monitors!(nodes[1], 0);
7023         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7024         check_added_monitors!(nodes[1], 1);
7025
7026         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7027         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7028         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7029         check_added_monitors!(nodes[0], 1);
7030
7031         // Cache one local commitment tx as lastest
7032         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7033
7034         let events = nodes[0].node.get_and_clear_pending_msg_events();
7035         match events[0] {
7036                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7037                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7038                 },
7039                 _ => panic!("Unexpected event"),
7040         }
7041         match events[1] {
7042                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7043                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7044                 },
7045                 _ => panic!("Unexpected event"),
7046         }
7047
7048         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7049         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7050         if announce_latest {
7051                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7052         } else {
7053                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7054         }
7055
7056         check_closed_broadcast!(nodes[0], true);
7057         check_added_monitors!(nodes[0], 1);
7058         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7059
7060         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7061         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7062         let events = nodes[0].node.get_and_clear_pending_events();
7063         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7064         assert_eq!(events.len(), 4);
7065         let mut first_failed = false;
7066         for event in events {
7067                 match event {
7068                         Event::PaymentPathFailed { payment_hash, .. } => {
7069                                 if payment_hash == payment_hash_1 {
7070                                         assert!(!first_failed);
7071                                         first_failed = true;
7072                                 } else {
7073                                         assert_eq!(payment_hash, payment_hash_2);
7074                                 }
7075                         },
7076                         Event::PaymentFailed { .. } => {}
7077                         _ => panic!("Unexpected event"),
7078                 }
7079         }
7080 }
7081
7082 #[test]
7083 fn test_failure_delay_dust_htlc_local_commitment() {
7084         do_test_failure_delay_dust_htlc_local_commitment(true);
7085         do_test_failure_delay_dust_htlc_local_commitment(false);
7086 }
7087
7088 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7089         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7090         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7091         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7092         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7093         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7094         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7095
7096         let chanmon_cfgs = create_chanmon_cfgs(3);
7097         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7098         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7099         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7100         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7101
7102         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7103                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7104
7105         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7106         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7107
7108         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7109         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7110
7111         // We revoked bs_commitment_tx
7112         if revoked {
7113                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7114                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7115         }
7116
7117         let mut timeout_tx = Vec::new();
7118         if local {
7119                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7120                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7121                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7122                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7123                 expect_payment_failed!(nodes[0], dust_hash, false);
7124
7125                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7126                 check_closed_broadcast!(nodes[0], true);
7127                 check_added_monitors!(nodes[0], 1);
7128                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7129                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7130                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7131                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7132                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7133                 mine_transaction(&nodes[0], &timeout_tx[0]);
7134                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7135                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7136         } else {
7137                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7138                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7139                 check_closed_broadcast!(nodes[0], true);
7140                 check_added_monitors!(nodes[0], 1);
7141                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7142                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7143
7144                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7145                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7146                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7147                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7148                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7149                 // dust HTLC should have been failed.
7150                 expect_payment_failed!(nodes[0], dust_hash, false);
7151
7152                 if !revoked {
7153                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7154                 } else {
7155                         assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7156                 }
7157                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7158                 mine_transaction(&nodes[0], &timeout_tx[0]);
7159                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7160                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7161                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7162         }
7163 }
7164
7165 #[test]
7166 fn test_sweep_outbound_htlc_failure_update() {
7167         do_test_sweep_outbound_htlc_failure_update(false, true);
7168         do_test_sweep_outbound_htlc_failure_update(false, false);
7169         do_test_sweep_outbound_htlc_failure_update(true, false);
7170 }
7171
7172 #[test]
7173 fn test_user_configurable_csv_delay() {
7174         // We test our channel constructors yield errors when we pass them absurd csv delay
7175
7176         let mut low_our_to_self_config = UserConfig::default();
7177         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7178         let mut high_their_to_self_config = UserConfig::default();
7179         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7180         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7181         let chanmon_cfgs = create_chanmon_cfgs(2);
7182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7184         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7185
7186         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7187         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7188                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7189                 &low_our_to_self_config, 0, 42, None)
7190         {
7191                 match error {
7192                         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())); },
7193                         _ => panic!("Unexpected event"),
7194                 }
7195         } else { assert!(false) }
7196
7197         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7198         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7199         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7200         open_channel.to_self_delay = 200;
7201         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7202                 &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,
7203                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7204         {
7205                 match error {
7206                         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()));  },
7207                         _ => panic!("Unexpected event"),
7208                 }
7209         } else { assert!(false); }
7210
7211         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7212         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7213         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()));
7214         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7215         accept_channel.to_self_delay = 200;
7216         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7217         let reason_msg;
7218         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7219                 match action {
7220                         &ErrorAction::SendErrorMessage { ref msg } => {
7221                                 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()));
7222                                 reason_msg = msg.data.clone();
7223                         },
7224                         _ => { panic!(); }
7225                 }
7226         } else { panic!(); }
7227         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7228
7229         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7230         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7231         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7232         open_channel.to_self_delay = 200;
7233         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7234                 &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,
7235                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7236         {
7237                 match error {
7238                         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())); },
7239                         _ => panic!("Unexpected event"),
7240                 }
7241         } else { assert!(false); }
7242 }
7243
7244 #[test]
7245 fn test_check_htlc_underpaying() {
7246         // Send payment through A -> B but A is maliciously
7247         // sending a probe payment (i.e less than expected value0
7248         // to B, B should refuse payment.
7249
7250         let chanmon_cfgs = create_chanmon_cfgs(2);
7251         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7252         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7253         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7254
7255         // Create some initial channels
7256         create_announced_chan_between_nodes(&nodes, 0, 1);
7257
7258         let scorer = test_utils::TestScorer::new();
7259         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7260         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7261                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7262         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7263         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7264                 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7265         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7266         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7267         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7268                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7269         check_added_monitors!(nodes[0], 1);
7270
7271         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7272         assert_eq!(events.len(), 1);
7273         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7274         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7275         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7276
7277         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7278         // and then will wait a second random delay before failing the HTLC back:
7279         expect_pending_htlcs_forwardable!(nodes[1]);
7280         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7281
7282         // Node 3 is expecting payment of 100_000 but received 10_000,
7283         // it should fail htlc like we didn't know the preimage.
7284         nodes[1].node.process_pending_htlc_forwards();
7285
7286         let events = nodes[1].node.get_and_clear_pending_msg_events();
7287         assert_eq!(events.len(), 1);
7288         let (update_fail_htlc, commitment_signed) = match events[0] {
7289                 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 } } => {
7290                         assert!(update_add_htlcs.is_empty());
7291                         assert!(update_fulfill_htlcs.is_empty());
7292                         assert_eq!(update_fail_htlcs.len(), 1);
7293                         assert!(update_fail_malformed_htlcs.is_empty());
7294                         assert!(update_fee.is_none());
7295                         (update_fail_htlcs[0].clone(), commitment_signed)
7296                 },
7297                 _ => panic!("Unexpected event"),
7298         };
7299         check_added_monitors!(nodes[1], 1);
7300
7301         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7302         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7303
7304         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7305         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7306         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7307         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7308 }
7309
7310 #[test]
7311 fn test_announce_disable_channels() {
7312         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7313         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7314
7315         let chanmon_cfgs = create_chanmon_cfgs(2);
7316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7318         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7319
7320         create_announced_chan_between_nodes(&nodes, 0, 1);
7321         create_announced_chan_between_nodes(&nodes, 1, 0);
7322         create_announced_chan_between_nodes(&nodes, 0, 1);
7323
7324         // Disconnect peers
7325         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7326         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7327
7328         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7329                 nodes[0].node.timer_tick_occurred();
7330         }
7331         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7332         assert_eq!(msg_events.len(), 3);
7333         let mut chans_disabled = HashMap::new();
7334         for e in msg_events {
7335                 match e {
7336                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7337                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7338                                 // Check that each channel gets updated exactly once
7339                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7340                                         panic!("Generated ChannelUpdate for wrong chan!");
7341                                 }
7342                         },
7343                         _ => panic!("Unexpected event"),
7344                 }
7345         }
7346         // Reconnect peers
7347         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7348                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7349         }, true).unwrap();
7350         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7351         assert_eq!(reestablish_1.len(), 3);
7352         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7353                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7354         }, false).unwrap();
7355         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7356         assert_eq!(reestablish_2.len(), 3);
7357
7358         // Reestablish chan_1
7359         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7360         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7361         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7362         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7363         // Reestablish chan_2
7364         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7365         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7366         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7367         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7368         // Reestablish chan_3
7369         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7370         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7371         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7372         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7373
7374         for _ in 0..ENABLE_GOSSIP_TICKS {
7375                 nodes[0].node.timer_tick_occurred();
7376         }
7377         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7378         nodes[0].node.timer_tick_occurred();
7379         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7380         assert_eq!(msg_events.len(), 3);
7381         for e in msg_events {
7382                 match e {
7383                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7384                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7385                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7386                                         // Each update should have a higher timestamp than the previous one, replacing
7387                                         // the old one.
7388                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7389                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7390                                 }
7391                         },
7392                         _ => panic!("Unexpected event"),
7393                 }
7394         }
7395         // Check that each channel gets updated exactly once
7396         assert!(chans_disabled.is_empty());
7397 }
7398
7399 #[test]
7400 fn test_bump_penalty_txn_on_revoked_commitment() {
7401         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7402         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7403
7404         let chanmon_cfgs = create_chanmon_cfgs(2);
7405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7407         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7408
7409         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7410
7411         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7412         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7413                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7414         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7415         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7416
7417         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7418         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7419         assert_eq!(revoked_txn[0].output.len(), 4);
7420         assert_eq!(revoked_txn[0].input.len(), 1);
7421         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7422         let revoked_txid = revoked_txn[0].txid();
7423
7424         let mut penalty_sum = 0;
7425         for outp in revoked_txn[0].output.iter() {
7426                 if outp.script_pubkey.is_v0_p2wsh() {
7427                         penalty_sum += outp.value;
7428                 }
7429         }
7430
7431         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7432         let header_114 = connect_blocks(&nodes[1], 14);
7433
7434         // Actually revoke tx by claiming a HTLC
7435         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7436         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7437         check_added_monitors!(nodes[1], 1);
7438
7439         // One or more justice tx should have been broadcast, check it
7440         let penalty_1;
7441         let feerate_1;
7442         {
7443                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7444                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7445                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7446                 assert_eq!(node_txn[0].output.len(), 1);
7447                 check_spends!(node_txn[0], revoked_txn[0]);
7448                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7449                 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7450                 penalty_1 = node_txn[0].txid();
7451                 node_txn.clear();
7452         };
7453
7454         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7455         connect_blocks(&nodes[1], 15);
7456         let mut penalty_2 = penalty_1;
7457         let mut feerate_2 = 0;
7458         {
7459                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7460                 assert_eq!(node_txn.len(), 1);
7461                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7462                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7463                         assert_eq!(node_txn[0].output.len(), 1);
7464                         check_spends!(node_txn[0], revoked_txn[0]);
7465                         penalty_2 = node_txn[0].txid();
7466                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7467                         assert_ne!(penalty_2, penalty_1);
7468                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7469                         feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7470                         // Verify 25% bump heuristic
7471                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7472                         node_txn.clear();
7473                 }
7474         }
7475         assert_ne!(feerate_2, 0);
7476
7477         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7478         connect_blocks(&nodes[1], 1);
7479         let penalty_3;
7480         let mut feerate_3 = 0;
7481         {
7482                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7483                 assert_eq!(node_txn.len(), 1);
7484                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7485                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7486                         assert_eq!(node_txn[0].output.len(), 1);
7487                         check_spends!(node_txn[0], revoked_txn[0]);
7488                         penalty_3 = node_txn[0].txid();
7489                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7490                         assert_ne!(penalty_3, penalty_2);
7491                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7492                         feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7493                         // Verify 25% bump heuristic
7494                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7495                         node_txn.clear();
7496                 }
7497         }
7498         assert_ne!(feerate_3, 0);
7499
7500         nodes[1].node.get_and_clear_pending_events();
7501         nodes[1].node.get_and_clear_pending_msg_events();
7502 }
7503
7504 #[test]
7505 fn test_bump_penalty_txn_on_revoked_htlcs() {
7506         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7507         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7508
7509         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7510         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7511         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7512         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7513         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7514
7515         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7516         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7517         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7518         let scorer = test_utils::TestScorer::new();
7519         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7520         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7521         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7522                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7523         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7524         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7525                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7526         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7527         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7528                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7529         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7530
7531         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7532         assert_eq!(revoked_local_txn[0].input.len(), 1);
7533         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7534
7535         // Revoke local commitment tx
7536         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7537
7538         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7539         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7540         check_closed_broadcast!(nodes[1], true);
7541         check_added_monitors!(nodes[1], 1);
7542         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7543         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7544
7545         let revoked_htlc_txn = {
7546                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7547                 assert_eq!(txn.len(), 2);
7548
7549                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7550                 assert_eq!(txn[0].input.len(), 1);
7551                 check_spends!(txn[0], revoked_local_txn[0]);
7552
7553                 assert_eq!(txn[1].input.len(), 1);
7554                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7555                 assert_eq!(txn[1].output.len(), 1);
7556                 check_spends!(txn[1], revoked_local_txn[0]);
7557
7558                 txn
7559         };
7560
7561         // Broadcast set of revoked txn on A
7562         let hash_128 = connect_blocks(&nodes[0], 40);
7563         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7564         connect_block(&nodes[0], &block_11);
7565         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7566         connect_block(&nodes[0], &block_129);
7567         let events = nodes[0].node.get_and_clear_pending_events();
7568         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7569         match events.last().unwrap() {
7570                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7571                 _ => panic!("Unexpected event"),
7572         }
7573         let first;
7574         let feerate_1;
7575         let penalty_txn;
7576         {
7577                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7578                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7579                 // Verify claim tx are spending revoked HTLC txn
7580
7581                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7582                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7583                 // which are included in the same block (they are broadcasted because we scan the
7584                 // transactions linearly and generate claims as we go, they likely should be removed in the
7585                 // future).
7586                 assert_eq!(node_txn[0].input.len(), 1);
7587                 check_spends!(node_txn[0], revoked_local_txn[0]);
7588                 assert_eq!(node_txn[1].input.len(), 1);
7589                 check_spends!(node_txn[1], revoked_local_txn[0]);
7590                 assert_eq!(node_txn[2].input.len(), 1);
7591                 check_spends!(node_txn[2], revoked_local_txn[0]);
7592
7593                 // Each of the three justice transactions claim a separate (single) output of the three
7594                 // available, which we check here:
7595                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7596                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7597                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7598
7599                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7600                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7601
7602                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7603                 // output, checked above).
7604                 assert_eq!(node_txn[3].input.len(), 2);
7605                 assert_eq!(node_txn[3].output.len(), 1);
7606                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7607
7608                 first = node_txn[3].txid();
7609                 // Store both feerates for later comparison
7610                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7611                 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7612                 penalty_txn = vec![node_txn[2].clone()];
7613                 node_txn.clear();
7614         }
7615
7616         // Connect one more block to see if bumped penalty are issued for HTLC txn
7617         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7618         connect_block(&nodes[0], &block_130);
7619         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7620         connect_block(&nodes[0], &block_131);
7621
7622         // Few more blocks to confirm penalty txn
7623         connect_blocks(&nodes[0], 4);
7624         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7625         let header_144 = connect_blocks(&nodes[0], 9);
7626         let node_txn = {
7627                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7628                 assert_eq!(node_txn.len(), 1);
7629
7630                 assert_eq!(node_txn[0].input.len(), 2);
7631                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7632                 // Verify bumped tx is different and 25% bump heuristic
7633                 assert_ne!(first, node_txn[0].txid());
7634                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7635                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7636                 assert!(feerate_2 * 100 > feerate_1 * 125);
7637                 let txn = vec![node_txn[0].clone()];
7638                 node_txn.clear();
7639                 txn
7640         };
7641         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7642         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7643         connect_blocks(&nodes[0], 20);
7644         {
7645                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7646                 // We verify than no new transaction has been broadcast because previously
7647                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7648                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7649                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7650                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7651                 // up bumped justice generation.
7652                 assert_eq!(node_txn.len(), 0);
7653                 node_txn.clear();
7654         }
7655         check_closed_broadcast!(nodes[0], true);
7656         check_added_monitors!(nodes[0], 1);
7657 }
7658
7659 #[test]
7660 fn test_bump_penalty_txn_on_remote_commitment() {
7661         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7662         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7663
7664         // Create 2 HTLCs
7665         // Provide preimage for one
7666         // Check aggregation
7667
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
7673         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7674         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7675         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7676
7677         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7678         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7679         assert_eq!(remote_txn[0].output.len(), 4);
7680         assert_eq!(remote_txn[0].input.len(), 1);
7681         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7682
7683         // Claim a HTLC without revocation (provide B monitor with preimage)
7684         nodes[1].node.claim_funds(payment_preimage);
7685         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7686         mine_transaction(&nodes[1], &remote_txn[0]);
7687         check_added_monitors!(nodes[1], 2);
7688         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7689
7690         // One or more claim tx should have been broadcast, check it
7691         let timeout;
7692         let preimage;
7693         let preimage_bump;
7694         let feerate_timeout;
7695         let feerate_preimage;
7696         {
7697                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7698                 // 3 transactions including:
7699                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7700                 assert_eq!(node_txn.len(), 3);
7701                 assert_eq!(node_txn[0].input.len(), 1);
7702                 assert_eq!(node_txn[1].input.len(), 1);
7703                 assert_eq!(node_txn[2].input.len(), 1);
7704                 check_spends!(node_txn[0], remote_txn[0]);
7705                 check_spends!(node_txn[1], remote_txn[0]);
7706                 check_spends!(node_txn[2], remote_txn[0]);
7707
7708                 preimage = node_txn[0].txid();
7709                 let index = node_txn[0].input[0].previous_output.vout;
7710                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7711                 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7712
7713                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7714                         (node_txn[2].clone(), node_txn[1].clone())
7715                 } else {
7716                         (node_txn[1].clone(), node_txn[2].clone())
7717                 };
7718
7719                 preimage_bump = preimage_bump_tx;
7720                 check_spends!(preimage_bump, remote_txn[0]);
7721                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7722
7723                 timeout = timeout_tx.txid();
7724                 let index = timeout_tx.input[0].previous_output.vout;
7725                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7726                 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7727
7728                 node_txn.clear();
7729         };
7730         assert_ne!(feerate_timeout, 0);
7731         assert_ne!(feerate_preimage, 0);
7732
7733         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7734         connect_blocks(&nodes[1], 1);
7735         {
7736                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7737                 assert_eq!(node_txn.len(), 1);
7738                 assert_eq!(node_txn[0].input.len(), 1);
7739                 assert_eq!(preimage_bump.input.len(), 1);
7740                 check_spends!(node_txn[0], remote_txn[0]);
7741                 check_spends!(preimage_bump, remote_txn[0]);
7742
7743                 let index = preimage_bump.input[0].previous_output.vout;
7744                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7745                 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7746                 assert!(new_feerate * 100 > feerate_timeout * 125);
7747                 assert_ne!(timeout, preimage_bump.txid());
7748
7749                 let index = node_txn[0].input[0].previous_output.vout;
7750                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7751                 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7752                 assert!(new_feerate * 100 > feerate_preimage * 125);
7753                 assert_ne!(preimage, node_txn[0].txid());
7754
7755                 node_txn.clear();
7756         }
7757
7758         nodes[1].node.get_and_clear_pending_events();
7759         nodes[1].node.get_and_clear_pending_msg_events();
7760 }
7761
7762 #[test]
7763 fn test_counterparty_raa_skip_no_crash() {
7764         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7765         // commitment transaction, we would have happily carried on and provided them the next
7766         // commitment transaction based on one RAA forward. This would probably eventually have led to
7767         // channel closure, but it would not have resulted in funds loss. Still, our
7768         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7769         // check simply that the channel is closed in response to such an RAA, but don't check whether
7770         // we decide to punish our counterparty for revoking their funds (as we don't currently
7771         // implement that).
7772         let chanmon_cfgs = create_chanmon_cfgs(2);
7773         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7774         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7775         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7776         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7777
7778         let per_commitment_secret;
7779         let next_per_commitment_point;
7780         {
7781                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7782                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7783                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7784                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7785                 ).flatten().unwrap().get_signer();
7786
7787                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7788
7789                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7790                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7791                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7792
7793                 // Must revoke without gaps
7794                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7795                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7796
7797                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7798                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7799                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7800         }
7801
7802         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7803                 &msgs::RevokeAndACK {
7804                         channel_id,
7805                         per_commitment_secret,
7806                         next_per_commitment_point,
7807                         #[cfg(taproot)]
7808                         next_local_nonce: None,
7809                 });
7810         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7811         check_added_monitors!(nodes[1], 1);
7812         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7813                 , [nodes[0].node.get_our_node_id()], 100000);
7814 }
7815
7816 #[test]
7817 fn test_bump_txn_sanitize_tracking_maps() {
7818         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7819         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7820
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, None]);
7824         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7825
7826         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7827         // Lock HTLC in both directions
7828         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7829         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7830
7831         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7832         assert_eq!(revoked_local_txn[0].input.len(), 1);
7833         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7834
7835         // Revoke local commitment tx
7836         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7837
7838         // Broadcast set of revoked txn on A
7839         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7840         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7841         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7842
7843         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7844         check_closed_broadcast!(nodes[0], true);
7845         check_added_monitors!(nodes[0], 1);
7846         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7847         let penalty_txn = {
7848                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7849                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7850                 check_spends!(node_txn[0], revoked_local_txn[0]);
7851                 check_spends!(node_txn[1], revoked_local_txn[0]);
7852                 check_spends!(node_txn[2], revoked_local_txn[0]);
7853                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7854                 node_txn.clear();
7855                 penalty_txn
7856         };
7857         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7858         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7859         {
7860                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7861                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7862                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7863         }
7864 }
7865
7866 #[test]
7867 fn test_channel_conf_timeout() {
7868         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7869         // confirm within 2016 blocks, as recommended by BOLT 2.
7870         let chanmon_cfgs = create_chanmon_cfgs(2);
7871         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7872         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7873         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7874
7875         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7876
7877         // The outbound node should wait forever for confirmation:
7878         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7879         // copied here instead of directly referencing the constant.
7880         connect_blocks(&nodes[0], 2016);
7881         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7882
7883         // The inbound node should fail the channel after exactly 2016 blocks
7884         connect_blocks(&nodes[1], 2015);
7885         check_added_monitors!(nodes[1], 0);
7886         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7887
7888         connect_blocks(&nodes[1], 1);
7889         check_added_monitors!(nodes[1], 1);
7890         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7891         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7892         assert_eq!(close_ev.len(), 1);
7893         match close_ev[0] {
7894                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7895                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7896                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7897                 },
7898                 _ => panic!("Unexpected event"),
7899         }
7900 }
7901
7902 #[test]
7903 fn test_override_channel_config() {
7904         let chanmon_cfgs = create_chanmon_cfgs(2);
7905         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7906         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7907         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7908
7909         // Node0 initiates a channel to node1 using the override config.
7910         let mut override_config = UserConfig::default();
7911         override_config.channel_handshake_config.our_to_self_delay = 200;
7912
7913         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7914
7915         // Assert the channel created by node0 is using the override config.
7916         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7917         assert_eq!(res.channel_flags, 0);
7918         assert_eq!(res.to_self_delay, 200);
7919 }
7920
7921 #[test]
7922 fn test_override_0msat_htlc_minimum() {
7923         let mut zero_config = UserConfig::default();
7924         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7925         let chanmon_cfgs = create_chanmon_cfgs(2);
7926         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7927         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7928         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7929
7930         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7931         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7932         assert_eq!(res.htlc_minimum_msat, 1);
7933
7934         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7935         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7936         assert_eq!(res.htlc_minimum_msat, 1);
7937 }
7938
7939 #[test]
7940 fn test_channel_update_has_correct_htlc_maximum_msat() {
7941         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7942         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7943         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7944         // 90% of the `channel_value`.
7945         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7946
7947         let mut config_30_percent = UserConfig::default();
7948         config_30_percent.channel_handshake_config.announced_channel = true;
7949         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7950         let mut config_50_percent = UserConfig::default();
7951         config_50_percent.channel_handshake_config.announced_channel = true;
7952         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7953         let mut config_95_percent = UserConfig::default();
7954         config_95_percent.channel_handshake_config.announced_channel = true;
7955         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7956         let mut config_100_percent = UserConfig::default();
7957         config_100_percent.channel_handshake_config.announced_channel = true;
7958         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7959
7960         let chanmon_cfgs = create_chanmon_cfgs(4);
7961         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7962         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)]);
7963         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7964
7965         let channel_value_satoshis = 100000;
7966         let channel_value_msat = channel_value_satoshis * 1000;
7967         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7968         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7969         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7970
7971         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7972         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7973
7974         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7975         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7976         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7977         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7978         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7979         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7980
7981         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7982         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7983         // `channel_value`.
7984         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7985         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7986         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7987         // `channel_value`.
7988         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7989 }
7990
7991 #[test]
7992 fn test_manually_accept_inbound_channel_request() {
7993         let mut manually_accept_conf = UserConfig::default();
7994         manually_accept_conf.manually_accept_inbound_channels = true;
7995         let chanmon_cfgs = create_chanmon_cfgs(2);
7996         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7997         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7998         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7999
8000         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8001         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8002
8003         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8004
8005         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8006         // accepting the inbound channel request.
8007         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8008
8009         let events = nodes[1].node.get_and_clear_pending_events();
8010         match events[0] {
8011                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8012                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8013                 }
8014                 _ => panic!("Unexpected event"),
8015         }
8016
8017         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8018         assert_eq!(accept_msg_ev.len(), 1);
8019
8020         match accept_msg_ev[0] {
8021                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8022                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8023                 }
8024                 _ => panic!("Unexpected event"),
8025         }
8026
8027         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8028
8029         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8030         assert_eq!(close_msg_ev.len(), 1);
8031
8032         let events = nodes[1].node.get_and_clear_pending_events();
8033         match events[0] {
8034                 Event::ChannelClosed { user_channel_id, .. } => {
8035                         assert_eq!(user_channel_id, 23);
8036                 }
8037                 _ => panic!("Unexpected event"),
8038         }
8039 }
8040
8041 #[test]
8042 fn test_manually_reject_inbound_channel_request() {
8043         let mut manually_accept_conf = UserConfig::default();
8044         manually_accept_conf.manually_accept_inbound_channels = true;
8045         let chanmon_cfgs = create_chanmon_cfgs(2);
8046         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8047         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8048         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8049
8050         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8051         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8052
8053         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8054
8055         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8056         // rejecting the inbound channel request.
8057         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8058
8059         let events = nodes[1].node.get_and_clear_pending_events();
8060         match events[0] {
8061                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8062                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8063                 }
8064                 _ => panic!("Unexpected event"),
8065         }
8066
8067         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8068         assert_eq!(close_msg_ev.len(), 1);
8069
8070         match close_msg_ev[0] {
8071                 MessageSendEvent::HandleError { ref node_id, .. } => {
8072                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8073                 }
8074                 _ => panic!("Unexpected event"),
8075         }
8076
8077         // There should be no more events to process, as the channel was never opened.
8078         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8079 }
8080
8081 #[test]
8082 fn test_can_not_accept_inbound_channel_twice() {
8083         let mut manually_accept_conf = UserConfig::default();
8084         manually_accept_conf.manually_accept_inbound_channels = true;
8085         let chanmon_cfgs = create_chanmon_cfgs(2);
8086         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8087         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8088         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8089
8090         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8091         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8092
8093         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8094
8095         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8096         // accepting the inbound channel request.
8097         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8098
8099         let events = nodes[1].node.get_and_clear_pending_events();
8100         match events[0] {
8101                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8102                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8103                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8104                         match api_res {
8105                                 Err(APIError::APIMisuseError { err }) => {
8106                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8107                                 },
8108                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8109                                 Err(e) => panic!("Unexpected Error {:?}", e),
8110                         }
8111                 }
8112                 _ => panic!("Unexpected event"),
8113         }
8114
8115         // Ensure that the channel wasn't closed after attempting to accept it twice.
8116         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8117         assert_eq!(accept_msg_ev.len(), 1);
8118
8119         match accept_msg_ev[0] {
8120                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8121                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8122                 }
8123                 _ => panic!("Unexpected event"),
8124         }
8125 }
8126
8127 #[test]
8128 fn test_can_not_accept_unknown_inbound_channel() {
8129         let chanmon_cfg = create_chanmon_cfgs(2);
8130         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8131         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8132         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8133
8134         let unknown_channel_id = ChannelId::new_zero();
8135         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8136         match api_res {
8137                 Err(APIError::APIMisuseError { err }) => {
8138                         assert_eq!(err, "No such channel awaiting to be accepted.");
8139                 },
8140                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8141                 Err(e) => panic!("Unexpected Error: {:?}", e),
8142         }
8143 }
8144
8145 #[test]
8146 fn test_onion_value_mpp_set_calculation() {
8147         // Test that we use the onion value `amt_to_forward` when
8148         // calculating whether we've reached the `total_msat` of an MPP
8149         // by having a routing node forward more than `amt_to_forward`
8150         // and checking that the receiving node doesn't generate
8151         // a PaymentClaimable event too early
8152         let node_count = 4;
8153         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8154         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8155         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8156         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8157
8158         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8159         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8160         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8161         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8162
8163         let total_msat = 100_000;
8164         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8165         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8166         let sample_path = route.paths.pop().unwrap();
8167
8168         let mut path_1 = sample_path.clone();
8169         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8170         path_1.hops[0].short_channel_id = chan_1_id;
8171         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8172         path_1.hops[1].short_channel_id = chan_3_id;
8173         path_1.hops[1].fee_msat = 100_000;
8174         route.paths.push(path_1);
8175
8176         let mut path_2 = sample_path.clone();
8177         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8178         path_2.hops[0].short_channel_id = chan_2_id;
8179         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8180         path_2.hops[1].short_channel_id = chan_4_id;
8181         path_2.hops[1].fee_msat = 1_000;
8182         route.paths.push(path_2);
8183
8184         // Send payment
8185         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8186         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8187                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8188         nodes[0].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[0], expected_paths.len());
8191
8192         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8193         assert_eq!(events.len(), expected_paths.len());
8194
8195         // First path
8196         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8197         let mut payment_event = SendEvent::from_event(ev);
8198         let mut prev_node = &nodes[0];
8199
8200         for (idx, &node) in expected_paths[0].iter().enumerate() {
8201                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8202
8203                 if idx == 0 { // routing node
8204                         let session_priv = [3; 32];
8205                         let height = nodes[0].best_block_info().1;
8206                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8207                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8208                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8209                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8210                         // Edit amt_to_forward to simulate the sender having set
8211                         // the final amount and the routing node taking less fee
8212                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8213                                 *amt_msat = 99_000;
8214                         } else { panic!() }
8215                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8216                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8217                 }
8218
8219                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8220                 check_added_monitors!(node, 0);
8221                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8222                 expect_pending_htlcs_forwardable!(node);
8223
8224                 if idx == 0 {
8225                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8226                         assert_eq!(events_2.len(), 1);
8227                         check_added_monitors!(node, 1);
8228                         payment_event = SendEvent::from_event(events_2.remove(0));
8229                         assert_eq!(payment_event.msgs.len(), 1);
8230                 } else {
8231                         let events_2 = node.node.get_and_clear_pending_events();
8232                         assert!(events_2.is_empty());
8233                 }
8234
8235                 prev_node = node;
8236         }
8237
8238         // Second path
8239         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8240         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8241
8242         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8243 }
8244
8245 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8246
8247         let routing_node_count = msat_amounts.len();
8248         let node_count = routing_node_count + 2;
8249
8250         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8251         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8252         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8253         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8254
8255         let src_idx = 0;
8256         let dst_idx = 1;
8257
8258         // Create channels for each amount
8259         let mut expected_paths = Vec::with_capacity(routing_node_count);
8260         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8261         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8262         for i in 0..routing_node_count {
8263                 let routing_node = 2 + i;
8264                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8265                 src_chan_ids.push(src_chan_id);
8266                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8267                 dst_chan_ids.push(dst_chan_id);
8268                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8269                 expected_paths.push(path);
8270         }
8271         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8272
8273         // Create a route for each amount
8274         let example_amount = 100000;
8275         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);
8276         let sample_path = route.paths.pop().unwrap();
8277         for i in 0..routing_node_count {
8278                 let routing_node = 2 + i;
8279                 let mut path = sample_path.clone();
8280                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8281                 path.hops[0].short_channel_id = src_chan_ids[i];
8282                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8283                 path.hops[1].short_channel_id = dst_chan_ids[i];
8284                 path.hops[1].fee_msat = msat_amounts[i];
8285                 route.paths.push(path);
8286         }
8287
8288         // Send payment with manually set total_msat
8289         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8290         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8291                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8292         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8293                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8294         check_added_monitors!(nodes[src_idx], expected_paths.len());
8295
8296         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8297         assert_eq!(events.len(), expected_paths.len());
8298         let mut amount_received = 0;
8299         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8300                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8301
8302                 let current_path_amount = msat_amounts[path_idx];
8303                 amount_received += current_path_amount;
8304                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8305                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8306         }
8307
8308         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8309 }
8310
8311 #[test]
8312 fn test_overshoot_mpp() {
8313         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8314         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8315 }
8316
8317 #[test]
8318 fn test_simple_mpp() {
8319         // Simple test of sending a multi-path payment.
8320         let chanmon_cfgs = create_chanmon_cfgs(4);
8321         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8322         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8323         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8324
8325         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8326         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8327         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8328         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8329
8330         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8331         let path = route.paths[0].clone();
8332         route.paths.push(path);
8333         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8334         route.paths[0].hops[0].short_channel_id = chan_1_id;
8335         route.paths[0].hops[1].short_channel_id = chan_3_id;
8336         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8337         route.paths[1].hops[0].short_channel_id = chan_2_id;
8338         route.paths[1].hops[1].short_channel_id = chan_4_id;
8339         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8340         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8341 }
8342
8343 #[test]
8344 fn test_preimage_storage() {
8345         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8346         let chanmon_cfgs = create_chanmon_cfgs(2);
8347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8349         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8350
8351         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8352
8353         {
8354                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8355                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8356                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8357                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8358                 check_added_monitors!(nodes[0], 1);
8359                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8360                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8361                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8362                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8363         }
8364         // Note that after leaving the above scope we have no knowledge of any arguments or return
8365         // values from previous calls.
8366         expect_pending_htlcs_forwardable!(nodes[1]);
8367         let events = nodes[1].node.get_and_clear_pending_events();
8368         assert_eq!(events.len(), 1);
8369         match events[0] {
8370                 Event::PaymentClaimable { ref purpose, .. } => {
8371                         match &purpose {
8372                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8373                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8374                                 },
8375                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8376                         }
8377                 },
8378                 _ => panic!("Unexpected event"),
8379         }
8380 }
8381
8382 #[test]
8383 fn test_bad_secret_hash() {
8384         // Simple test of unregistered payment hash/invalid payment secret handling
8385         let chanmon_cfgs = create_chanmon_cfgs(2);
8386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8389
8390         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8391
8392         let random_payment_hash = PaymentHash([42; 32]);
8393         let random_payment_secret = PaymentSecret([43; 32]);
8394         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8395         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8396
8397         // All the below cases should end up being handled exactly identically, so we macro the
8398         // resulting events.
8399         macro_rules! handle_unknown_invalid_payment_data {
8400                 ($payment_hash: expr) => {
8401                         check_added_monitors!(nodes[0], 1);
8402                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8403                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8404                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8405                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8406
8407                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8408                         // again to process the pending backwards-failure of the HTLC
8409                         expect_pending_htlcs_forwardable!(nodes[1]);
8410                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8411                         check_added_monitors!(nodes[1], 1);
8412
8413                         // We should fail the payment back
8414                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8415                         match events.pop().unwrap() {
8416                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8417                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8418                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8419                                 },
8420                                 _ => panic!("Unexpected event"),
8421                         }
8422                 }
8423         }
8424
8425         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8426         // Error data is the HTLC value (100,000) and current block height
8427         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8428
8429         // Send a payment with the right payment hash but the wrong payment secret
8430         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8431                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8432         handle_unknown_invalid_payment_data!(our_payment_hash);
8433         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8434
8435         // Send a payment with a random payment hash, but the right payment secret
8436         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8437                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8438         handle_unknown_invalid_payment_data!(random_payment_hash);
8439         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8440
8441         // Send a payment with a random payment hash and random payment secret
8442         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8443                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8444         handle_unknown_invalid_payment_data!(random_payment_hash);
8445         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8446 }
8447
8448 #[test]
8449 fn test_update_err_monitor_lockdown() {
8450         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8451         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8452         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8453         // error.
8454         //
8455         // This scenario may happen in a watchtower setup, where watchtower process a block height
8456         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8457         // commitment at same time.
8458
8459         let chanmon_cfgs = create_chanmon_cfgs(2);
8460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8462         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8463
8464         // Create some initial channel
8465         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8466         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8467
8468         // Rebalance the network to generate htlc in the two directions
8469         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8470
8471         // Route a HTLC from node 0 to node 1 (but don't settle)
8472         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8473
8474         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8475         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8476         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8477         let persister = test_utils::TestPersister::new();
8478         let watchtower = {
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), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8487                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8488                 watchtower
8489         };
8490         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8491         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8492         // transaction lock time requirements here.
8493         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8494         watchtower.chain_monitor.block_connected(&block, 200);
8495
8496         // Try to update ChannelMonitor
8497         nodes[1].node.claim_funds(preimage);
8498         check_added_monitors!(nodes[1], 1);
8499         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8500
8501         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8502         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8503         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8504         {
8505                 let mut node_0_per_peer_lock;
8506                 let mut node_0_peer_state_lock;
8507                 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) {
8508                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8509                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8510                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8511                         } else { assert!(false); }
8512                 } else {
8513                         assert!(false);
8514                 }
8515         }
8516         // Our local monitor is in-sync and hasn't processed yet timeout
8517         check_added_monitors!(nodes[0], 1);
8518         let events = nodes[0].node.get_and_clear_pending_events();
8519         assert_eq!(events.len(), 1);
8520 }
8521
8522 #[test]
8523 fn test_concurrent_monitor_claim() {
8524         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8525         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8526         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8527         // state N+1 confirms. Alice claims output from state N+1.
8528
8529         let chanmon_cfgs = create_chanmon_cfgs(2);
8530         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8531         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8532         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8533
8534         // Create some initial channel
8535         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8536         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8537
8538         // Rebalance the network to generate htlc in the two directions
8539         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8540
8541         // Route a HTLC from node 0 to node 1 (but don't settle)
8542         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8543
8544         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8545         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8546         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8547         let persister = test_utils::TestPersister::new();
8548         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8549                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8550         );
8551         let watchtower_alice = {
8552                 let new_monitor = {
8553                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8554                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8555                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8556                         assert!(new_monitor == *monitor);
8557                         new_monitor
8558                 };
8559                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8560                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8561                 watchtower
8562         };
8563         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8564         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8565         // requirements here.
8566         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8567         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8568         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8569
8570         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8571         let alice_state = {
8572                 let mut txn = alice_broadcaster.txn_broadcast();
8573                 assert_eq!(txn.len(), 2);
8574                 txn.remove(0)
8575         };
8576
8577         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8578         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8579         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8580         let persister = test_utils::TestPersister::new();
8581         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8582         let watchtower_bob = {
8583                 let new_monitor = {
8584                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8585                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8586                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8587                         assert!(new_monitor == *monitor);
8588                         new_monitor
8589                 };
8590                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8591                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8592                 watchtower
8593         };
8594         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8595
8596         // Route another payment to generate another update with still previous HTLC pending
8597         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8598         nodes[1].node.send_payment_with_route(&route, payment_hash,
8599                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8600         check_added_monitors!(nodes[1], 1);
8601
8602         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8603         assert_eq!(updates.update_add_htlcs.len(), 1);
8604         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8605         {
8606                 let mut node_0_per_peer_lock;
8607                 let mut node_0_peer_state_lock;
8608                 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) {
8609                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8610                                 // Watchtower Alice should already have seen the block and reject the update
8611                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8612                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8613                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8614                         } else { assert!(false); }
8615                 } else {
8616                         assert!(false);
8617                 }
8618         }
8619         // Our local monitor is in-sync and hasn't processed yet timeout
8620         check_added_monitors!(nodes[0], 1);
8621
8622         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8623         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8624
8625         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8626         let bob_state_y;
8627         {
8628                 let mut txn = bob_broadcaster.txn_broadcast();
8629                 assert_eq!(txn.len(), 2);
8630                 bob_state_y = txn.remove(0);
8631         };
8632
8633         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8634         let height = HTLC_TIMEOUT_BROADCAST + 1;
8635         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8636         check_closed_broadcast(&nodes[0], 1, true);
8637         check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8638                 [nodes[1].node.get_our_node_id()], 100000);
8639         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8640         check_added_monitors(&nodes[0], 1);
8641         {
8642                 let htlc_txn = alice_broadcaster.txn_broadcast();
8643                 assert_eq!(htlc_txn.len(), 2);
8644                 check_spends!(htlc_txn[0], bob_state_y);
8645                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8646                 // it. However, she should, because it now has an invalid parent.
8647                 check_spends!(htlc_txn[1], alice_state);
8648         }
8649 }
8650
8651 #[test]
8652 fn test_pre_lockin_no_chan_closed_update() {
8653         // Test that if a peer closes a channel in response to a funding_created message we don't
8654         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8655         // message).
8656         //
8657         // Doing so would imply a channel monitor update before the initial channel monitor
8658         // registration, violating our API guarantees.
8659         //
8660         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8661         // then opening a second channel with the same funding output as the first (which is not
8662         // rejected because the first channel does not exist in the ChannelManager) and closing it
8663         // before receiving funding_signed.
8664         let chanmon_cfgs = create_chanmon_cfgs(2);
8665         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8666         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8667         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8668
8669         // Create an initial channel
8670         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8671         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8672         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8673         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8674         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8675
8676         // Move the first channel through the funding flow...
8677         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8678
8679         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8680         check_added_monitors!(nodes[0], 0);
8681
8682         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8683         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8684         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8685         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8686         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8687                 [nodes[1].node.get_our_node_id()], 100000);
8688 }
8689
8690 #[test]
8691 fn test_htlc_no_detection() {
8692         // This test is a mutation to underscore the detection logic bug we had
8693         // before #653. HTLC value routed is above the remaining balance, thus
8694         // inverting HTLC and `to_remote` output. HTLC will come second and
8695         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8696         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8697         // outputs order detection for correct spending children filtring.
8698
8699         let chanmon_cfgs = create_chanmon_cfgs(2);
8700         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8701         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8702         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8703
8704         // Create some initial channels
8705         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8706
8707         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8708         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8709         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8710         assert_eq!(local_txn[0].input.len(), 1);
8711         assert_eq!(local_txn[0].output.len(), 3);
8712         check_spends!(local_txn[0], chan_1.3);
8713
8714         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8715         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8716         connect_block(&nodes[0], &block);
8717         // We deliberately connect the local tx twice as this should provoke a failure calling
8718         // this test before #653 fix.
8719         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8720         check_closed_broadcast!(nodes[0], true);
8721         check_added_monitors!(nodes[0], 1);
8722         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8723         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8724
8725         let htlc_timeout = {
8726                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8727                 assert_eq!(node_txn.len(), 1);
8728                 assert_eq!(node_txn[0].input.len(), 1);
8729                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8730                 check_spends!(node_txn[0], local_txn[0]);
8731                 node_txn[0].clone()
8732         };
8733
8734         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8735         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8736         expect_payment_failed!(nodes[0], our_payment_hash, false);
8737 }
8738
8739 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8740         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8741         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8742         // Carol, Alice would be the upstream node, and Carol the downstream.)
8743         //
8744         // Steps of the test:
8745         // 1) Alice sends a HTLC to Carol through Bob.
8746         // 2) Carol doesn't settle the HTLC.
8747         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8748         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8749         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8750         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8751         // 5) Carol release the preimage to Bob off-chain.
8752         // 6) Bob claims the offered output on the broadcasted commitment.
8753         let chanmon_cfgs = create_chanmon_cfgs(3);
8754         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8755         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8756         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8757
8758         // Create some initial channels
8759         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8760         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8761
8762         // Steps (1) and (2):
8763         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8764         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8765
8766         // Check that Alice's commitment transaction now contains an output for this HTLC.
8767         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8768         check_spends!(alice_txn[0], chan_ab.3);
8769         assert_eq!(alice_txn[0].output.len(), 2);
8770         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8771         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8772         assert_eq!(alice_txn.len(), 2);
8773
8774         // Steps (3) and (4):
8775         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8776         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8777         let mut force_closing_node = 0; // Alice force-closes
8778         let mut counterparty_node = 1; // Bob if Alice force-closes
8779
8780         // Bob force-closes
8781         if !broadcast_alice {
8782                 force_closing_node = 1;
8783                 counterparty_node = 0;
8784         }
8785         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8786         check_closed_broadcast!(nodes[force_closing_node], true);
8787         check_added_monitors!(nodes[force_closing_node], 1);
8788         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8789         if go_onchain_before_fulfill {
8790                 let txn_to_broadcast = match broadcast_alice {
8791                         true => alice_txn.clone(),
8792                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8793                 };
8794                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8795                 if broadcast_alice {
8796                         check_closed_broadcast!(nodes[1], true);
8797                         check_added_monitors!(nodes[1], 1);
8798                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8799                 }
8800         }
8801
8802         // Step (5):
8803         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8804         // process of removing the HTLC from their commitment transactions.
8805         nodes[2].node.claim_funds(payment_preimage);
8806         check_added_monitors!(nodes[2], 1);
8807         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8808
8809         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8810         assert!(carol_updates.update_add_htlcs.is_empty());
8811         assert!(carol_updates.update_fail_htlcs.is_empty());
8812         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8813         assert!(carol_updates.update_fee.is_none());
8814         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8815
8816         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8817         let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8818         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8819         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8820         if !go_onchain_before_fulfill && broadcast_alice {
8821                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8822                 assert_eq!(events.len(), 1);
8823                 match events[0] {
8824                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8825                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8826                         },
8827                         _ => panic!("Unexpected event"),
8828                 };
8829         }
8830         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8831         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8832         // Carol<->Bob's updated commitment transaction info.
8833         check_added_monitors!(nodes[1], 2);
8834
8835         let events = nodes[1].node.get_and_clear_pending_msg_events();
8836         assert_eq!(events.len(), 2);
8837         let bob_revocation = match events[0] {
8838                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8839                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8840                         (*msg).clone()
8841                 },
8842                 _ => panic!("Unexpected event"),
8843         };
8844         let bob_updates = match events[1] {
8845                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8846                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8847                         (*updates).clone()
8848                 },
8849                 _ => panic!("Unexpected event"),
8850         };
8851
8852         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8853         check_added_monitors!(nodes[2], 1);
8854         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8855         check_added_monitors!(nodes[2], 1);
8856
8857         let events = nodes[2].node.get_and_clear_pending_msg_events();
8858         assert_eq!(events.len(), 1);
8859         let carol_revocation = match events[0] {
8860                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8861                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8862                         (*msg).clone()
8863                 },
8864                 _ => panic!("Unexpected event"),
8865         };
8866         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8867         check_added_monitors!(nodes[1], 1);
8868
8869         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8870         // here's where we put said channel's commitment tx on-chain.
8871         let mut txn_to_broadcast = alice_txn.clone();
8872         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8873         if !go_onchain_before_fulfill {
8874                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8875                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8876                 if broadcast_alice {
8877                         check_closed_broadcast!(nodes[1], true);
8878                         check_added_monitors!(nodes[1], 1);
8879                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8880                 }
8881                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8882                 if broadcast_alice {
8883                         assert_eq!(bob_txn.len(), 1);
8884                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8885                 } else {
8886                         assert_eq!(bob_txn.len(), 2);
8887                         check_spends!(bob_txn[0], chan_ab.3);
8888                 }
8889         }
8890
8891         // Step (6):
8892         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8893         // broadcasted commitment transaction.
8894         {
8895                 let script_weight = match broadcast_alice {
8896                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8897                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8898                 };
8899                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8900                 // Bob force-closed and broadcasts the commitment transaction along with a
8901                 // HTLC-output-claiming transaction.
8902                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8903                 if broadcast_alice {
8904                         assert_eq!(bob_txn.len(), 1);
8905                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8906                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8907                 } else {
8908                         assert_eq!(bob_txn.len(), 2);
8909                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8910                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8911                 }
8912         }
8913 }
8914
8915 #[test]
8916 fn test_onchain_htlc_settlement_after_close() {
8917         do_test_onchain_htlc_settlement_after_close(true, true);
8918         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8919         do_test_onchain_htlc_settlement_after_close(true, false);
8920         do_test_onchain_htlc_settlement_after_close(false, false);
8921 }
8922
8923 #[test]
8924 fn test_duplicate_temporary_channel_id_from_different_peers() {
8925         // Tests that we can accept two different `OpenChannel` requests with the same
8926         // `temporary_channel_id`, as long as they are from different peers.
8927         let chanmon_cfgs = create_chanmon_cfgs(3);
8928         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8929         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8930         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8931
8932         // Create an first channel channel
8933         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8934         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8935
8936         // Create an second channel
8937         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8938         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8939
8940         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8941         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8942         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8943
8944         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8945         // `temporary_channel_id` as they are from different peers.
8946         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8947         {
8948                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8949                 assert_eq!(events.len(), 1);
8950                 match &events[0] {
8951                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8952                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8953                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8954                         },
8955                         _ => panic!("Unexpected event"),
8956                 }
8957         }
8958
8959         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8960         {
8961                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8962                 assert_eq!(events.len(), 1);
8963                 match &events[0] {
8964                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8965                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8966                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8967                         },
8968                         _ => panic!("Unexpected event"),
8969                 }
8970         }
8971 }
8972
8973 #[test]
8974 fn test_duplicate_funding_err_in_funding() {
8975         // Test that if we have a live channel with one peer, then another peer comes along and tries
8976         // to create a second channel with the same txid we'll fail and not overwrite the
8977         // outpoint_to_peer map in `ChannelManager`.
8978         //
8979         // This was previously broken.
8980         let chanmon_cfgs = create_chanmon_cfgs(3);
8981         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8982         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8983         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8984
8985         let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
8986         let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
8987         assert_eq!(real_chan_funding_txo.to_channel_id(), real_channel_id);
8988
8989         nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
8990         let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8991         let node_c_temp_chan_id = open_chan_msg.temporary_channel_id;
8992         open_chan_msg.temporary_channel_id = real_channel_id;
8993         nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
8994         let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
8995         accept_chan_msg.temporary_channel_id = node_c_temp_chan_id;
8996         nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8997
8998         // Now that we have a second channel with the same funding txo, send a bogus funding message
8999         // and let nodes[1] remove the inbound channel.
9000         let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9001
9002         nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9003
9004         let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9005         funding_created_msg.temporary_channel_id = real_channel_id;
9006         // Make the signature invalid by changing the funding output
9007         funding_created_msg.funding_output_index += 10;
9008         nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9009         get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9010         let err = "Invalid funding_created signature from peer".to_owned();
9011         let reason = ClosureReason::ProcessingError { err };
9012         let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9013         check_closed_events(&nodes[1], &[expected_closing]);
9014
9015         assert_eq!(
9016                 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9017                 nodes[0].node.get_our_node_id()
9018         );
9019 }
9020
9021 #[test]
9022 fn test_duplicate_chan_id() {
9023         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9024         // already open we reject it and keep the old channel.
9025         //
9026         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9027         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9028         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9029         // updating logic for the existing channel.
9030         let chanmon_cfgs = create_chanmon_cfgs(2);
9031         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9032         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9033         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9034
9035         // Create an initial channel
9036         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9037         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9038         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9039         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()));
9040
9041         // Try to create a second channel with the same temporary_channel_id as the first and check
9042         // that it is rejected.
9043         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9044         {
9045                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9046                 assert_eq!(events.len(), 1);
9047                 match events[0] {
9048                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9049                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9050                                 // first (valid) and second (invalid) channels are closed, given they both have
9051                                 // the same non-temporary channel_id. However, currently we do not, so we just
9052                                 // move forward with it.
9053                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9054                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9055                         },
9056                         _ => panic!("Unexpected event"),
9057                 }
9058         }
9059
9060         // Move the first channel through the funding flow...
9061         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9062
9063         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9064         check_added_monitors!(nodes[0], 0);
9065
9066         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9067         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9068         {
9069                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9070                 assert_eq!(added_monitors.len(), 1);
9071                 assert_eq!(added_monitors[0].0, funding_output);
9072                 added_monitors.clear();
9073         }
9074         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9075
9076         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9077
9078         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9079         let channel_id = funding_outpoint.to_channel_id();
9080
9081         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9082         // temporary one).
9083
9084         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9085         // Technically this is allowed by the spec, but we don't support it and there's little reason
9086         // to. Still, it shouldn't cause any other issues.
9087         open_chan_msg.temporary_channel_id = channel_id;
9088         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9089         {
9090                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9091                 assert_eq!(events.len(), 1);
9092                 match events[0] {
9093                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9094                                 // Technically, at this point, nodes[1] would be justified in thinking both
9095                                 // channels are closed, but currently we do not, so we just move forward with it.
9096                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9097                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9098                         },
9099                         _ => panic!("Unexpected event"),
9100                 }
9101         }
9102
9103         // Now try to create a second channel which has a duplicate funding output.
9104         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9105         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9106         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9107         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()));
9108         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9109
9110         let funding_created = {
9111                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9112                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9113                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9114                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9115                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9116                 // channelmanager in a possibly nonsense state instead).
9117                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9118                         ChannelPhase::UnfundedOutboundV1(mut chan) => {
9119                                 let logger = test_utils::TestLogger::new();
9120                                 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9121                         },
9122                         _ => panic!("Unexpected ChannelPhase variant"),
9123                 }
9124         };
9125         check_added_monitors!(nodes[0], 0);
9126         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created.unwrap());
9127         // At this point we'll look up if the channel_id is present and immediately fail the channel
9128         // without trying to persist the `ChannelMonitor`.
9129         check_added_monitors!(nodes[1], 0);
9130
9131         check_closed_events(&nodes[1], &[
9132                 ExpectedCloseEvent::from_id_reason(channel_id, false, ClosureReason::ProcessingError {
9133                         err: "Already had channel with the new channel_id".to_owned()
9134                 })
9135         ]);
9136
9137         // ...still, nodes[1] will reject the duplicate channel.
9138         {
9139                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9140                 assert_eq!(events.len(), 1);
9141                 match events[0] {
9142                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9143                                 // Technically, at this point, nodes[1] would be justified in thinking both
9144                                 // channels are closed, but currently we do not, so we just move forward with it.
9145                                 assert_eq!(msg.channel_id, channel_id);
9146                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9147                         },
9148                         _ => panic!("Unexpected event"),
9149                 }
9150         }
9151
9152         // finally, finish creating the original channel and send a payment over it to make sure
9153         // everything is functional.
9154         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9155         {
9156                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9157                 assert_eq!(added_monitors.len(), 1);
9158                 assert_eq!(added_monitors[0].0, funding_output);
9159                 added_monitors.clear();
9160         }
9161         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9162
9163         let events_4 = nodes[0].node.get_and_clear_pending_events();
9164         assert_eq!(events_4.len(), 0);
9165         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9166         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9167
9168         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9169         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9170         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9171
9172         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9173 }
9174
9175 #[test]
9176 fn test_error_chans_closed() {
9177         // Test that we properly handle error messages, closing appropriate channels.
9178         //
9179         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9180         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9181         // we can test various edge cases around it to ensure we don't regress.
9182         let chanmon_cfgs = create_chanmon_cfgs(3);
9183         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9184         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9185         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9186
9187         // Create some initial channels
9188         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9189         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9190         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9191
9192         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9193         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9194         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9195
9196         // Closing a channel from a different peer has no effect
9197         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9198         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9199
9200         // Closing one channel doesn't impact others
9201         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9202         check_added_monitors!(nodes[0], 1);
9203         check_closed_broadcast!(nodes[0], false);
9204         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9205                 [nodes[1].node.get_our_node_id()], 100000);
9206         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9207         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9208         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);
9209         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);
9210
9211         // A null channel ID should close all channels
9212         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9213         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9214         check_added_monitors!(nodes[0], 2);
9215         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9216                 [nodes[1].node.get_our_node_id(); 2], 100000);
9217         let events = nodes[0].node.get_and_clear_pending_msg_events();
9218         assert_eq!(events.len(), 2);
9219         match events[0] {
9220                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9221                         assert_eq!(msg.contents.flags & 2, 2);
9222                 },
9223                 _ => panic!("Unexpected event"),
9224         }
9225         match events[1] {
9226                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9227                         assert_eq!(msg.contents.flags & 2, 2);
9228                 },
9229                 _ => panic!("Unexpected event"),
9230         }
9231         // Note that at this point users of a standard PeerHandler will end up calling
9232         // peer_disconnected.
9233         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9234         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9235
9236         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9237         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9238         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9239 }
9240
9241 #[test]
9242 fn test_invalid_funding_tx() {
9243         // Test that we properly handle invalid funding transactions sent to us from a peer.
9244         //
9245         // Previously, all other major lightning implementations had failed to properly sanitize
9246         // funding transactions from their counterparties, leading to a multi-implementation critical
9247         // security vulnerability (though we always sanitized properly, we've previously had
9248         // un-released crashes in the sanitization process).
9249         //
9250         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9251         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9252         // gave up on it. We test this here by generating such a transaction.
9253         let chanmon_cfgs = create_chanmon_cfgs(2);
9254         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9256         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9257
9258         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9259         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()));
9260         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()));
9261
9262         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9263
9264         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9265         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9266         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9267         // its length.
9268         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9269         let wit_program_script: ScriptBuf = wit_program.into();
9270         for output in tx.output.iter_mut() {
9271                 // Make the confirmed funding transaction have a bogus script_pubkey
9272                 output.script_pubkey = ScriptBuf::new_v0_p2wsh(&wit_program_script.wscript_hash());
9273         }
9274
9275         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9276         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()));
9277         check_added_monitors!(nodes[1], 1);
9278         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9279
9280         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()));
9281         check_added_monitors!(nodes[0], 1);
9282         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9283
9284         let events_1 = nodes[0].node.get_and_clear_pending_events();
9285         assert_eq!(events_1.len(), 0);
9286
9287         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9288         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9289         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9290
9291         let expected_err = "funding tx had wrong script/value or output index";
9292         confirm_transaction_at(&nodes[1], &tx, 1);
9293         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9294                 [nodes[0].node.get_our_node_id()], 100000);
9295         check_added_monitors!(nodes[1], 1);
9296         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9297         assert_eq!(events_2.len(), 1);
9298         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9299                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9300                 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9301                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9302                 } else { panic!(); }
9303         } else { panic!(); }
9304         assert_eq!(nodes[1].node.list_channels().len(), 0);
9305
9306         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9307         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9308         // as its not 32 bytes long.
9309         let mut spend_tx = Transaction {
9310                 version: 2i32, lock_time: LockTime::ZERO,
9311                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9312                         previous_output: BitcoinOutPoint {
9313                                 txid: tx.txid(),
9314                                 vout: idx as u32,
9315                         },
9316                         script_sig: ScriptBuf::new(),
9317                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9318                         witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9319                 }).collect(),
9320                 output: vec![TxOut {
9321                         value: 1000,
9322                         script_pubkey: ScriptBuf::new(),
9323                 }]
9324         };
9325         check_spends!(spend_tx, tx);
9326         mine_transaction(&nodes[1], &spend_tx);
9327 }
9328
9329 #[test]
9330 fn test_coinbase_funding_tx() {
9331         // Miners are able to fund channels directly from coinbase transactions, however
9332         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9333         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9334         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9335         //
9336         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9337         // immediately operational after opening.
9338         let chanmon_cfgs = create_chanmon_cfgs(2);
9339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9341         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9342
9343         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9344         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9345
9346         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9347         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9348
9349         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9350
9351         // Create the coinbase funding transaction.
9352         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9353
9354         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9355         check_added_monitors!(nodes[0], 0);
9356         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9357
9358         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9359         check_added_monitors!(nodes[1], 1);
9360         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9361
9362         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9363
9364         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9365         check_added_monitors!(nodes[0], 1);
9366
9367         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9368         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9369
9370         // Starting at height 0, we "confirm" the coinbase at height 1.
9371         confirm_transaction_at(&nodes[0], &tx, 1);
9372         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9373         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9374         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9375         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9376         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9377         connect_blocks(&nodes[0], 1);
9378         // There should now be a `channel_ready` which can be handled.
9379         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()));
9380
9381         confirm_transaction_at(&nodes[1], &tx, 1);
9382         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9383         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9384         connect_blocks(&nodes[1], 1);
9385         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9386         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9387 }
9388
9389 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9390         // In the first version of the chain::Confirm interface, after a refactor was made to not
9391         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9392         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9393         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9394         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9395         // spending transaction until height N+1 (or greater). This was due to the way
9396         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9397         // spending transaction at the height the input transaction was confirmed at, not whether we
9398         // should broadcast a spending transaction at the current height.
9399         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9400         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9401         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9402         // until we learned about an additional block.
9403         //
9404         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9405         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9406         let chanmon_cfgs = create_chanmon_cfgs(3);
9407         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9408         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9409         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9410         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9411
9412         create_announced_chan_between_nodes(&nodes, 0, 1);
9413         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9414         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9415         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9416         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9417
9418         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9419         check_closed_broadcast!(nodes[1], true);
9420         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9421         check_added_monitors!(nodes[1], 1);
9422         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9423         assert_eq!(node_txn.len(), 1);
9424
9425         let conf_height = nodes[1].best_block_info().1;
9426         if !test_height_before_timelock {
9427                 connect_blocks(&nodes[1], 24 * 6);
9428         }
9429         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9430                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9431         if test_height_before_timelock {
9432                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9433                 // generate any events or broadcast any transactions
9434                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9435                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9436         } else {
9437                 // We should broadcast an HTLC transaction spending our funding transaction first
9438                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9439                 assert_eq!(spending_txn.len(), 2);
9440                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9441                 check_spends!(spending_txn[1], node_txn[0]);
9442                 // We should also generate a SpendableOutputs event with the to_self output (as its
9443                 // timelock is up).
9444                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9445                 assert_eq!(descriptor_spend_txn.len(), 1);
9446
9447                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9448                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9449                 // additional block built on top of the current chain.
9450                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9451                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9452                 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 }]);
9453                 check_added_monitors!(nodes[1], 1);
9454
9455                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9456                 assert!(updates.update_add_htlcs.is_empty());
9457                 assert!(updates.update_fulfill_htlcs.is_empty());
9458                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9459                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9460                 assert!(updates.update_fee.is_none());
9461                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9462                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9463                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9464         }
9465 }
9466
9467 #[test]
9468 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9469         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9470         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9471 }
9472
9473 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9474         let chanmon_cfgs = create_chanmon_cfgs(2);
9475         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9476         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9477         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9478
9479         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9480
9481         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9482                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9483         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9484
9485         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9486
9487         {
9488                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9489                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9490                 check_added_monitors!(nodes[0], 1);
9491                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9492                 assert_eq!(events.len(), 1);
9493                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9494                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9495                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9496         }
9497         expect_pending_htlcs_forwardable!(nodes[1]);
9498         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9499
9500         {
9501                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9502                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9503                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9504                 check_added_monitors!(nodes[0], 1);
9505                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9506                 assert_eq!(events.len(), 1);
9507                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9508                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9509                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9510                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9511                 // assume the second is a privacy attack (no longer particularly relevant
9512                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9513                 // the first HTLC delivered above.
9514         }
9515
9516         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9517         nodes[1].node.process_pending_htlc_forwards();
9518
9519         if test_for_second_fail_panic {
9520                 // Now we go fail back the first HTLC from the user end.
9521                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9522
9523                 let expected_destinations = vec![
9524                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9525                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9526                 ];
9527                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9528                 nodes[1].node.process_pending_htlc_forwards();
9529
9530                 check_added_monitors!(nodes[1], 1);
9531                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9532                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9533
9534                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9535                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9536                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9537
9538                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9539                 assert_eq!(failure_events.len(), 4);
9540                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9541                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9542                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9543                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9544         } else {
9545                 // Let the second HTLC fail and claim the first
9546                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9547                 nodes[1].node.process_pending_htlc_forwards();
9548
9549                 check_added_monitors!(nodes[1], 1);
9550                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9551                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9552                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9553
9554                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9555
9556                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9557         }
9558 }
9559
9560 #[test]
9561 fn test_dup_htlc_second_fail_panic() {
9562         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9563         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9564         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9565         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9566         do_test_dup_htlc_second_rejected(true);
9567 }
9568
9569 #[test]
9570 fn test_dup_htlc_second_rejected() {
9571         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9572         // simply reject the second HTLC but are still able to claim the first HTLC.
9573         do_test_dup_htlc_second_rejected(false);
9574 }
9575
9576 #[test]
9577 fn test_inconsistent_mpp_params() {
9578         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9579         // such HTLC and allow the second to stay.
9580         let chanmon_cfgs = create_chanmon_cfgs(4);
9581         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9582         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9583         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9584
9585         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9586         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9587         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9588         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9589
9590         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9591                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9592         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9593         assert_eq!(route.paths.len(), 2);
9594         route.paths.sort_by(|path_a, _| {
9595                 // Sort the path so that the path through nodes[1] comes first
9596                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9597                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9598         });
9599
9600         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9601
9602         let cur_height = nodes[0].best_block_info().1;
9603         let payment_id = PaymentId([42; 32]);
9604
9605         let session_privs = {
9606                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9607                 // ultimately have, just not right away.
9608                 let mut dup_route = route.clone();
9609                 dup_route.paths.push(route.paths[1].clone());
9610                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9611                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9612         };
9613         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9614                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9615                 &None, session_privs[0]).unwrap();
9616         check_added_monitors!(nodes[0], 1);
9617
9618         {
9619                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9620                 assert_eq!(events.len(), 1);
9621                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9622         }
9623         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9624
9625         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9626                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9627         check_added_monitors!(nodes[0], 1);
9628
9629         {
9630                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9631                 assert_eq!(events.len(), 1);
9632                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9633
9634                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9635                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9636
9637                 expect_pending_htlcs_forwardable!(nodes[2]);
9638                 check_added_monitors!(nodes[2], 1);
9639
9640                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9641                 assert_eq!(events.len(), 1);
9642                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9643
9644                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9645                 check_added_monitors!(nodes[3], 0);
9646                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9647
9648                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9649                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9650                 // post-payment_secrets) and fail back the new HTLC.
9651         }
9652         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9653         nodes[3].node.process_pending_htlc_forwards();
9654         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9655         nodes[3].node.process_pending_htlc_forwards();
9656
9657         check_added_monitors!(nodes[3], 1);
9658
9659         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9660         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9661         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9662
9663         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 }]);
9664         check_added_monitors!(nodes[2], 1);
9665
9666         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9667         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9668         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9669
9670         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9671
9672         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9673                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9674                 &None, session_privs[2]).unwrap();
9675         check_added_monitors!(nodes[0], 1);
9676
9677         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9678         assert_eq!(events.len(), 1);
9679         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9680
9681         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9682         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9683 }
9684
9685 #[test]
9686 fn test_double_partial_claim() {
9687         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9688         // time out, the sender resends only some of the MPP parts, then the user processes the
9689         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9690         // amount.
9691         let chanmon_cfgs = create_chanmon_cfgs(4);
9692         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9693         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9694         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9695
9696         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9697         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9698         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9699         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9700
9701         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9702         assert_eq!(route.paths.len(), 2);
9703         route.paths.sort_by(|path_a, _| {
9704                 // Sort the path so that the path through nodes[1] comes first
9705                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9706                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9707         });
9708
9709         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9710         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9711         // amount of time to respond to.
9712
9713         // Connect some blocks to time out the payment
9714         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9715         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9716
9717         let failed_destinations = vec![
9718                 HTLCDestination::FailedPayment { payment_hash },
9719                 HTLCDestination::FailedPayment { payment_hash },
9720         ];
9721         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9722
9723         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9724
9725         // nodes[1] now retries one of the two paths...
9726         nodes[0].node.send_payment_with_route(&route, payment_hash,
9727                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9728         check_added_monitors!(nodes[0], 2);
9729
9730         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9731         assert_eq!(events.len(), 2);
9732         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9733         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9734
9735         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9736         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9737         nodes[3].node.claim_funds(payment_preimage);
9738         check_added_monitors!(nodes[3], 0);
9739         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9740 }
9741
9742 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9743 #[derive(Clone, Copy, PartialEq)]
9744 enum ExposureEvent {
9745         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9746         AtHTLCForward,
9747         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9748         AtHTLCReception,
9749         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9750         AtUpdateFeeOutbound,
9751 }
9752
9753 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9754         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9755         // policy.
9756         //
9757         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9758         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9759         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9760         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9761         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9762         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9763         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9764         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9765
9766         let chanmon_cfgs = create_chanmon_cfgs(2);
9767         let mut config = test_default_channel_config();
9768         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9769                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9770                 // to get roughly the same initial value as the default setting when this test was
9771                 // originally written.
9772                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9773         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9774         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9775         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9776         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9777
9778         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9779         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9780         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9781         open_channel.max_accepted_htlcs = 60;
9782         if on_holder_tx {
9783                 open_channel.dust_limit_satoshis = 546;
9784         }
9785         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9786         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9787         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9788
9789         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9790
9791         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9792
9793         if on_holder_tx {
9794                 let mut node_0_per_peer_lock;
9795                 let mut node_0_peer_state_lock;
9796                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9797                         ChannelPhase::UnfundedOutboundV1(chan) => {
9798                                 chan.context.holder_dust_limit_satoshis = 546;
9799                         },
9800                         _ => panic!("Unexpected ChannelPhase variant"),
9801                 }
9802         }
9803
9804         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9805         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()));
9806         check_added_monitors!(nodes[1], 1);
9807         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9808
9809         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()));
9810         check_added_monitors!(nodes[0], 1);
9811         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9812
9813         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9814         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9815         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9816
9817         // Fetch a route in advance as we will be unable to once we're unable to send.
9818         let (mut route, payment_hash, _, payment_secret) =
9819                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9820
9821         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9822                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9823                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9824                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9825                 (chan.context().get_dust_buffer_feerate(None) as u64,
9826                 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9827         };
9828         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;
9829         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9830
9831         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;
9832         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9833
9834         let dust_htlc_on_counterparty_tx: u64 = 4;
9835         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9836
9837         if on_holder_tx {
9838                 if dust_outbound_balance {
9839                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9840                         // Outbound dust balance: 4372 sats
9841                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9842                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9843                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9844                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9845                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9846                         }
9847                 } else {
9848                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9849                         // Inbound dust balance: 4372 sats
9850                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9851                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9852                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9853                         }
9854                 }
9855         } else {
9856                 if dust_outbound_balance {
9857                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9858                         // Outbound dust balance: 5000 sats
9859                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9860                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9861                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9862                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9863                         }
9864                 } else {
9865                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9866                         // Inbound dust balance: 5000 sats
9867                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9868                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9869                         }
9870                 }
9871         }
9872
9873         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9874                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9875                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9876                 // With default dust exposure: 5000 sats
9877                 if on_holder_tx {
9878                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9879                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9880                                 ), true, APIError::ChannelUnavailable { .. }, {});
9881                 } else {
9882                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9883                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9884                                 ), true, APIError::ChannelUnavailable { .. }, {});
9885                 }
9886         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9887                 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 });
9888                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9889                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9890                 check_added_monitors!(nodes[1], 1);
9891                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9892                 assert_eq!(events.len(), 1);
9893                 let payment_event = SendEvent::from_event(events.remove(0));
9894                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9895                 // With default dust exposure: 5000 sats
9896                 if on_holder_tx {
9897                         // Outbound dust balance: 6399 sats
9898                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9899                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9900                         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
9901                 } else {
9902                         // Outbound dust balance: 5200 sats
9903                         nodes[0].logger.assert_log("lightning::ln::channel",
9904                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9905                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9906                                         max_dust_htlc_exposure_msat), 1);
9907                 }
9908         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9909                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9910                 // For the multiplier dust exposure limit, since it scales with feerate,
9911                 // we need to add a lot of HTLCs that will become dust at the new feerate
9912                 // to cross the threshold.
9913                 for _ in 0..20 {
9914                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9915                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9916                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9917                 }
9918                 {
9919                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9920                         *feerate_lock = *feerate_lock * 10;
9921                 }
9922                 nodes[0].node.timer_tick_occurred();
9923                 check_added_monitors!(nodes[0], 1);
9924                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9925         }
9926
9927         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9928         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9929         added_monitors.clear();
9930 }
9931
9932 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9933         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9934         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9935         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9936         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9937         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9938         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9939         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9940         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9941         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9942         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9943         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9944         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9945 }
9946
9947 #[test]
9948 fn test_max_dust_htlc_exposure() {
9949         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9950         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9951 }
9952
9953 #[test]
9954 fn test_non_final_funding_tx() {
9955         let chanmon_cfgs = create_chanmon_cfgs(2);
9956         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9957         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9958         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9959
9960         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9961         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9962         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9963         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9964         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9965
9966         let best_height = nodes[0].node.best_block.read().unwrap().height();
9967
9968         let chan_id = *nodes[0].network_chan_count.borrow();
9969         let events = nodes[0].node.get_and_clear_pending_events();
9970         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
9971         assert_eq!(events.len(), 1);
9972         let mut tx = match events[0] {
9973                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9974                         // Timelock the transaction _beyond_ the best client height + 1.
9975                         Transaction { version: chan_id as i32, lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
9976                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9977                         }]}
9978                 },
9979                 _ => panic!("Unexpected event"),
9980         };
9981         // Transaction should fail as it's evaluated as non-final for propagation.
9982         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9983                 Err(APIError::APIMisuseError { err }) => {
9984                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9985                 },
9986                 _ => panic!()
9987         }
9988         let events = nodes[0].node.get_and_clear_pending_events();
9989         assert_eq!(events.len(), 1);
9990         match events[0] {
9991                 Event::ChannelClosed { channel_id, .. } => {
9992                         assert_eq!(channel_id, temp_channel_id);
9993                 },
9994                 _ => panic!("Unexpected event"),
9995         }
9996 }
9997
9998 #[test]
9999 fn test_non_final_funding_tx_within_headroom() {
10000         let chanmon_cfgs = create_chanmon_cfgs(2);
10001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10003         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10004
10005         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10006         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10007         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10008         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10009         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10010
10011         let best_height = nodes[0].node.best_block.read().unwrap().height();
10012
10013         let chan_id = *nodes[0].network_chan_count.borrow();
10014         let events = nodes[0].node.get_and_clear_pending_events();
10015         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10016         assert_eq!(events.len(), 1);
10017         let mut tx = match events[0] {
10018                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10019                         // Timelock the transaction within a +1 headroom from the best block.
10020                         Transaction { version: chan_id as i32, lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10021                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10022                         }]}
10023                 },
10024                 _ => panic!("Unexpected event"),
10025         };
10026
10027         // Transaction should be accepted if it's in a +1 headroom from best block.
10028         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10029         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10030 }
10031
10032 #[test]
10033 fn accept_busted_but_better_fee() {
10034         // If a peer sends us a fee update that is too low, but higher than our previous channel
10035         // feerate, we should accept it. In the future we may want to consider closing the channel
10036         // later, but for now we only accept the update.
10037         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10038         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10039         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10040         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10041
10042         create_chan_between_nodes(&nodes[0], &nodes[1]);
10043
10044         // Set nodes[1] to expect 5,000 sat/kW.
10045         {
10046                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10047                 *feerate_lock = 5000;
10048         }
10049
10050         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10051         {
10052                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10053                 *feerate_lock = 1000;
10054         }
10055         nodes[0].node.timer_tick_occurred();
10056         check_added_monitors!(nodes[0], 1);
10057
10058         let events = nodes[0].node.get_and_clear_pending_msg_events();
10059         assert_eq!(events.len(), 1);
10060         match events[0] {
10061                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10062                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10063                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10064                 },
10065                 _ => panic!("Unexpected event"),
10066         };
10067
10068         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10069         // it.
10070         {
10071                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10072                 *feerate_lock = 2000;
10073         }
10074         nodes[0].node.timer_tick_occurred();
10075         check_added_monitors!(nodes[0], 1);
10076
10077         let events = nodes[0].node.get_and_clear_pending_msg_events();
10078         assert_eq!(events.len(), 1);
10079         match events[0] {
10080                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10081                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10082                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10083                 },
10084                 _ => panic!("Unexpected event"),
10085         };
10086
10087         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10088         // channel.
10089         {
10090                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10091                 *feerate_lock = 1000;
10092         }
10093         nodes[0].node.timer_tick_occurred();
10094         check_added_monitors!(nodes[0], 1);
10095
10096         let events = nodes[0].node.get_and_clear_pending_msg_events();
10097         assert_eq!(events.len(), 1);
10098         match events[0] {
10099                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10100                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10101                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10102                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10103                                 [nodes[0].node.get_our_node_id()], 100000);
10104                         check_closed_broadcast!(nodes[1], true);
10105                         check_added_monitors!(nodes[1], 1);
10106                 },
10107                 _ => panic!("Unexpected event"),
10108         };
10109 }
10110
10111 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10112         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10113         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10114         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10115         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10116         let min_final_cltv_expiry_delta = 120;
10117         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10118                 min_final_cltv_expiry_delta - 2 };
10119         let recv_value = 100_000;
10120
10121         create_chan_between_nodes(&nodes[0], &nodes[1]);
10122
10123         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10124         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10125                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10126                         Some(recv_value), Some(min_final_cltv_expiry_delta));
10127                 (payment_hash, payment_preimage, payment_secret)
10128         } else {
10129                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10130                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10131         };
10132         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10133         nodes[0].node.send_payment_with_route(&route, payment_hash,
10134                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10135         check_added_monitors!(nodes[0], 1);
10136         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10137         assert_eq!(events.len(), 1);
10138         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10139         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10140         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10141         expect_pending_htlcs_forwardable!(nodes[1]);
10142
10143         if valid_delta {
10144                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10145                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10146
10147                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10148         } else {
10149                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10150
10151                 check_added_monitors!(nodes[1], 1);
10152
10153                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10154                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10155                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10156
10157                 expect_payment_failed!(nodes[0], payment_hash, true);
10158         }
10159 }
10160
10161 #[test]
10162 fn test_payment_with_custom_min_cltv_expiry_delta() {
10163         do_payment_with_custom_min_final_cltv_expiry(false, false);
10164         do_payment_with_custom_min_final_cltv_expiry(false, true);
10165         do_payment_with_custom_min_final_cltv_expiry(true, false);
10166         do_payment_with_custom_min_final_cltv_expiry(true, true);
10167 }
10168
10169 #[test]
10170 fn test_disconnects_peer_awaiting_response_ticks() {
10171         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10172         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10173         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10174         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10175         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10176         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10177
10178         // Asserts a disconnect event is queued to the user.
10179         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10180                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10181                         if let MessageSendEvent::HandleError { action, .. } = event {
10182                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10183                                         Some(())
10184                                 } else {
10185                                         None
10186                                 }
10187                         } else {
10188                                 None
10189                         }
10190                 );
10191                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10192         };
10193
10194         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10195         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10196         let check_disconnect = |node: &Node| {
10197                 // No disconnect without any timer ticks.
10198                 check_disconnect_event(node, false);
10199
10200                 // No disconnect with 1 timer tick less than required.
10201                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10202                         node.node.timer_tick_occurred();
10203                         check_disconnect_event(node, false);
10204                 }
10205
10206                 // Disconnect after reaching the required ticks.
10207                 node.node.timer_tick_occurred();
10208                 check_disconnect_event(node, true);
10209
10210                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10211                 node.node.timer_tick_occurred();
10212                 check_disconnect_event(node, true);
10213         };
10214
10215         create_chan_between_nodes(&nodes[0], &nodes[1]);
10216
10217         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10218         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10219         nodes[0].node.timer_tick_occurred();
10220         check_added_monitors!(&nodes[0], 1);
10221         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10222         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10223         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10224         check_added_monitors!(&nodes[1], 1);
10225
10226         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10227         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10228         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10229         check_added_monitors!(&nodes[0], 1);
10230         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10231         check_added_monitors(&nodes[0], 1);
10232
10233         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10234         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10235         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10236         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10237         check_disconnect(&nodes[1]);
10238
10239         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10240         //
10241         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10242         // final `RevokeAndACK` to Bob to complete it.
10243         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10244         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10245         let bob_init = msgs::Init {
10246                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10247         };
10248         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10249         let alice_init = msgs::Init {
10250                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10251         };
10252         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10253
10254         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10255         // received Bob's yet, so she should disconnect him after reaching
10256         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10257         let alice_channel_reestablish = get_event_msg!(
10258                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10259         );
10260         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10261         check_disconnect(&nodes[0]);
10262
10263         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10264         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10265                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10266                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10267                         Some(msg.clone())
10268                 } else {
10269                         None
10270                 }
10271         ).unwrap();
10272         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10273
10274         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10275         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10276                 nodes[0].node.timer_tick_occurred();
10277                 check_disconnect_event(&nodes[0], false);
10278         }
10279
10280         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10281         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10282         check_disconnect(&nodes[1]);
10283
10284         // Finally, have Bob process the last message.
10285         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10286         check_added_monitors(&nodes[1], 1);
10287
10288         // At this point, neither node should attempt to disconnect each other, since they aren't
10289         // waiting on any messages.
10290         for node in &nodes {
10291                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10292                         node.node.timer_tick_occurred();
10293                         check_disconnect_event(node, false);
10294                 }
10295         }
10296 }
10297
10298 #[test]
10299 fn test_remove_expired_outbound_unfunded_channels() {
10300         let chanmon_cfgs = create_chanmon_cfgs(2);
10301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10303         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10304
10305         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10306         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10307         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10308         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10309         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10310
10311         let events = nodes[0].node.get_and_clear_pending_events();
10312         assert_eq!(events.len(), 1);
10313         match events[0] {
10314                 Event::FundingGenerationReady { .. } => (),
10315                 _ => panic!("Unexpected event"),
10316         };
10317
10318         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10319         let check_outbound_channel_existence = |should_exist: bool| {
10320                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10321                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10322                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10323         };
10324
10325         // Channel should exist without any timer ticks.
10326         check_outbound_channel_existence(true);
10327
10328         // Channel should exist with 1 timer tick less than required.
10329         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10330                 nodes[0].node.timer_tick_occurred();
10331                 check_outbound_channel_existence(true)
10332         }
10333
10334         // Remove channel after reaching the required ticks.
10335         nodes[0].node.timer_tick_occurred();
10336         check_outbound_channel_existence(false);
10337
10338         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10339         assert_eq!(msg_events.len(), 1);
10340         match msg_events[0] {
10341                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10342                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10343                 },
10344                 _ => panic!("Unexpected event"),
10345         }
10346         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10347 }
10348
10349 #[test]
10350 fn test_remove_expired_inbound_unfunded_channels() {
10351         let chanmon_cfgs = create_chanmon_cfgs(2);
10352         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10353         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10354         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10355
10356         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10357         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10358         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10359         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10360         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10361
10362         let events = nodes[0].node.get_and_clear_pending_events();
10363         assert_eq!(events.len(), 1);
10364         match events[0] {
10365                 Event::FundingGenerationReady { .. } => (),
10366                 _ => panic!("Unexpected event"),
10367         };
10368
10369         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10370         let check_inbound_channel_existence = |should_exist: bool| {
10371                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10372                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10373                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10374         };
10375
10376         // Channel should exist without any timer ticks.
10377         check_inbound_channel_existence(true);
10378
10379         // Channel should exist with 1 timer tick less than required.
10380         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10381                 nodes[1].node.timer_tick_occurred();
10382                 check_inbound_channel_existence(true)
10383         }
10384
10385         // Remove channel after reaching the required ticks.
10386         nodes[1].node.timer_tick_occurred();
10387         check_inbound_channel_existence(false);
10388
10389         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10390         assert_eq!(msg_events.len(), 1);
10391         match msg_events[0] {
10392                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10393                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10394                 },
10395                 _ => panic!("Unexpected event"),
10396         }
10397         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10398 }
10399
10400 fn do_test_multi_post_event_actions(do_reload: bool) {
10401         // Tests handling multiple post-Event actions at once.
10402         // There is specific code in ChannelManager to handle channels where multiple post-Event
10403         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10404         //
10405         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10406         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10407         // - one from an RAA and one from an inbound commitment_signed.
10408         let chanmon_cfgs = create_chanmon_cfgs(3);
10409         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10410         let (persister, chain_monitor);
10411         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10412         let nodes_0_deserialized;
10413         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10414
10415         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10416         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10417
10418         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10419         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10420
10421         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10422         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10423
10424         nodes[1].node.claim_funds(our_payment_preimage);
10425         check_added_monitors!(nodes[1], 1);
10426         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10427
10428         nodes[2].node.claim_funds(payment_preimage_2);
10429         check_added_monitors!(nodes[2], 1);
10430         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10431
10432         for dest in &[1, 2] {
10433                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10434                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10435                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10436                 check_added_monitors(&nodes[0], 0);
10437         }
10438
10439         let (route, payment_hash_3, _, payment_secret_3) =
10440                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10441         let payment_id = PaymentId(payment_hash_3.0);
10442         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10443                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10444         check_added_monitors(&nodes[1], 1);
10445
10446         let send_event = SendEvent::from_node(&nodes[1]);
10447         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10448         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10449         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10450
10451         if do_reload {
10452                 let nodes_0_serialized = nodes[0].node.encode();
10453                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10454                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10455                 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);
10456
10457                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10458                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10459
10460                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10461                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10462         }
10463
10464         let events = nodes[0].node.get_and_clear_pending_events();
10465         assert_eq!(events.len(), 4);
10466         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10467                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10468         } else { panic!(); }
10469         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10470                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10471         } else { panic!(); }
10472         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10473         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10474
10475         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10476         // completion, we'll respond to nodes[1] with an RAA + CS.
10477         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10478         check_added_monitors(&nodes[0], 3);
10479 }
10480
10481 #[test]
10482 fn test_multi_post_event_actions() {
10483         do_test_multi_post_event_actions(true);
10484         do_test_multi_post_event_actions(false);
10485 }
10486
10487 #[test]
10488 fn test_batch_channel_open() {
10489         let chanmon_cfgs = create_chanmon_cfgs(3);
10490         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10491         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10492         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10493
10494         // Initiate channel opening and create the batch channel funding transaction.
10495         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10496                 (&nodes[1], 100_000, 0, 42, None),
10497                 (&nodes[2], 200_000, 0, 43, None),
10498         ]);
10499
10500         // Go through the funding_created and funding_signed flow with node 1.
10501         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10502         check_added_monitors(&nodes[1], 1);
10503         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10504
10505         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10506         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10507         check_added_monitors(&nodes[0], 1);
10508
10509         // The transaction should not have been broadcast before all channels are ready.
10510         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10511
10512         // Go through the funding_created and funding_signed flow with node 2.
10513         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10514         check_added_monitors(&nodes[2], 1);
10515         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10516
10517         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10518         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10519         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10520         check_added_monitors(&nodes[0], 1);
10521
10522         // The transaction should not have been broadcast before persisting all monitors has been
10523         // completed.
10524         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10525         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10526
10527         // Complete the persistence of the monitor.
10528         nodes[0].chain_monitor.complete_sole_pending_chan_update(
10529                 &OutPoint { txid: tx.txid(), index: 1 }.to_channel_id()
10530         );
10531         let events = nodes[0].node.get_and_clear_pending_events();
10532
10533         // The transaction should only have been broadcast now.
10534         let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10535         assert_eq!(broadcasted_txs.len(), 1);
10536         assert_eq!(broadcasted_txs[0], tx);
10537
10538         assert_eq!(events.len(), 2);
10539         assert!(events.iter().any(|e| matches!(
10540                 *e,
10541                 crate::events::Event::ChannelPending {
10542                         ref counterparty_node_id,
10543                         ..
10544                 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10545         )));
10546         assert!(events.iter().any(|e| matches!(
10547                 *e,
10548                 crate::events::Event::ChannelPending {
10549                         ref counterparty_node_id,
10550                         ..
10551                 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10552         )));
10553 }
10554
10555 #[test]
10556 fn test_disconnect_in_funding_batch() {
10557         let chanmon_cfgs = create_chanmon_cfgs(3);
10558         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10559         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10560         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10561
10562         // Initiate channel opening and create the batch channel funding transaction.
10563         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10564                 (&nodes[1], 100_000, 0, 42, None),
10565                 (&nodes[2], 200_000, 0, 43, None),
10566         ]);
10567
10568         // Go through the funding_created and funding_signed flow with node 1.
10569         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10570         check_added_monitors(&nodes[1], 1);
10571         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10572
10573         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10574         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10575         check_added_monitors(&nodes[0], 1);
10576
10577         // The transaction should not have been broadcast before all channels are ready.
10578         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10579
10580         // The remaining peer in the batch disconnects.
10581         nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
10582
10583         // The channels in the batch will close immediately.
10584         let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10585         let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10586         check_closed_events(&nodes[0], &[
10587                 ExpectedCloseEvent {
10588                         channel_id: Some(channel_id_1),
10589                         discard_funding: true,
10590                         ..Default::default()
10591                 },
10592                 ExpectedCloseEvent {
10593                         channel_id: Some(channel_id_2),
10594                         discard_funding: true,
10595                         ..Default::default()
10596                 },
10597         ]);
10598
10599         // The monitor should become closed.
10600         check_added_monitors(&nodes[0], 1);
10601         {
10602                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10603                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10604                 assert_eq!(monitor_updates_1.len(), 1);
10605                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10606         }
10607
10608         // The funding transaction should not have been broadcast, and therefore, we don't need
10609         // to broadcast a force-close transaction for the closed monitor.
10610         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10611
10612         // Ensure the channels don't exist anymore.
10613         assert!(nodes[0].node.list_channels().is_empty());
10614 }
10615
10616 #[test]
10617 fn test_batch_funding_close_after_funding_signed() {
10618         let chanmon_cfgs = create_chanmon_cfgs(3);
10619         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10620         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10621         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10622
10623         // Initiate channel opening and create the batch channel funding transaction.
10624         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10625                 (&nodes[1], 100_000, 0, 42, None),
10626                 (&nodes[2], 200_000, 0, 43, None),
10627         ]);
10628
10629         // Go through the funding_created and funding_signed flow with node 1.
10630         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10631         check_added_monitors(&nodes[1], 1);
10632         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10633
10634         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10635         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10636         check_added_monitors(&nodes[0], 1);
10637
10638         // Go through the funding_created and funding_signed flow with node 2.
10639         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10640         check_added_monitors(&nodes[2], 1);
10641         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10642
10643         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10644         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10645         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10646         check_added_monitors(&nodes[0], 1);
10647
10648         // The transaction should not have been broadcast before all channels are ready.
10649         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10650
10651         // Force-close the channel for which we've completed the initial monitor.
10652         let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10653         let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10654         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10655         check_added_monitors(&nodes[0], 2);
10656         {
10657                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10658                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10659                 assert_eq!(monitor_updates_1.len(), 1);
10660                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10661                 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10662                 assert_eq!(monitor_updates_2.len(), 1);
10663                 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10664         }
10665         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10666         match msg_events[0] {
10667                 MessageSendEvent::HandleError { .. } => (),
10668                 _ => panic!("Unexpected message."),
10669         }
10670
10671         // We broadcast the commitment transaction as part of the force-close.
10672         {
10673                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10674                 assert_eq!(broadcasted_txs.len(), 1);
10675                 assert!(broadcasted_txs[0].txid() != tx.txid());
10676                 assert_eq!(broadcasted_txs[0].input.len(), 1);
10677                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10678         }
10679
10680         // All channels in the batch should close immediately.
10681         check_closed_events(&nodes[0], &[
10682                 ExpectedCloseEvent {
10683                         channel_id: Some(channel_id_1),
10684                         discard_funding: true,
10685                         ..Default::default()
10686                 },
10687                 ExpectedCloseEvent {
10688                         channel_id: Some(channel_id_2),
10689                         discard_funding: true,
10690                         ..Default::default()
10691                 },
10692         ]);
10693
10694         // Ensure the channels don't exist anymore.
10695         assert!(nodes[0].node.list_channels().is_empty());
10696 }
10697
10698 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10699         // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10700         // funding and commitment transaction confirm in the same block.
10701         let chanmon_cfgs = create_chanmon_cfgs(2);
10702         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10703         let mut min_depth_1_block_cfg = test_default_channel_config();
10704         min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10706         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10707
10708         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10709         let chan_id = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 }.to_channel_id();
10710
10711         assert_eq!(nodes[0].node.list_channels().len(), 1);
10712         assert_eq!(nodes[1].node.list_channels().len(), 1);
10713
10714         let (closing_node, other_node) = if confirm_remote_commitment {
10715                 (&nodes[1], &nodes[0])
10716         } else {
10717                 (&nodes[0], &nodes[1])
10718         };
10719
10720         closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10721         let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10722         assert_eq!(msg_events.len(), 1);
10723         match msg_events.pop().unwrap() {
10724                 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10725                 _ => panic!("Unexpected event"),
10726         }
10727         check_added_monitors(closing_node, 1);
10728         check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10729
10730         let commitment_tx = {
10731                 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10732                 assert_eq!(txn.len(), 1);
10733                 let commitment_tx = txn.pop().unwrap();
10734                 check_spends!(commitment_tx, funding_tx);
10735                 commitment_tx
10736         };
10737
10738         mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10739         mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10740
10741         check_closed_broadcast(other_node, 1, true);
10742         check_added_monitors(other_node, 1);
10743         check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10744
10745         assert!(nodes[0].node.list_channels().is_empty());
10746         assert!(nodes[1].node.list_channels().is_empty());
10747 }
10748
10749 #[test]
10750 fn test_funding_and_commitment_tx_confirm_same_block() {
10751         do_test_funding_and_commitment_tx_confirm_same_block(false);
10752         do_test_funding_and_commitment_tx_confirm_same_block(true);
10753 }