Refactor `ChannelManager` with `ChannelPhase`
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
47
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
50
51 use regex;
52
53 use crate::io;
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex, RwLock};
60
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
63
64 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
65
66 #[test]
67 fn test_insane_channel_opens() {
68         // Stand up a network of 2 nodes
69         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
70         let mut cfg = UserConfig::default();
71         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
72         let chanmon_cfgs = create_chanmon_cfgs(2);
73         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
74         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
75         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
76
77         // Instantiate channel parameters where we push the maximum msats given our
78         // funding satoshis
79         let channel_value_sat = 31337; // same as funding satoshis
80         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
81         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
82
83         // Have node0 initiate a channel to node1 with aforementioned parameters
84         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
85
86         // Extract the channel open message from node0 to node1
87         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
88
89         // Test helper that asserts we get the correct error string given a mutator
90         // that supposedly makes the channel open message insane
91         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
92                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
93                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
94                 assert_eq!(msg_events.len(), 1);
95                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
96                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
97                         match action {
98                                 &ErrorAction::SendErrorMessage { .. } => {
99                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
100                                 },
101                                 _ => panic!("unexpected event!"),
102                         }
103                 } else { assert!(false); }
104         };
105
106         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
107
108         // Test all mutations that would make the channel open message insane
109         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
110         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
111
112         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
113
114         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
115
116         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
117
118         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
119
120         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
121
122         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
123
124         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 }
126
127 #[test]
128 fn test_funding_exceeds_no_wumbo_limit() {
129         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
130         // them.
131         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
132         let chanmon_cfgs = create_chanmon_cfgs(2);
133         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
134         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
135         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
136         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
137
138         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
139                 Err(APIError::APIMisuseError { err }) => {
140                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
141                 },
142                 _ => panic!()
143         }
144 }
145
146 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
147         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
148         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
149         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
150         // in normal testing, we test it explicitly here.
151         let chanmon_cfgs = create_chanmon_cfgs(2);
152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
155         let default_config = UserConfig::default();
156
157         // Have node0 initiate a channel to node1 with aforementioned parameters
158         let mut push_amt = 100_000_000;
159         let feerate_per_kw = 253;
160         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
161         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
162         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
163
164         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
165         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
166         if !send_from_initiator {
167                 open_channel_message.channel_reserve_satoshis = 0;
168                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169         }
170         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
171
172         // Extract the channel accept message from node1 to node0
173         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
174         if send_from_initiator {
175                 accept_channel_message.channel_reserve_satoshis = 0;
176                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
177         }
178         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
179         {
180                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
181                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
182                 let mut sender_node_per_peer_lock;
183                 let mut sender_node_peer_state_lock;
184                 if send_from_initiator {
185                         let chan = get_inbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
186                         chan.context.holder_selected_channel_reserve_satoshis = 0;
187                         chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
188                 } else {
189                         let chan = get_outbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
190                         chan.context.holder_selected_channel_reserve_satoshis = 0;
191                         chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
192                 }
193         }
194
195         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
196         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
197         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
198
199         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
200         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
201         if send_from_initiator {
202                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
203                         // Note that for outbound channels we have to consider the commitment tx fee and the
204                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
205                         // well as an additional HTLC.
206                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
207         } else {
208                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
209         }
210 }
211
212 #[test]
213 fn test_counterparty_no_reserve() {
214         do_test_counterparty_no_reserve(true);
215         do_test_counterparty_no_reserve(false);
216 }
217
218 #[test]
219 fn test_async_inbound_update_fee() {
220         let chanmon_cfgs = create_chanmon_cfgs(2);
221         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
222         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
223         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
224         create_announced_chan_between_nodes(&nodes, 0, 1);
225
226         // balancing
227         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
228
229         // A                                        B
230         // update_fee                            ->
231         // send (1) commitment_signed            -.
232         //                                       <- update_add_htlc/commitment_signed
233         // send (2) RAA (awaiting remote revoke) -.
234         // (1) commitment_signed is delivered    ->
235         //                                       .- send (3) RAA (awaiting remote revoke)
236         // (2) RAA is delivered                  ->
237         //                                       .- send (4) commitment_signed
238         //                                       <- (3) RAA is delivered
239         // send (5) commitment_signed            -.
240         //                                       <- (4) commitment_signed is delivered
241         // send (6) RAA                          -.
242         // (5) commitment_signed is delivered    ->
243         //                                       <- RAA
244         // (6) RAA is delivered                  ->
245
246         // First nodes[0] generates an update_fee
247         {
248                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
249                 *feerate_lock += 20;
250         }
251         nodes[0].node.timer_tick_occurred();
252         check_added_monitors!(nodes[0], 1);
253
254         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
255         assert_eq!(events_0.len(), 1);
256         let (update_msg, commitment_signed) = match events_0[0] { // (1)
257                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
258                         (update_fee.as_ref(), commitment_signed)
259                 },
260                 _ => panic!("Unexpected event"),
261         };
262
263         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
264
265         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
266         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
267         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
268                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
269         check_added_monitors!(nodes[1], 1);
270
271         let payment_event = {
272                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
273                 assert_eq!(events_1.len(), 1);
274                 SendEvent::from_event(events_1.remove(0))
275         };
276         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
277         assert_eq!(payment_event.msgs.len(), 1);
278
279         // ...now when the messages get delivered everyone should be happy
280         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
281         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
282         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
283         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
284         check_added_monitors!(nodes[0], 1);
285
286         // deliver(1), generate (3):
287         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
288         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
289         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
290         check_added_monitors!(nodes[1], 1);
291
292         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
293         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
294         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
295         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
296         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
298         assert!(bs_update.update_fee.is_none()); // (4)
299         check_added_monitors!(nodes[1], 1);
300
301         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
302         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
303         assert!(as_update.update_add_htlcs.is_empty()); // (5)
304         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
305         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
307         assert!(as_update.update_fee.is_none()); // (5)
308         check_added_monitors!(nodes[0], 1);
309
310         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
311         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
312         // only (6) so get_event_msg's assert(len == 1) passes
313         check_added_monitors!(nodes[0], 1);
314
315         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
316         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
317         check_added_monitors!(nodes[1], 1);
318
319         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
320         check_added_monitors!(nodes[0], 1);
321
322         let events_2 = nodes[0].node.get_and_clear_pending_events();
323         assert_eq!(events_2.len(), 1);
324         match events_2[0] {
325                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
326                 _ => panic!("Unexpected event"),
327         }
328
329         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
330         check_added_monitors!(nodes[1], 1);
331 }
332
333 #[test]
334 fn test_update_fee_unordered_raa() {
335         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
336         // crash in an earlier version of the update_fee patch)
337         let chanmon_cfgs = create_chanmon_cfgs(2);
338         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
339         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
340         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
341         create_announced_chan_between_nodes(&nodes, 0, 1);
342
343         // balancing
344         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
345
346         // First nodes[0] generates an update_fee
347         {
348                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
349                 *feerate_lock += 20;
350         }
351         nodes[0].node.timer_tick_occurred();
352         check_added_monitors!(nodes[0], 1);
353
354         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
355         assert_eq!(events_0.len(), 1);
356         let update_msg = match events_0[0] { // (1)
357                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
358                         update_fee.as_ref()
359                 },
360                 _ => panic!("Unexpected event"),
361         };
362
363         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
364
365         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
366         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
367         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
368                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
369         check_added_monitors!(nodes[1], 1);
370
371         let payment_event = {
372                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
373                 assert_eq!(events_1.len(), 1);
374                 SendEvent::from_event(events_1.remove(0))
375         };
376         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
377         assert_eq!(payment_event.msgs.len(), 1);
378
379         // ...now when the messages get delivered everyone should be happy
380         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
381         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
382         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
384         check_added_monitors!(nodes[0], 1);
385
386         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
387         check_added_monitors!(nodes[1], 1);
388
389         // We can't continue, sadly, because our (1) now has a bogus signature
390 }
391
392 #[test]
393 fn test_multi_flight_update_fee() {
394         let chanmon_cfgs = create_chanmon_cfgs(2);
395         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
396         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
397         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
398         create_announced_chan_between_nodes(&nodes, 0, 1);
399
400         // A                                        B
401         // update_fee/commitment_signed          ->
402         //                                       .- send (1) RAA and (2) commitment_signed
403         // update_fee (never committed)          ->
404         // (3) update_fee                        ->
405         // We have to manually generate the above update_fee, it is allowed by the protocol but we
406         // don't track which updates correspond to which revoke_and_ack responses so we're in
407         // AwaitingRAA mode and will not generate the update_fee yet.
408         //                                       <- (1) RAA delivered
409         // (3) is generated and send (4) CS      -.
410         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
411         // know the per_commitment_point to use for it.
412         //                                       <- (2) commitment_signed delivered
413         // revoke_and_ack                        ->
414         //                                          B should send no response here
415         // (4) commitment_signed delivered       ->
416         //                                       <- RAA/commitment_signed delivered
417         // revoke_and_ack                        ->
418
419         // First nodes[0] generates an update_fee
420         let initial_feerate;
421         {
422                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
423                 initial_feerate = *feerate_lock;
424                 *feerate_lock = initial_feerate + 20;
425         }
426         nodes[0].node.timer_tick_occurred();
427         check_added_monitors!(nodes[0], 1);
428
429         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
430         assert_eq!(events_0.len(), 1);
431         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
432                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
433                         (update_fee.as_ref().unwrap(), commitment_signed)
434                 },
435                 _ => panic!("Unexpected event"),
436         };
437
438         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
439         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
440         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
441         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
442         check_added_monitors!(nodes[1], 1);
443
444         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
445         // transaction:
446         {
447                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
448                 *feerate_lock = initial_feerate + 40;
449         }
450         nodes[0].node.timer_tick_occurred();
451         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
452         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
453
454         // Create the (3) update_fee message that nodes[0] will generate before it does...
455         let mut update_msg_2 = msgs::UpdateFee {
456                 channel_id: update_msg_1.channel_id.clone(),
457                 feerate_per_kw: (initial_feerate + 30) as u32,
458         };
459
460         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
461
462         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
463         // Deliver (3)
464         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
465
466         // Deliver (1), generating (3) and (4)
467         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
468         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
469         check_added_monitors!(nodes[0], 1);
470         assert!(as_second_update.update_add_htlcs.is_empty());
471         assert!(as_second_update.update_fulfill_htlcs.is_empty());
472         assert!(as_second_update.update_fail_htlcs.is_empty());
473         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
474         // Check that the update_fee newly generated matches what we delivered:
475         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
476         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
477
478         // Deliver (2) commitment_signed
479         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
480         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
481         check_added_monitors!(nodes[0], 1);
482         // No commitment_signed so get_event_msg's assert(len == 1) passes
483
484         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
485         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
486         check_added_monitors!(nodes[1], 1);
487
488         // Delever (4)
489         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
490         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
491         check_added_monitors!(nodes[1], 1);
492
493         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
494         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
495         check_added_monitors!(nodes[0], 1);
496
497         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
498         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
499         // No commitment_signed so get_event_msg's assert(len == 1) passes
500         check_added_monitors!(nodes[0], 1);
501
502         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
503         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
504         check_added_monitors!(nodes[1], 1);
505 }
506
507 fn do_test_sanity_on_in_flight_opens(steps: u8) {
508         // Previously, we had issues deserializing channels when we hadn't connected the first block
509         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
510         // serialization round-trips and simply do steps towards opening a channel and then drop the
511         // Node objects.
512
513         let chanmon_cfgs = create_chanmon_cfgs(2);
514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
517
518         if steps & 0b1000_0000 != 0{
519                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
520                 connect_block(&nodes[0], &block);
521                 connect_block(&nodes[1], &block);
522         }
523
524         if steps & 0x0f == 0 { return; }
525         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
526         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
527
528         if steps & 0x0f == 1 { return; }
529         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
530         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
531
532         if steps & 0x0f == 2 { return; }
533         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
534
535         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
536
537         if steps & 0x0f == 3 { return; }
538         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
539         check_added_monitors!(nodes[0], 0);
540         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
541
542         if steps & 0x0f == 4 { return; }
543         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
544         {
545                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
546                 assert_eq!(added_monitors.len(), 1);
547                 assert_eq!(added_monitors[0].0, funding_output);
548                 added_monitors.clear();
549         }
550         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
551
552         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
553
554         if steps & 0x0f == 5 { return; }
555         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
556         {
557                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
558                 assert_eq!(added_monitors.len(), 1);
559                 assert_eq!(added_monitors[0].0, funding_output);
560                 added_monitors.clear();
561         }
562
563         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
564         let events_4 = nodes[0].node.get_and_clear_pending_events();
565         assert_eq!(events_4.len(), 0);
566
567         if steps & 0x0f == 6 { return; }
568         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
569
570         if steps & 0x0f == 7 { return; }
571         confirm_transaction_at(&nodes[0], &tx, 2);
572         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
573         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
574         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
575 }
576
577 #[test]
578 fn test_sanity_on_in_flight_opens() {
579         do_test_sanity_on_in_flight_opens(0);
580         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(1);
582         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(2);
584         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(3);
586         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(4);
588         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(5);
590         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
591         do_test_sanity_on_in_flight_opens(6);
592         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
593         do_test_sanity_on_in_flight_opens(7);
594         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
595         do_test_sanity_on_in_flight_opens(8);
596         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
597 }
598
599 #[test]
600 fn test_update_fee_vanilla() {
601         let chanmon_cfgs = create_chanmon_cfgs(2);
602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605         create_announced_chan_between_nodes(&nodes, 0, 1);
606
607         {
608                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
609                 *feerate_lock += 25;
610         }
611         nodes[0].node.timer_tick_occurred();
612         check_added_monitors!(nodes[0], 1);
613
614         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
615         assert_eq!(events_0.len(), 1);
616         let (update_msg, commitment_signed) = match events_0[0] {
617                         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 } } => {
618                         (update_fee.as_ref(), commitment_signed)
619                 },
620                 _ => panic!("Unexpected event"),
621         };
622         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
623
624         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
625         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
626         check_added_monitors!(nodes[1], 1);
627
628         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
629         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
630         check_added_monitors!(nodes[0], 1);
631
632         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
633         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
634         // No commitment_signed so get_event_msg's assert(len == 1) passes
635         check_added_monitors!(nodes[0], 1);
636
637         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
638         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
639         check_added_monitors!(nodes[1], 1);
640 }
641
642 #[test]
643 fn test_update_fee_that_funder_cannot_afford() {
644         let chanmon_cfgs = create_chanmon_cfgs(2);
645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
648         let channel_value = 5000;
649         let push_sats = 700;
650         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
651         let channel_id = chan.2;
652         let secp_ctx = Secp256k1::new();
653         let default_config = UserConfig::default();
654         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
655
656         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
657
658         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
659         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
660         // calculate two different feerates here - the expected local limit as well as the expected
661         // remote limit.
662         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;
663         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
664         {
665                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
666                 *feerate_lock = feerate;
667         }
668         nodes[0].node.timer_tick_occurred();
669         check_added_monitors!(nodes[0], 1);
670         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
671
672         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
673
674         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
675
676         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
677         {
678                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
679
680                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
681                 assert_eq!(commitment_tx.output.len(), 2);
682                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
683                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
684                 actual_fee = channel_value - actual_fee;
685                 assert_eq!(total_fee, actual_fee);
686         }
687
688         {
689                 // Increment the feerate by a small constant, accounting for rounding errors
690                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
691                 *feerate_lock += 4;
692         }
693         nodes[0].node.timer_tick_occurred();
694         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
695         check_added_monitors!(nodes[0], 0);
696
697         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
698
699         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
700         // needed to sign the new commitment tx and (2) sign the new commitment tx.
701         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
702                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
703                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
704                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
705                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
706                 ).flatten().unwrap();
707                 let chan_signer = local_chan.get_signer();
708                 let pubkeys = chan_signer.as_ref().pubkeys();
709                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
710                  pubkeys.funding_pubkey)
711         };
712         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
713                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
714                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
715                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
716                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
717                 ).flatten().unwrap();
718                 let chan_signer = remote_chan.get_signer();
719                 let pubkeys = chan_signer.as_ref().pubkeys();
720                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
721                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
722                  pubkeys.funding_pubkey)
723         };
724
725         // Assemble the set of keys we can use for signatures for our commitment_signed message.
726         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
727                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
728
729         let res = {
730                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
731                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
732                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
733                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
734                 ).flatten().unwrap();
735                 let local_chan_signer = local_chan.get_signer();
736                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
737                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
738                         INITIAL_COMMITMENT_NUMBER - 1,
739                         push_sats,
740                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
741                         local_funding, remote_funding,
742                         commit_tx_keys.clone(),
743                         non_buffer_feerate + 4,
744                         &mut htlcs,
745                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
746                 );
747                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
748         };
749
750         let commit_signed_msg = msgs::CommitmentSigned {
751                 channel_id: chan.2,
752                 signature: res.0,
753                 htlc_signatures: res.1,
754                 #[cfg(taproot)]
755                 partial_signature_with_nonce: None,
756         };
757
758         let update_fee = msgs::UpdateFee {
759                 channel_id: chan.2,
760                 feerate_per_kw: non_buffer_feerate + 4,
761         };
762
763         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
764
765         //While producing the commitment_signed response after handling a received update_fee request the
766         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
767         //Should produce and error.
768         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
769         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
770         check_added_monitors!(nodes[1], 1);
771         check_closed_broadcast!(nodes[1], true);
772         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
773                 [nodes[0].node.get_our_node_id()], channel_value);
774 }
775
776 #[test]
777 fn test_update_fee_with_fundee_update_add_htlc() {
778         let chanmon_cfgs = create_chanmon_cfgs(2);
779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
781         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
782         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
783
784         // balancing
785         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
786
787         {
788                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
789                 *feerate_lock += 20;
790         }
791         nodes[0].node.timer_tick_occurred();
792         check_added_monitors!(nodes[0], 1);
793
794         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
795         assert_eq!(events_0.len(), 1);
796         let (update_msg, commitment_signed) = match events_0[0] {
797                         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 } } => {
798                         (update_fee.as_ref(), commitment_signed)
799                 },
800                 _ => panic!("Unexpected event"),
801         };
802         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
803         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
804         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
805         check_added_monitors!(nodes[1], 1);
806
807         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
808
809         // nothing happens since node[1] is in AwaitingRemoteRevoke
810         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
811                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
812         {
813                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
814                 assert_eq!(added_monitors.len(), 0);
815                 added_monitors.clear();
816         }
817         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
818         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
819         // node[1] has nothing to do
820
821         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
822         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
823         check_added_monitors!(nodes[0], 1);
824
825         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
826         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
827         // No commitment_signed so get_event_msg's assert(len == 1) passes
828         check_added_monitors!(nodes[0], 1);
829         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
830         check_added_monitors!(nodes[1], 1);
831         // AwaitingRemoteRevoke ends here
832
833         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
834         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
835         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
836         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
837         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
838         assert_eq!(commitment_update.update_fee.is_none(), true);
839
840         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
841         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
842         check_added_monitors!(nodes[0], 1);
843         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
844
845         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
846         check_added_monitors!(nodes[1], 1);
847         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
848
849         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
850         check_added_monitors!(nodes[1], 1);
851         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
852         // No commitment_signed so get_event_msg's assert(len == 1) passes
853
854         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
855         check_added_monitors!(nodes[0], 1);
856         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
857
858         expect_pending_htlcs_forwardable!(nodes[0]);
859
860         let events = nodes[0].node.get_and_clear_pending_events();
861         assert_eq!(events.len(), 1);
862         match events[0] {
863                 Event::PaymentClaimable { .. } => { },
864                 _ => panic!("Unexpected event"),
865         };
866
867         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
868
869         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
870         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
871         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
872         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
873         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
874 }
875
876 #[test]
877 fn test_update_fee() {
878         let chanmon_cfgs = create_chanmon_cfgs(2);
879         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
880         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
881         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
882         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
883         let channel_id = chan.2;
884
885         // A                                        B
886         // (1) update_fee/commitment_signed      ->
887         //                                       <- (2) revoke_and_ack
888         //                                       .- send (3) commitment_signed
889         // (4) update_fee/commitment_signed      ->
890         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
891         //                                       <- (3) commitment_signed delivered
892         // send (6) revoke_and_ack               -.
893         //                                       <- (5) deliver revoke_and_ack
894         // (6) deliver revoke_and_ack            ->
895         //                                       .- send (7) commitment_signed in response to (4)
896         //                                       <- (7) deliver commitment_signed
897         // revoke_and_ack                        ->
898
899         // Create and deliver (1)...
900         let feerate;
901         {
902                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
903                 feerate = *feerate_lock;
904                 *feerate_lock = feerate + 20;
905         }
906         nodes[0].node.timer_tick_occurred();
907         check_added_monitors!(nodes[0], 1);
908
909         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
910         assert_eq!(events_0.len(), 1);
911         let (update_msg, commitment_signed) = match events_0[0] {
912                         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 } } => {
913                         (update_fee.as_ref(), commitment_signed)
914                 },
915                 _ => panic!("Unexpected event"),
916         };
917         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
918
919         // Generate (2) and (3):
920         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
921         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
922         check_added_monitors!(nodes[1], 1);
923
924         // Deliver (2):
925         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
926         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
927         check_added_monitors!(nodes[0], 1);
928
929         // Create and deliver (4)...
930         {
931                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
932                 *feerate_lock = feerate + 30;
933         }
934         nodes[0].node.timer_tick_occurred();
935         check_added_monitors!(nodes[0], 1);
936         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
937         assert_eq!(events_0.len(), 1);
938         let (update_msg, commitment_signed) = match events_0[0] {
939                         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 } } => {
940                         (update_fee.as_ref(), commitment_signed)
941                 },
942                 _ => panic!("Unexpected event"),
943         };
944
945         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
946         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
947         check_added_monitors!(nodes[1], 1);
948         // ... creating (5)
949         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
950         // No commitment_signed so get_event_msg's assert(len == 1) passes
951
952         // Handle (3), creating (6):
953         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
954         check_added_monitors!(nodes[0], 1);
955         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
956         // No commitment_signed so get_event_msg's assert(len == 1) passes
957
958         // Deliver (5):
959         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
960         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
961         check_added_monitors!(nodes[0], 1);
962
963         // Deliver (6), creating (7):
964         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
965         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
966         assert!(commitment_update.update_add_htlcs.is_empty());
967         assert!(commitment_update.update_fulfill_htlcs.is_empty());
968         assert!(commitment_update.update_fail_htlcs.is_empty());
969         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
970         assert!(commitment_update.update_fee.is_none());
971         check_added_monitors!(nodes[1], 1);
972
973         // Deliver (7)
974         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
975         check_added_monitors!(nodes[0], 1);
976         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
977         // No commitment_signed so get_event_msg's assert(len == 1) passes
978
979         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
980         check_added_monitors!(nodes[1], 1);
981         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
982
983         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
984         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
985         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
986         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
987         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
988 }
989
990 #[test]
991 fn fake_network_test() {
992         // Simple test which builds a network of ChannelManagers, connects them to each other, and
993         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
994         let chanmon_cfgs = create_chanmon_cfgs(4);
995         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
996         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
997         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
998
999         // Create some initial channels
1000         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1001         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1002         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1003
1004         // Rebalance the network a bit by relaying one payment through all the channels...
1005         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1006         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1008         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1009
1010         // Send some more payments
1011         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1012         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1013         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1014
1015         // Test failure packets
1016         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1017         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1018
1019         // Add a new channel that skips 3
1020         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1021
1022         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1023         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1024         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1025         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1026         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1027         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1028         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1029
1030         // Do some rebalance loop payments, simultaneously
1031         let mut hops = Vec::with_capacity(3);
1032         hops.push(RouteHop {
1033                 pubkey: nodes[2].node.get_our_node_id(),
1034                 node_features: NodeFeatures::empty(),
1035                 short_channel_id: chan_2.0.contents.short_channel_id,
1036                 channel_features: ChannelFeatures::empty(),
1037                 fee_msat: 0,
1038                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1039         });
1040         hops.push(RouteHop {
1041                 pubkey: nodes[3].node.get_our_node_id(),
1042                 node_features: NodeFeatures::empty(),
1043                 short_channel_id: chan_3.0.contents.short_channel_id,
1044                 channel_features: ChannelFeatures::empty(),
1045                 fee_msat: 0,
1046                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1047         });
1048         hops.push(RouteHop {
1049                 pubkey: nodes[1].node.get_our_node_id(),
1050                 node_features: nodes[1].node.node_features(),
1051                 short_channel_id: chan_4.0.contents.short_channel_id,
1052                 channel_features: nodes[1].node.channel_features(),
1053                 fee_msat: 1000000,
1054                 cltv_expiry_delta: TEST_FINAL_CLTV,
1055         });
1056         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;
1057         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;
1058         let payment_preimage_1 = send_along_route(&nodes[1],
1059                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1060                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1061
1062         let mut hops = Vec::with_capacity(3);
1063         hops.push(RouteHop {
1064                 pubkey: nodes[3].node.get_our_node_id(),
1065                 node_features: NodeFeatures::empty(),
1066                 short_channel_id: chan_4.0.contents.short_channel_id,
1067                 channel_features: ChannelFeatures::empty(),
1068                 fee_msat: 0,
1069                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1070         });
1071         hops.push(RouteHop {
1072                 pubkey: nodes[2].node.get_our_node_id(),
1073                 node_features: NodeFeatures::empty(),
1074                 short_channel_id: chan_3.0.contents.short_channel_id,
1075                 channel_features: ChannelFeatures::empty(),
1076                 fee_msat: 0,
1077                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1078         });
1079         hops.push(RouteHop {
1080                 pubkey: nodes[1].node.get_our_node_id(),
1081                 node_features: nodes[1].node.node_features(),
1082                 short_channel_id: chan_2.0.contents.short_channel_id,
1083                 channel_features: nodes[1].node.channel_features(),
1084                 fee_msat: 1000000,
1085                 cltv_expiry_delta: TEST_FINAL_CLTV,
1086         });
1087         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;
1088         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;
1089         let payment_hash_2 = send_along_route(&nodes[1],
1090                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1091                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1092
1093         // Claim the rebalances...
1094         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1095         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1096
1097         // Close down the channels...
1098         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1099         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1100         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1101         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1102         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1103         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1104         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1105         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1106         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1107         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1108         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1109         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1110 }
1111
1112 #[test]
1113 fn holding_cell_htlc_counting() {
1114         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1115         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1116         // commitment dance rounds.
1117         let chanmon_cfgs = create_chanmon_cfgs(3);
1118         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1119         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1120         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1121         create_announced_chan_between_nodes(&nodes, 0, 1);
1122         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1123
1124         // Fetch a route in advance as we will be unable to once we're unable to send.
1125         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1126
1127         let mut payments = Vec::new();
1128         for _ in 0..50 {
1129                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1130                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1131                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1132                 payments.push((payment_preimage, payment_hash));
1133         }
1134         check_added_monitors!(nodes[1], 1);
1135
1136         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1137         assert_eq!(events.len(), 1);
1138         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1139         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1140
1141         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1142         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1143         // another HTLC.
1144         {
1145                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1146                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1147                         ), true, APIError::ChannelUnavailable { .. }, {});
1148                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1149         }
1150
1151         // This should also be true if we try to forward a payment.
1152         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1153         {
1154                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1155                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1156                 check_added_monitors!(nodes[0], 1);
1157         }
1158
1159         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1160         assert_eq!(events.len(), 1);
1161         let payment_event = SendEvent::from_event(events.pop().unwrap());
1162         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1163
1164         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1165         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1166         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1167         // fails), the second will process the resulting failure and fail the HTLC backward.
1168         expect_pending_htlcs_forwardable!(nodes[1]);
1169         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 }]);
1170         check_added_monitors!(nodes[1], 1);
1171
1172         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1173         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1174         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1175
1176         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1177
1178         // Now forward all the pending HTLCs and claim them back
1179         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1180         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1181         check_added_monitors!(nodes[2], 1);
1182
1183         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185         check_added_monitors!(nodes[1], 1);
1186         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1187
1188         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1189         check_added_monitors!(nodes[1], 1);
1190         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1191
1192         for ref update in as_updates.update_add_htlcs.iter() {
1193                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1194         }
1195         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1196         check_added_monitors!(nodes[2], 1);
1197         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1198         check_added_monitors!(nodes[2], 1);
1199         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1200
1201         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1202         check_added_monitors!(nodes[1], 1);
1203         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1204         check_added_monitors!(nodes[1], 1);
1205         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1206
1207         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1208         check_added_monitors!(nodes[2], 1);
1209
1210         expect_pending_htlcs_forwardable!(nodes[2]);
1211
1212         let events = nodes[2].node.get_and_clear_pending_events();
1213         assert_eq!(events.len(), payments.len());
1214         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1215                 match event {
1216                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1217                                 assert_eq!(*payment_hash, *hash);
1218                         },
1219                         _ => panic!("Unexpected event"),
1220                 };
1221         }
1222
1223         for (preimage, _) in payments.drain(..) {
1224                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1225         }
1226
1227         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1228 }
1229
1230 #[test]
1231 fn duplicate_htlc_test() {
1232         // Test that we accept duplicate payment_hash HTLCs across the network and that
1233         // claiming/failing them are all separate and don't affect each other
1234         let chanmon_cfgs = create_chanmon_cfgs(6);
1235         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1236         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1237         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1238
1239         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1240         create_announced_chan_between_nodes(&nodes, 0, 3);
1241         create_announced_chan_between_nodes(&nodes, 1, 3);
1242         create_announced_chan_between_nodes(&nodes, 2, 3);
1243         create_announced_chan_between_nodes(&nodes, 3, 4);
1244         create_announced_chan_between_nodes(&nodes, 3, 5);
1245
1246         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1247
1248         *nodes[0].network_payment_count.borrow_mut() -= 1;
1249         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1250
1251         *nodes[0].network_payment_count.borrow_mut() -= 1;
1252         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1253
1254         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1255         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1256         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1257 }
1258
1259 #[test]
1260 fn test_duplicate_htlc_different_direction_onchain() {
1261         // Test that ChannelMonitor doesn't generate 2 preimage txn
1262         // when we have 2 HTLCs with same preimage that go across a node
1263         // in opposite directions, even with the same payment secret.
1264         let chanmon_cfgs = create_chanmon_cfgs(2);
1265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1267         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1268
1269         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1270
1271         // balancing
1272         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1273
1274         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1275
1276         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1277         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1278         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1279
1280         // Provide preimage to node 0 by claiming payment
1281         nodes[0].node.claim_funds(payment_preimage);
1282         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1283         check_added_monitors!(nodes[0], 1);
1284
1285         // Broadcast node 1 commitment txn
1286         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1287
1288         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1289         let mut has_both_htlcs = 0; // check htlcs match ones committed
1290         for outp in remote_txn[0].output.iter() {
1291                 if outp.value == 800_000 / 1000 {
1292                         has_both_htlcs += 1;
1293                 } else if outp.value == 900_000 / 1000 {
1294                         has_both_htlcs += 1;
1295                 }
1296         }
1297         assert_eq!(has_both_htlcs, 2);
1298
1299         mine_transaction(&nodes[0], &remote_txn[0]);
1300         check_added_monitors!(nodes[0], 1);
1301         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1302         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1303
1304         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1305         assert_eq!(claim_txn.len(), 3);
1306
1307         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1308         check_spends!(claim_txn[1], remote_txn[0]);
1309         check_spends!(claim_txn[2], remote_txn[0]);
1310         let preimage_tx = &claim_txn[0];
1311         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1312                 (&claim_txn[1], &claim_txn[2])
1313         } else {
1314                 (&claim_txn[2], &claim_txn[1])
1315         };
1316
1317         assert_eq!(preimage_tx.input.len(), 1);
1318         assert_eq!(preimage_bump_tx.input.len(), 1);
1319
1320         assert_eq!(preimage_tx.input.len(), 1);
1321         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1322         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1323
1324         assert_eq!(timeout_tx.input.len(), 1);
1325         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1326         check_spends!(timeout_tx, remote_txn[0]);
1327         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1328
1329         let events = nodes[0].node.get_and_clear_pending_msg_events();
1330         assert_eq!(events.len(), 3);
1331         for e in events {
1332                 match e {
1333                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1334                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1335                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1336                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1337                         },
1338                         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, .. } } => {
1339                                 assert!(update_add_htlcs.is_empty());
1340                                 assert!(update_fail_htlcs.is_empty());
1341                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1342                                 assert!(update_fail_malformed_htlcs.is_empty());
1343                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1344                         },
1345                         _ => panic!("Unexpected event"),
1346                 }
1347         }
1348 }
1349
1350 #[test]
1351 fn test_basic_channel_reserve() {
1352         let chanmon_cfgs = create_chanmon_cfgs(2);
1353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1356         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1357
1358         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1359         let channel_reserve = chan_stat.channel_reserve_msat;
1360
1361         // The 2* and +1 are for the fee spike reserve.
1362         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));
1363         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1364         let (mut route, our_payment_hash, _, our_payment_secret) =
1365                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1366         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1367         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1368                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1369         match err {
1370                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1371                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1372                         else { panic!("Unexpected error variant"); }
1373                 },
1374                 _ => panic!("Unexpected error variant"),
1375         }
1376         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1377
1378         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1379 }
1380
1381 #[test]
1382 fn test_fee_spike_violation_fails_htlc() {
1383         let chanmon_cfgs = create_chanmon_cfgs(2);
1384         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1385         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1386         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1387         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1388
1389         let (mut route, payment_hash, _, payment_secret) =
1390                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1391         route.paths[0].hops[0].fee_msat += 1;
1392         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1393         let secp_ctx = Secp256k1::new();
1394         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1395
1396         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1397
1398         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1399         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1400                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1401         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1402         let msg = msgs::UpdateAddHTLC {
1403                 channel_id: chan.2,
1404                 htlc_id: 0,
1405                 amount_msat: htlc_msat,
1406                 payment_hash: payment_hash,
1407                 cltv_expiry: htlc_cltv,
1408                 onion_routing_packet: onion_packet,
1409                 skimmed_fee_msat: None,
1410         };
1411
1412         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1413
1414         // Now manually create the commitment_signed message corresponding to the update_add
1415         // nodes[0] just sent. In the code for construction of this message, "local" refers
1416         // to the sender of the message, and "remote" refers to the receiver.
1417
1418         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1419
1420         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1421
1422         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1423         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1424         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1425                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1426                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1427                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1428                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1429                 ).flatten().unwrap();
1430                 let chan_signer = local_chan.get_signer();
1431                 // Make the signer believe we validated another commitment, so we can release the secret
1432                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1433
1434                 let pubkeys = chan_signer.as_ref().pubkeys();
1435                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1436                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1437                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1438                  chan_signer.as_ref().pubkeys().funding_pubkey)
1439         };
1440         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1441                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1442                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1443                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1444                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1445                 ).flatten().unwrap();
1446                 let chan_signer = remote_chan.get_signer();
1447                 let pubkeys = chan_signer.as_ref().pubkeys();
1448                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1449                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1450                  chan_signer.as_ref().pubkeys().funding_pubkey)
1451         };
1452
1453         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1454         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1455                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1456
1457         // Build the remote commitment transaction so we can sign it, and then later use the
1458         // signature for the commitment_signed message.
1459         let local_chan_balance = 1313;
1460
1461         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1462                 offered: false,
1463                 amount_msat: 3460001,
1464                 cltv_expiry: htlc_cltv,
1465                 payment_hash,
1466                 transaction_output_index: Some(1),
1467         };
1468
1469         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1470
1471         let res = {
1472                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1473                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1474                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1475                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1476                 ).flatten().unwrap();
1477                 let local_chan_signer = local_chan.get_signer();
1478                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1479                         commitment_number,
1480                         95000,
1481                         local_chan_balance,
1482                         local_funding, remote_funding,
1483                         commit_tx_keys.clone(),
1484                         feerate_per_kw,
1485                         &mut vec![(accepted_htlc_info, ())],
1486                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1487                 );
1488                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1489         };
1490
1491         let commit_signed_msg = msgs::CommitmentSigned {
1492                 channel_id: chan.2,
1493                 signature: res.0,
1494                 htlc_signatures: res.1,
1495                 #[cfg(taproot)]
1496                 partial_signature_with_nonce: None,
1497         };
1498
1499         // Send the commitment_signed message to the nodes[1].
1500         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1501         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1502
1503         // Send the RAA to nodes[1].
1504         let raa_msg = msgs::RevokeAndACK {
1505                 channel_id: chan.2,
1506                 per_commitment_secret: local_secret,
1507                 next_per_commitment_point: next_local_point,
1508                 #[cfg(taproot)]
1509                 next_local_nonce: None,
1510         };
1511         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1512
1513         let events = nodes[1].node.get_and_clear_pending_msg_events();
1514         assert_eq!(events.len(), 1);
1515         // Make sure the HTLC failed in the way we expect.
1516         match events[0] {
1517                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1518                         assert_eq!(update_fail_htlcs.len(), 1);
1519                         update_fail_htlcs[0].clone()
1520                 },
1521                 _ => panic!("Unexpected event"),
1522         };
1523         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1524                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1525
1526         check_added_monitors!(nodes[1], 2);
1527 }
1528
1529 #[test]
1530 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1531         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1532         // Set the fee rate for the channel very high, to the point where the fundee
1533         // sending any above-dust amount would result in a channel reserve violation.
1534         // In this test we check that we would be prevented from sending an HTLC in
1535         // this situation.
1536         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1537         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1538         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1539         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1540         let default_config = UserConfig::default();
1541         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1542
1543         let mut push_amt = 100_000_000;
1544         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1545
1546         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1547
1548         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1549
1550         // Fetch a route in advance as we will be unable to once we're unable to send.
1551         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1552         // Sending exactly enough to hit the reserve amount should be accepted
1553         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1554                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1555         }
1556
1557         // However one more HTLC should be significantly over the reserve amount and fail.
1558         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1559                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1560                 ), true, APIError::ChannelUnavailable { .. }, {});
1561         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1562 }
1563
1564 #[test]
1565 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1566         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1567         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1568         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1569         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1570         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1571         let default_config = UserConfig::default();
1572         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1573
1574         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1575         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1576         // transaction fee with 0 HTLCs (183 sats)).
1577         let mut push_amt = 100_000_000;
1578         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1579         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1580         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1581
1582         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1583         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1584                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1585         }
1586
1587         let (mut route, payment_hash, _, payment_secret) =
1588                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1589         route.paths[0].hops[0].fee_msat = 700_000;
1590         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1591         let secp_ctx = Secp256k1::new();
1592         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1593         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1594         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1595         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1596                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1597         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1598         let msg = msgs::UpdateAddHTLC {
1599                 channel_id: chan.2,
1600                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1601                 amount_msat: htlc_msat,
1602                 payment_hash: payment_hash,
1603                 cltv_expiry: htlc_cltv,
1604                 onion_routing_packet: onion_packet,
1605                 skimmed_fee_msat: None,
1606         };
1607
1608         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1609         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1610         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1611         assert_eq!(nodes[0].node.list_channels().len(), 0);
1612         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1613         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1614         check_added_monitors!(nodes[0], 1);
1615         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() },
1616                 [nodes[1].node.get_our_node_id()], 100000);
1617 }
1618
1619 #[test]
1620 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1621         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1622         // calculating our commitment transaction fee (this was previously broken).
1623         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1624         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1625
1626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1628         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1629         let default_config = UserConfig::default();
1630         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1631
1632         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1633         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1634         // transaction fee with 0 HTLCs (183 sats)).
1635         let mut push_amt = 100_000_000;
1636         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1637         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1638         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1639
1640         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1641                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1642         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1643         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1644         // commitment transaction fee.
1645         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1646
1647         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1648         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1649                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1650         }
1651
1652         // One more than the dust amt should fail, however.
1653         let (mut route, our_payment_hash, _, our_payment_secret) =
1654                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1655         route.paths[0].hops[0].fee_msat += 1;
1656         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1657                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1658                 ), true, APIError::ChannelUnavailable { .. }, {});
1659 }
1660
1661 #[test]
1662 fn test_chan_init_feerate_unaffordability() {
1663         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1664         // channel reserve and feerate requirements.
1665         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1666         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1667         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1668         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1669         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1670         let default_config = UserConfig::default();
1671         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1672
1673         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1674         // HTLC.
1675         let mut push_amt = 100_000_000;
1676         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1677         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1678                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1679
1680         // During open, we don't have a "counterparty channel reserve" to check against, so that
1681         // requirement only comes into play on the open_channel handling side.
1682         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1683         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1684         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1685         open_channel_msg.push_msat += 1;
1686         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1687
1688         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1689         assert_eq!(msg_events.len(), 1);
1690         match msg_events[0] {
1691                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1692                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1693                 },
1694                 _ => panic!("Unexpected event"),
1695         }
1696 }
1697
1698 #[test]
1699 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1700         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1701         // calculating our counterparty's commitment transaction fee (this was previously broken).
1702         let chanmon_cfgs = create_chanmon_cfgs(2);
1703         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1704         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1705         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1706         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1707
1708         let payment_amt = 46000; // Dust amount
1709         // In the previous code, these first four payments would succeed.
1710         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1711         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1712         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1713         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1714
1715         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1716         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1717         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1718         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1719         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1720         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721
1722         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1723         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1724         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1725         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1726 }
1727
1728 #[test]
1729 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1730         let chanmon_cfgs = create_chanmon_cfgs(3);
1731         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1732         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1733         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1734         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1735         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1736
1737         let feemsat = 239;
1738         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1739         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1740         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1741         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1742
1743         // Add a 2* and +1 for the fee spike reserve.
1744         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1745         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;
1746         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1747
1748         // Add a pending HTLC.
1749         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1750         let payment_event_1 = {
1751                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1752                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1753                 check_added_monitors!(nodes[0], 1);
1754
1755                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1756                 assert_eq!(events.len(), 1);
1757                 SendEvent::from_event(events.remove(0))
1758         };
1759         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1760
1761         // Attempt to trigger a channel reserve violation --> payment failure.
1762         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1763         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;
1764         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1765         let mut route_2 = route_1.clone();
1766         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1767
1768         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1769         let secp_ctx = Secp256k1::new();
1770         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1771         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1772         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1773         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1774                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1775         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1776         let msg = msgs::UpdateAddHTLC {
1777                 channel_id: chan.2,
1778                 htlc_id: 1,
1779                 amount_msat: htlc_msat + 1,
1780                 payment_hash: our_payment_hash_1,
1781                 cltv_expiry: htlc_cltv,
1782                 onion_routing_packet: onion_packet,
1783                 skimmed_fee_msat: None,
1784         };
1785
1786         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1787         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1788         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1789         assert_eq!(nodes[1].node.list_channels().len(), 1);
1790         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1791         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1792         check_added_monitors!(nodes[1], 1);
1793         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1794                 [nodes[0].node.get_our_node_id()], 100000);
1795 }
1796
1797 #[test]
1798 fn test_inbound_outbound_capacity_is_not_zero() {
1799         let chanmon_cfgs = create_chanmon_cfgs(2);
1800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1803         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1804         let channels0 = node_chanmgrs[0].list_channels();
1805         let channels1 = node_chanmgrs[1].list_channels();
1806         let default_config = UserConfig::default();
1807         assert_eq!(channels0.len(), 1);
1808         assert_eq!(channels1.len(), 1);
1809
1810         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1811         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1812         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1813
1814         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1815         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1816 }
1817
1818 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1819         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1820 }
1821
1822 #[test]
1823 fn test_channel_reserve_holding_cell_htlcs() {
1824         let chanmon_cfgs = create_chanmon_cfgs(3);
1825         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1826         // When this test was written, the default base fee floated based on the HTLC count.
1827         // It is now fixed, so we simply set the fee to the expected value here.
1828         let mut config = test_default_channel_config();
1829         config.channel_config.forwarding_fee_base_msat = 239;
1830         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1831         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1832         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1833         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1834
1835         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1836         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1837
1838         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1839         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1840
1841         macro_rules! expect_forward {
1842                 ($node: expr) => {{
1843                         let mut events = $node.node.get_and_clear_pending_msg_events();
1844                         assert_eq!(events.len(), 1);
1845                         check_added_monitors!($node, 1);
1846                         let payment_event = SendEvent::from_event(events.remove(0));
1847                         payment_event
1848                 }}
1849         }
1850
1851         let feemsat = 239; // set above
1852         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1853         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1854         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1855
1856         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1857
1858         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1859         {
1860                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1861                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1862                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1863                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1864                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1865
1866                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1867                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1868                         ), true, APIError::ChannelUnavailable { .. }, {});
1869                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1870         }
1871
1872         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1873         // nodes[0]'s wealth
1874         loop {
1875                 let amt_msat = recv_value_0 + total_fee_msat;
1876                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1877                 // Also, ensure that each payment has enough to be over the dust limit to
1878                 // ensure it'll be included in each commit tx fee calculation.
1879                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1880                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1881                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1882                         break;
1883                 }
1884
1885                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1886                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1887                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1888                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1889                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1890
1891                 let (stat01_, stat11_, stat12_, stat22_) = (
1892                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1893                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1894                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1895                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1896                 );
1897
1898                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1899                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1900                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1901                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1902                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1903         }
1904
1905         // adding pending output.
1906         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1907         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1908         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1909         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1910         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1911         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1912         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1913         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1914         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1915         // policy.
1916         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1917         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1918         let amt_msat_1 = recv_value_1 + total_fee_msat;
1919
1920         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);
1921         let payment_event_1 = {
1922                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1923                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1924                 check_added_monitors!(nodes[0], 1);
1925
1926                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1927                 assert_eq!(events.len(), 1);
1928                 SendEvent::from_event(events.remove(0))
1929         };
1930         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1931
1932         // channel reserve test with htlc pending output > 0
1933         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1934         {
1935                 let mut route = route_1.clone();
1936                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1937                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1938                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1939                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1940                         ), true, APIError::ChannelUnavailable { .. }, {});
1941                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1942         }
1943
1944         // split the rest to test holding cell
1945         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1946         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1947         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1948         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1949         {
1950                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1951                 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);
1952         }
1953
1954         // now see if they go through on both sides
1955         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);
1956         // but this will stuck in the holding cell
1957         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1958                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1959         check_added_monitors!(nodes[0], 0);
1960         let events = nodes[0].node.get_and_clear_pending_events();
1961         assert_eq!(events.len(), 0);
1962
1963         // test with outbound holding cell amount > 0
1964         {
1965                 let (mut route, our_payment_hash, _, our_payment_secret) =
1966                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1967                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1968                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1969                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1970                         ), true, APIError::ChannelUnavailable { .. }, {});
1971                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1972         }
1973
1974         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);
1975         // this will also stuck in the holding cell
1976         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1977                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1978         check_added_monitors!(nodes[0], 0);
1979         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1980         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1981
1982         // flush the pending htlc
1983         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1984         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1985         check_added_monitors!(nodes[1], 1);
1986
1987         // the pending htlc should be promoted to committed
1988         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1989         check_added_monitors!(nodes[0], 1);
1990         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1991
1992         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1993         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1994         // No commitment_signed so get_event_msg's assert(len == 1) passes
1995         check_added_monitors!(nodes[0], 1);
1996
1997         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1998         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1999         check_added_monitors!(nodes[1], 1);
2000
2001         expect_pending_htlcs_forwardable!(nodes[1]);
2002
2003         let ref payment_event_11 = expect_forward!(nodes[1]);
2004         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2005         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2006
2007         expect_pending_htlcs_forwardable!(nodes[2]);
2008         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2009
2010         // flush the htlcs in the holding cell
2011         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2012         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2013         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2014         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2015         expect_pending_htlcs_forwardable!(nodes[1]);
2016
2017         let ref payment_event_3 = expect_forward!(nodes[1]);
2018         assert_eq!(payment_event_3.msgs.len(), 2);
2019         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2020         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2021
2022         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2023         expect_pending_htlcs_forwardable!(nodes[2]);
2024
2025         let events = nodes[2].node.get_and_clear_pending_events();
2026         assert_eq!(events.len(), 2);
2027         match events[0] {
2028                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2029                         assert_eq!(our_payment_hash_21, *payment_hash);
2030                         assert_eq!(recv_value_21, amount_msat);
2031                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2032                         assert_eq!(via_channel_id, Some(chan_2.2));
2033                         match &purpose {
2034                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2035                                         assert!(payment_preimage.is_none());
2036                                         assert_eq!(our_payment_secret_21, *payment_secret);
2037                                 },
2038                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2039                         }
2040                 },
2041                 _ => panic!("Unexpected event"),
2042         }
2043         match events[1] {
2044                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2045                         assert_eq!(our_payment_hash_22, *payment_hash);
2046                         assert_eq!(recv_value_22, amount_msat);
2047                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2048                         assert_eq!(via_channel_id, Some(chan_2.2));
2049                         match &purpose {
2050                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2051                                         assert!(payment_preimage.is_none());
2052                                         assert_eq!(our_payment_secret_22, *payment_secret);
2053                                 },
2054                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2055                         }
2056                 },
2057                 _ => panic!("Unexpected event"),
2058         }
2059
2060         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2061         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2062         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2063
2064         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2065         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2066         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2067
2068         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2069         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);
2070         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2071         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2072         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2073
2074         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2075         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2076 }
2077
2078 #[test]
2079 fn channel_reserve_in_flight_removes() {
2080         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2081         // can send to its counterparty, but due to update ordering, the other side may not yet have
2082         // considered those HTLCs fully removed.
2083         // This tests that we don't count HTLCs which will not be included in the next remote
2084         // commitment transaction towards the reserve value (as it implies no commitment transaction
2085         // will be generated which violates the remote reserve value).
2086         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2087         // To test this we:
2088         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2089         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2090         //    you only consider the value of the first HTLC, it may not),
2091         //  * start routing a third HTLC from A to B,
2092         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2093         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2094         //  * deliver the first fulfill from B
2095         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2096         //    claim,
2097         //  * deliver A's response CS and RAA.
2098         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2099         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2100         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2101         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2102         let chanmon_cfgs = create_chanmon_cfgs(2);
2103         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2104         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2105         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2106         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2107
2108         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2109         // Route the first two HTLCs.
2110         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2111         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2112         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2113
2114         // Start routing the third HTLC (this is just used to get everyone in the right state).
2115         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2116         let send_1 = {
2117                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2118                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2119                 check_added_monitors!(nodes[0], 1);
2120                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2121                 assert_eq!(events.len(), 1);
2122                 SendEvent::from_event(events.remove(0))
2123         };
2124
2125         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2126         // initial fulfill/CS.
2127         nodes[1].node.claim_funds(payment_preimage_1);
2128         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2129         check_added_monitors!(nodes[1], 1);
2130         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2131
2132         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2133         // remove the second HTLC when we send the HTLC back from B to A.
2134         nodes[1].node.claim_funds(payment_preimage_2);
2135         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2136         check_added_monitors!(nodes[1], 1);
2137         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2138
2139         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2140         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2141         check_added_monitors!(nodes[0], 1);
2142         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2143         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2144
2145         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2146         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2147         check_added_monitors!(nodes[1], 1);
2148         // B is already AwaitingRAA, so cant generate a CS here
2149         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2150
2151         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2152         check_added_monitors!(nodes[1], 1);
2153         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2154
2155         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2156         check_added_monitors!(nodes[0], 1);
2157         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2158
2159         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2160         check_added_monitors!(nodes[1], 1);
2161         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2162
2163         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2164         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2165         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2166         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2167         // on-chain as necessary).
2168         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2169         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2170         check_added_monitors!(nodes[0], 1);
2171         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2172         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2173
2174         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2175         check_added_monitors!(nodes[1], 1);
2176         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2177
2178         expect_pending_htlcs_forwardable!(nodes[1]);
2179         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2180
2181         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2182         // resolve the second HTLC from A's point of view.
2183         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2184         check_added_monitors!(nodes[0], 1);
2185         expect_payment_path_successful!(nodes[0]);
2186         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2187
2188         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2189         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2190         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2191         let send_2 = {
2192                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2193                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2194                 check_added_monitors!(nodes[1], 1);
2195                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2196                 assert_eq!(events.len(), 1);
2197                 SendEvent::from_event(events.remove(0))
2198         };
2199
2200         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2201         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2202         check_added_monitors!(nodes[0], 1);
2203         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2204
2205         // Now just resolve all the outstanding messages/HTLCs for completeness...
2206
2207         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2208         check_added_monitors!(nodes[1], 1);
2209         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2210
2211         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2212         check_added_monitors!(nodes[1], 1);
2213
2214         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2215         check_added_monitors!(nodes[0], 1);
2216         expect_payment_path_successful!(nodes[0]);
2217         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2218
2219         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2220         check_added_monitors!(nodes[1], 1);
2221         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2222
2223         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2224         check_added_monitors!(nodes[0], 1);
2225
2226         expect_pending_htlcs_forwardable!(nodes[0]);
2227         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2228
2229         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2230         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2231 }
2232
2233 #[test]
2234 fn channel_monitor_network_test() {
2235         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2236         // tests that ChannelMonitor is able to recover from various states.
2237         let chanmon_cfgs = create_chanmon_cfgs(5);
2238         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2239         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2240         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2241
2242         // Create some initial channels
2243         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2244         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2245         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2246         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2247
2248         // Make sure all nodes are at the same starting height
2249         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2250         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2251         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2252         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2253         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2254
2255         // Rebalance the network a bit by relaying one payment through all the channels...
2256         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2257         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2258         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2259         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2260
2261         // Simple case with no pending HTLCs:
2262         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2263         check_added_monitors!(nodes[1], 1);
2264         check_closed_broadcast!(nodes[1], true);
2265         {
2266                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2267                 assert_eq!(node_txn.len(), 1);
2268                 mine_transaction(&nodes[0], &node_txn[0]);
2269                 check_added_monitors!(nodes[0], 1);
2270                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2271         }
2272         check_closed_broadcast!(nodes[0], true);
2273         assert_eq!(nodes[0].node.list_channels().len(), 0);
2274         assert_eq!(nodes[1].node.list_channels().len(), 1);
2275         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2276         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2277
2278         // One pending HTLC is discarded by the force-close:
2279         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2280
2281         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2282         // broadcasted until we reach the timelock time).
2283         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2284         check_closed_broadcast!(nodes[1], true);
2285         check_added_monitors!(nodes[1], 1);
2286         {
2287                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2288                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2289                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2290                 mine_transaction(&nodes[2], &node_txn[0]);
2291                 check_added_monitors!(nodes[2], 1);
2292                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2293         }
2294         check_closed_broadcast!(nodes[2], true);
2295         assert_eq!(nodes[1].node.list_channels().len(), 0);
2296         assert_eq!(nodes[2].node.list_channels().len(), 1);
2297         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2298         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2299
2300         macro_rules! claim_funds {
2301                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2302                         {
2303                                 $node.node.claim_funds($preimage);
2304                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2305                                 check_added_monitors!($node, 1);
2306
2307                                 let events = $node.node.get_and_clear_pending_msg_events();
2308                                 assert_eq!(events.len(), 1);
2309                                 match events[0] {
2310                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2311                                                 assert!(update_add_htlcs.is_empty());
2312                                                 assert!(update_fail_htlcs.is_empty());
2313                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2314                                         },
2315                                         _ => panic!("Unexpected event"),
2316                                 };
2317                         }
2318                 }
2319         }
2320
2321         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2322         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2323         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2324         check_added_monitors!(nodes[2], 1);
2325         check_closed_broadcast!(nodes[2], true);
2326         let node2_commitment_txid;
2327         {
2328                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2329                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2330                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2331                 node2_commitment_txid = node_txn[0].txid();
2332
2333                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2334                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2335                 mine_transaction(&nodes[3], &node_txn[0]);
2336                 check_added_monitors!(nodes[3], 1);
2337                 check_preimage_claim(&nodes[3], &node_txn);
2338         }
2339         check_closed_broadcast!(nodes[3], true);
2340         assert_eq!(nodes[2].node.list_channels().len(), 0);
2341         assert_eq!(nodes[3].node.list_channels().len(), 1);
2342         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2343         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2344
2345         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2346         // confusing us in the following tests.
2347         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2348
2349         // One pending HTLC to time out:
2350         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2351         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2352         // buffer space).
2353
2354         let (close_chan_update_1, close_chan_update_2) = {
2355                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2356                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2357                 assert_eq!(events.len(), 2);
2358                 let close_chan_update_1 = match events[0] {
2359                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2360                                 msg.clone()
2361                         },
2362                         _ => panic!("Unexpected event"),
2363                 };
2364                 match events[1] {
2365                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2366                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2367                         },
2368                         _ => panic!("Unexpected event"),
2369                 }
2370                 check_added_monitors!(nodes[3], 1);
2371
2372                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2373                 {
2374                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2375                         node_txn.retain(|tx| {
2376                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2377                                         false
2378                                 } else { true }
2379                         });
2380                 }
2381
2382                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2383
2384                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2385                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2386
2387                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2388                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2389                 assert_eq!(events.len(), 2);
2390                 let close_chan_update_2 = match events[0] {
2391                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2392                                 msg.clone()
2393                         },
2394                         _ => panic!("Unexpected event"),
2395                 };
2396                 match events[1] {
2397                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2398                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2399                         },
2400                         _ => panic!("Unexpected event"),
2401                 }
2402                 check_added_monitors!(nodes[4], 1);
2403                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2404
2405                 mine_transaction(&nodes[4], &node_txn[0]);
2406                 check_preimage_claim(&nodes[4], &node_txn);
2407                 (close_chan_update_1, close_chan_update_2)
2408         };
2409         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2410         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2411         assert_eq!(nodes[3].node.list_channels().len(), 0);
2412         assert_eq!(nodes[4].node.list_channels().len(), 0);
2413
2414         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2415                 ChannelMonitorUpdateStatus::Completed);
2416         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2417         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2418 }
2419
2420 #[test]
2421 fn test_justice_tx_htlc_timeout() {
2422         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2423         let mut alice_config = UserConfig::default();
2424         alice_config.channel_handshake_config.announced_channel = true;
2425         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2426         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2427         let mut bob_config = UserConfig::default();
2428         bob_config.channel_handshake_config.announced_channel = true;
2429         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2430         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2431         let user_cfgs = [Some(alice_config), Some(bob_config)];
2432         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2433         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2434         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2435         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2436         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2437         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2438         // Create some new channels:
2439         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2440
2441         // A pending HTLC which will be revoked:
2442         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2443         // Get the will-be-revoked local txn from nodes[0]
2444         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2445         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2446         assert_eq!(revoked_local_txn[0].input.len(), 1);
2447         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2448         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2449         assert_eq!(revoked_local_txn[1].input.len(), 1);
2450         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2451         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2452         // Revoke the old state
2453         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2454
2455         {
2456                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2457                 {
2458                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2459                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2460                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2461                         check_spends!(node_txn[0], revoked_local_txn[0]);
2462                         node_txn.swap_remove(0);
2463                 }
2464                 check_added_monitors!(nodes[1], 1);
2465                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2466                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2467
2468                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2469                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2470                 // Verify broadcast of revoked HTLC-timeout
2471                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2472                 check_added_monitors!(nodes[0], 1);
2473                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2474                 // Broadcast revoked HTLC-timeout on node 1
2475                 mine_transaction(&nodes[1], &node_txn[1]);
2476                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2477         }
2478         get_announce_close_broadcast_events(&nodes, 0, 1);
2479         assert_eq!(nodes[0].node.list_channels().len(), 0);
2480         assert_eq!(nodes[1].node.list_channels().len(), 0);
2481 }
2482
2483 #[test]
2484 fn test_justice_tx_htlc_success() {
2485         // Test justice txn built on revoked HTLC-Success tx, against both sides
2486         let mut alice_config = UserConfig::default();
2487         alice_config.channel_handshake_config.announced_channel = true;
2488         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2489         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2490         let mut bob_config = UserConfig::default();
2491         bob_config.channel_handshake_config.announced_channel = true;
2492         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2493         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2494         let user_cfgs = [Some(alice_config), Some(bob_config)];
2495         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2496         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2497         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2498         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2499         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2500         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2501         // Create some new channels:
2502         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2503
2504         // A pending HTLC which will be revoked:
2505         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2506         // Get the will-be-revoked local txn from B
2507         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2508         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2509         assert_eq!(revoked_local_txn[0].input.len(), 1);
2510         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2511         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2512         // Revoke the old state
2513         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2514         {
2515                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2516                 {
2517                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2518                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2519                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2520
2521                         check_spends!(node_txn[0], revoked_local_txn[0]);
2522                         node_txn.swap_remove(0);
2523                 }
2524                 check_added_monitors!(nodes[0], 1);
2525                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2526
2527                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2528                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2529                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2530                 check_added_monitors!(nodes[1], 1);
2531                 mine_transaction(&nodes[0], &node_txn[1]);
2532                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2533                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2534         }
2535         get_announce_close_broadcast_events(&nodes, 0, 1);
2536         assert_eq!(nodes[0].node.list_channels().len(), 0);
2537         assert_eq!(nodes[1].node.list_channels().len(), 0);
2538 }
2539
2540 #[test]
2541 fn revoked_output_claim() {
2542         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2543         // transaction is broadcast by its counterparty
2544         let chanmon_cfgs = create_chanmon_cfgs(2);
2545         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2546         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2547         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2548         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2549         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2550         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2551         assert_eq!(revoked_local_txn.len(), 1);
2552         // Only output is the full channel value back to nodes[0]:
2553         assert_eq!(revoked_local_txn[0].output.len(), 1);
2554         // Send a payment through, updating everyone's latest commitment txn
2555         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2556
2557         // Inform nodes[1] that nodes[0] broadcast a stale tx
2558         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2559         check_added_monitors!(nodes[1], 1);
2560         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2561         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2562         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2563
2564         check_spends!(node_txn[0], revoked_local_txn[0]);
2565
2566         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2567         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2568         get_announce_close_broadcast_events(&nodes, 0, 1);
2569         check_added_monitors!(nodes[0], 1);
2570         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2571 }
2572
2573 #[test]
2574 fn test_forming_justice_tx_from_monitor_updates() {
2575         do_test_forming_justice_tx_from_monitor_updates(true);
2576         do_test_forming_justice_tx_from_monitor_updates(false);
2577 }
2578
2579 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2580         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2581         // is properly formed and can be broadcasted/confirmed successfully in the event
2582         // that a revoked commitment transaction is broadcasted
2583         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2584         let chanmon_cfgs = create_chanmon_cfgs(2);
2585         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2586         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2587         let persisters = vec![WatchtowerPersister::new(destination_script0),
2588                 WatchtowerPersister::new(destination_script1)];
2589         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2592         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2593         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2594
2595         if !broadcast_initial_commitment {
2596                 // Send a payment to move the channel forward
2597                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2598         }
2599
2600         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2601         // We'll keep this commitment transaction to broadcast once it's revoked.
2602         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2603         assert_eq!(revoked_local_txn.len(), 1);
2604         let revoked_commitment_tx = &revoked_local_txn[0];
2605
2606         // Send another payment, now revoking the previous commitment tx
2607         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2608
2609         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2610         check_spends!(justice_tx, revoked_commitment_tx);
2611
2612         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2613         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2614
2615         check_added_monitors!(nodes[1], 1);
2616         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2617                 &[nodes[0].node.get_our_node_id()], 100_000);
2618         get_announce_close_broadcast_events(&nodes, 1, 0);
2619
2620         check_added_monitors!(nodes[0], 1);
2621         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2622                 &[nodes[1].node.get_our_node_id()], 100_000);
2623
2624         // Check that the justice tx has sent the revoked output value to nodes[1]
2625         let monitor = get_monitor!(nodes[1], channel_id);
2626         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2627                 match balance {
2628                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2629                         _ => panic!("Unexpected balance type"),
2630                 }
2631         });
2632         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2633         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2634         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2635         assert_eq!(total_claimable_balance, expected_claimable_balance);
2636 }
2637
2638
2639 #[test]
2640 fn claim_htlc_outputs_shared_tx() {
2641         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2642         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2643         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2644         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2645         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2646         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2647
2648         // Create some new channel:
2649         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2650
2651         // Rebalance the network to generate htlc in the two directions
2652         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2653         // 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
2654         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2655         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2656
2657         // Get the will-be-revoked local txn from node[0]
2658         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2659         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2660         assert_eq!(revoked_local_txn[0].input.len(), 1);
2661         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2662         assert_eq!(revoked_local_txn[1].input.len(), 1);
2663         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2664         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2665         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2666
2667         //Revoke the old state
2668         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2669
2670         {
2671                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2672                 check_added_monitors!(nodes[0], 1);
2673                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2674                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2675                 check_added_monitors!(nodes[1], 1);
2676                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2677                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2678                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2679
2680                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2681                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2682
2683                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2684                 check_spends!(node_txn[0], revoked_local_txn[0]);
2685
2686                 let mut witness_lens = BTreeSet::new();
2687                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2688                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2689                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2690                 assert_eq!(witness_lens.len(), 3);
2691                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2692                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2693                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2694
2695                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2696                 // ANTI_REORG_DELAY confirmations.
2697                 mine_transaction(&nodes[1], &node_txn[0]);
2698                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2699                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2700         }
2701         get_announce_close_broadcast_events(&nodes, 0, 1);
2702         assert_eq!(nodes[0].node.list_channels().len(), 0);
2703         assert_eq!(nodes[1].node.list_channels().len(), 0);
2704 }
2705
2706 #[test]
2707 fn claim_htlc_outputs_single_tx() {
2708         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2709         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2710         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2711         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2712         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2713         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2714
2715         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2716
2717         // Rebalance the network to generate htlc in the two directions
2718         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2719         // 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
2720         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2721         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2722         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2723
2724         // Get the will-be-revoked local txn from node[0]
2725         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2726
2727         //Revoke the old state
2728         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2729
2730         {
2731                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2732                 check_added_monitors!(nodes[0], 1);
2733                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2734                 check_added_monitors!(nodes[1], 1);
2735                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2736                 let mut events = nodes[0].node.get_and_clear_pending_events();
2737                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2738                 match events.last().unwrap() {
2739                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2740                         _ => panic!("Unexpected event"),
2741                 }
2742
2743                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2744                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2745
2746                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2747
2748                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2749                 assert_eq!(node_txn[0].input.len(), 1);
2750                 check_spends!(node_txn[0], chan_1.3);
2751                 assert_eq!(node_txn[1].input.len(), 1);
2752                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2753                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2754                 check_spends!(node_txn[1], node_txn[0]);
2755
2756                 // Filter out any non justice transactions.
2757                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2758                 assert!(node_txn.len() > 3);
2759
2760                 assert_eq!(node_txn[0].input.len(), 1);
2761                 assert_eq!(node_txn[1].input.len(), 1);
2762                 assert_eq!(node_txn[2].input.len(), 1);
2763
2764                 check_spends!(node_txn[0], revoked_local_txn[0]);
2765                 check_spends!(node_txn[1], revoked_local_txn[0]);
2766                 check_spends!(node_txn[2], revoked_local_txn[0]);
2767
2768                 let mut witness_lens = BTreeSet::new();
2769                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2770                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2771                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2772                 assert_eq!(witness_lens.len(), 3);
2773                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2774                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2775                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2776
2777                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2778                 // ANTI_REORG_DELAY confirmations.
2779                 mine_transaction(&nodes[1], &node_txn[0]);
2780                 mine_transaction(&nodes[1], &node_txn[1]);
2781                 mine_transaction(&nodes[1], &node_txn[2]);
2782                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2783                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2784         }
2785         get_announce_close_broadcast_events(&nodes, 0, 1);
2786         assert_eq!(nodes[0].node.list_channels().len(), 0);
2787         assert_eq!(nodes[1].node.list_channels().len(), 0);
2788 }
2789
2790 #[test]
2791 fn test_htlc_on_chain_success() {
2792         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2793         // the preimage backward accordingly. So here we test that ChannelManager is
2794         // broadcasting the right event to other nodes in payment path.
2795         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2796         // A --------------------> B ----------------------> C (preimage)
2797         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2798         // commitment transaction was broadcast.
2799         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2800         // towards B.
2801         // B should be able to claim via preimage if A then broadcasts its local tx.
2802         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2803         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2804         // PaymentSent event).
2805
2806         let chanmon_cfgs = create_chanmon_cfgs(3);
2807         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2808         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2809         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2810
2811         // Create some initial channels
2812         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2813         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2814
2815         // Ensure all nodes are at the same height
2816         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2817         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2818         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2819         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2820
2821         // Rebalance the network a bit by relaying one payment through all the channels...
2822         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2823         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2824
2825         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2826         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2827
2828         // Broadcast legit commitment tx from C on B's chain
2829         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2830         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2831         assert_eq!(commitment_tx.len(), 1);
2832         check_spends!(commitment_tx[0], chan_2.3);
2833         nodes[2].node.claim_funds(our_payment_preimage);
2834         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2835         nodes[2].node.claim_funds(our_payment_preimage_2);
2836         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2837         check_added_monitors!(nodes[2], 2);
2838         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2839         assert!(updates.update_add_htlcs.is_empty());
2840         assert!(updates.update_fail_htlcs.is_empty());
2841         assert!(updates.update_fail_malformed_htlcs.is_empty());
2842         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2843
2844         mine_transaction(&nodes[2], &commitment_tx[0]);
2845         check_closed_broadcast!(nodes[2], true);
2846         check_added_monitors!(nodes[2], 1);
2847         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2848         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2849         assert_eq!(node_txn.len(), 2);
2850         check_spends!(node_txn[0], commitment_tx[0]);
2851         check_spends!(node_txn[1], commitment_tx[0]);
2852         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2853         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2855         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2856         assert_eq!(node_txn[0].lock_time.0, 0);
2857         assert_eq!(node_txn[1].lock_time.0, 0);
2858
2859         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2860         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()]));
2861         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2862         {
2863                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2864                 assert_eq!(added_monitors.len(), 1);
2865                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2866                 added_monitors.clear();
2867         }
2868         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2869         assert_eq!(forwarded_events.len(), 3);
2870         match forwarded_events[0] {
2871                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2872                 _ => panic!("Unexpected event"),
2873         }
2874         let chan_id = Some(chan_1.2);
2875         match forwarded_events[1] {
2876                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2877                         assert_eq!(fee_earned_msat, Some(1000));
2878                         assert_eq!(prev_channel_id, chan_id);
2879                         assert_eq!(claim_from_onchain_tx, true);
2880                         assert_eq!(next_channel_id, Some(chan_2.2));
2881                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2882                 },
2883                 _ => panic!()
2884         }
2885         match forwarded_events[2] {
2886                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2887                         assert_eq!(fee_earned_msat, Some(1000));
2888                         assert_eq!(prev_channel_id, chan_id);
2889                         assert_eq!(claim_from_onchain_tx, true);
2890                         assert_eq!(next_channel_id, Some(chan_2.2));
2891                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2892                 },
2893                 _ => panic!()
2894         }
2895         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2896         {
2897                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2898                 assert_eq!(added_monitors.len(), 2);
2899                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2900                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2901                 added_monitors.clear();
2902         }
2903         assert_eq!(events.len(), 3);
2904
2905         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2906         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2907
2908         match nodes_2_event {
2909                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2910                 _ => panic!("Unexpected event"),
2911         }
2912
2913         match nodes_0_event {
2914                 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, .. } } => {
2915                         assert!(update_add_htlcs.is_empty());
2916                         assert!(update_fail_htlcs.is_empty());
2917                         assert_eq!(update_fulfill_htlcs.len(), 1);
2918                         assert!(update_fail_malformed_htlcs.is_empty());
2919                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2920                 },
2921                 _ => panic!("Unexpected event"),
2922         };
2923
2924         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2925         match events[0] {
2926                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2927                 _ => panic!("Unexpected event"),
2928         }
2929
2930         macro_rules! check_tx_local_broadcast {
2931                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2932                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2933                         assert_eq!(node_txn.len(), 2);
2934                         // Node[1]: 2 * HTLC-timeout tx
2935                         // Node[0]: 2 * HTLC-timeout tx
2936                         check_spends!(node_txn[0], $commitment_tx);
2937                         check_spends!(node_txn[1], $commitment_tx);
2938                         assert_ne!(node_txn[0].lock_time.0, 0);
2939                         assert_ne!(node_txn[1].lock_time.0, 0);
2940                         if $htlc_offered {
2941                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2942                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2943                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2944                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2945                         } else {
2946                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2947                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2948                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2949                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2950                         }
2951                         node_txn.clear();
2952                 } }
2953         }
2954         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2955         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2956
2957         // Broadcast legit commitment tx from A on B's chain
2958         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2959         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2960         check_spends!(node_a_commitment_tx[0], chan_1.3);
2961         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2962         check_closed_broadcast!(nodes[1], true);
2963         check_added_monitors!(nodes[1], 1);
2964         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2965         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2966         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2967         let commitment_spend =
2968                 if node_txn.len() == 1 {
2969                         &node_txn[0]
2970                 } else {
2971                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2972                         // FullBlockViaListen
2973                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2974                                 check_spends!(node_txn[1], commitment_tx[0]);
2975                                 check_spends!(node_txn[2], commitment_tx[0]);
2976                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2977                                 &node_txn[0]
2978                         } else {
2979                                 check_spends!(node_txn[0], commitment_tx[0]);
2980                                 check_spends!(node_txn[1], commitment_tx[0]);
2981                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2982                                 &node_txn[2]
2983                         }
2984                 };
2985
2986         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2987         assert_eq!(commitment_spend.input.len(), 2);
2988         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2989         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2990         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2991         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2992         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2993         // we already checked the same situation with A.
2994
2995         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2996         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2997         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2998         check_closed_broadcast!(nodes[0], true);
2999         check_added_monitors!(nodes[0], 1);
3000         let events = nodes[0].node.get_and_clear_pending_events();
3001         assert_eq!(events.len(), 5);
3002         let mut first_claimed = false;
3003         for event in events {
3004                 match event {
3005                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3006                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3007                                         assert!(!first_claimed);
3008                                         first_claimed = true;
3009                                 } else {
3010                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3011                                         assert_eq!(payment_hash, payment_hash_2);
3012                                 }
3013                         },
3014                         Event::PaymentPathSuccessful { .. } => {},
3015                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3016                         _ => panic!("Unexpected event"),
3017                 }
3018         }
3019         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3020 }
3021
3022 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3023         // Test that in case of a unilateral close onchain, we detect the state of output and
3024         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3025         // broadcasting the right event to other nodes in payment path.
3026         // A ------------------> B ----------------------> C (timeout)
3027         //    B's commitment tx                 C's commitment tx
3028         //            \                                  \
3029         //         B's HTLC timeout tx               B's timeout tx
3030
3031         let chanmon_cfgs = create_chanmon_cfgs(3);
3032         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3033         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3034         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3035         *nodes[0].connect_style.borrow_mut() = connect_style;
3036         *nodes[1].connect_style.borrow_mut() = connect_style;
3037         *nodes[2].connect_style.borrow_mut() = connect_style;
3038
3039         // Create some intial channels
3040         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3041         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3042
3043         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3044         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3045         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3046
3047         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3048
3049         // Broadcast legit commitment tx from C on B's chain
3050         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3051         check_spends!(commitment_tx[0], chan_2.3);
3052         nodes[2].node.fail_htlc_backwards(&payment_hash);
3053         check_added_monitors!(nodes[2], 0);
3054         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3055         check_added_monitors!(nodes[2], 1);
3056
3057         let events = nodes[2].node.get_and_clear_pending_msg_events();
3058         assert_eq!(events.len(), 1);
3059         match events[0] {
3060                 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, .. } } => {
3061                         assert!(update_add_htlcs.is_empty());
3062                         assert!(!update_fail_htlcs.is_empty());
3063                         assert!(update_fulfill_htlcs.is_empty());
3064                         assert!(update_fail_malformed_htlcs.is_empty());
3065                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3066                 },
3067                 _ => panic!("Unexpected event"),
3068         };
3069         mine_transaction(&nodes[2], &commitment_tx[0]);
3070         check_closed_broadcast!(nodes[2], true);
3071         check_added_monitors!(nodes[2], 1);
3072         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3073         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3074         assert_eq!(node_txn.len(), 0);
3075
3076         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3077         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3078         mine_transaction(&nodes[1], &commitment_tx[0]);
3079         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3080                 , [nodes[2].node.get_our_node_id()], 100000);
3081         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3082         let timeout_tx = {
3083                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3084                 if nodes[1].connect_style.borrow().skips_blocks() {
3085                         assert_eq!(txn.len(), 1);
3086                 } else {
3087                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3088                 }
3089                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3090                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3091                 txn.remove(0)
3092         };
3093
3094         mine_transaction(&nodes[1], &timeout_tx);
3095         check_added_monitors!(nodes[1], 1);
3096         check_closed_broadcast!(nodes[1], true);
3097
3098         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3099
3100         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 }]);
3101         check_added_monitors!(nodes[1], 1);
3102         let events = nodes[1].node.get_and_clear_pending_msg_events();
3103         assert_eq!(events.len(), 1);
3104         match events[0] {
3105                 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, .. } } => {
3106                         assert!(update_add_htlcs.is_empty());
3107                         assert!(!update_fail_htlcs.is_empty());
3108                         assert!(update_fulfill_htlcs.is_empty());
3109                         assert!(update_fail_malformed_htlcs.is_empty());
3110                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3111                 },
3112                 _ => panic!("Unexpected event"),
3113         };
3114
3115         // Broadcast legit commitment tx from B on A's chain
3116         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3117         check_spends!(commitment_tx[0], chan_1.3);
3118
3119         mine_transaction(&nodes[0], &commitment_tx[0]);
3120         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3121
3122         check_closed_broadcast!(nodes[0], true);
3123         check_added_monitors!(nodes[0], 1);
3124         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3125         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3126         assert_eq!(node_txn.len(), 1);
3127         check_spends!(node_txn[0], commitment_tx[0]);
3128         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3129 }
3130
3131 #[test]
3132 fn test_htlc_on_chain_timeout() {
3133         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3134         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3135         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3136 }
3137
3138 #[test]
3139 fn test_simple_commitment_revoked_fail_backward() {
3140         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3141         // and fail backward accordingly.
3142
3143         let chanmon_cfgs = create_chanmon_cfgs(3);
3144         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3145         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3146         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3147
3148         // Create some initial channels
3149         create_announced_chan_between_nodes(&nodes, 0, 1);
3150         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3151
3152         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3153         // Get the will-be-revoked local txn from nodes[2]
3154         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3155         // Revoke the old state
3156         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3157
3158         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3159
3160         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3161         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3162         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3163         check_added_monitors!(nodes[1], 1);
3164         check_closed_broadcast!(nodes[1], true);
3165
3166         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 }]);
3167         check_added_monitors!(nodes[1], 1);
3168         let events = nodes[1].node.get_and_clear_pending_msg_events();
3169         assert_eq!(events.len(), 1);
3170         match events[0] {
3171                 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, .. } } => {
3172                         assert!(update_add_htlcs.is_empty());
3173                         assert_eq!(update_fail_htlcs.len(), 1);
3174                         assert!(update_fulfill_htlcs.is_empty());
3175                         assert!(update_fail_malformed_htlcs.is_empty());
3176                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3177
3178                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3179                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3180                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3181                 },
3182                 _ => panic!("Unexpected event"),
3183         }
3184 }
3185
3186 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3187         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3188         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3189         // commitment transaction anymore.
3190         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3191         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3192         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3193         // technically disallowed and we should probably handle it reasonably.
3194         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3195         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3196         // transactions:
3197         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3198         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3199         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3200         //   and once they revoke the previous commitment transaction (allowing us to send a new
3201         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3202         let chanmon_cfgs = create_chanmon_cfgs(3);
3203         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3204         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3205         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3206
3207         // Create some initial channels
3208         create_announced_chan_between_nodes(&nodes, 0, 1);
3209         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3210
3211         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3212         // Get the will-be-revoked local txn from nodes[2]
3213         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3214         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3215         // Revoke the old state
3216         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3217
3218         let value = if use_dust {
3219                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3220                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3221                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3222                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3223         } else { 3000000 };
3224
3225         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3226         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3227         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3228
3229         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3230         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3231         check_added_monitors!(nodes[2], 1);
3232         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3233         assert!(updates.update_add_htlcs.is_empty());
3234         assert!(updates.update_fulfill_htlcs.is_empty());
3235         assert!(updates.update_fail_malformed_htlcs.is_empty());
3236         assert_eq!(updates.update_fail_htlcs.len(), 1);
3237         assert!(updates.update_fee.is_none());
3238         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3239         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3240         // Drop the last RAA from 3 -> 2
3241
3242         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3243         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3244         check_added_monitors!(nodes[2], 1);
3245         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3246         assert!(updates.update_add_htlcs.is_empty());
3247         assert!(updates.update_fulfill_htlcs.is_empty());
3248         assert!(updates.update_fail_malformed_htlcs.is_empty());
3249         assert_eq!(updates.update_fail_htlcs.len(), 1);
3250         assert!(updates.update_fee.is_none());
3251         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3252         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3253         check_added_monitors!(nodes[1], 1);
3254         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3255         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3256         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3257         check_added_monitors!(nodes[2], 1);
3258
3259         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3260         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3261         check_added_monitors!(nodes[2], 1);
3262         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3263         assert!(updates.update_add_htlcs.is_empty());
3264         assert!(updates.update_fulfill_htlcs.is_empty());
3265         assert!(updates.update_fail_malformed_htlcs.is_empty());
3266         assert_eq!(updates.update_fail_htlcs.len(), 1);
3267         assert!(updates.update_fee.is_none());
3268         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3269         // At this point first_payment_hash has dropped out of the latest two commitment
3270         // transactions that nodes[1] is tracking...
3271         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3272         check_added_monitors!(nodes[1], 1);
3273         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3274         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3275         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3276         check_added_monitors!(nodes[2], 1);
3277
3278         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3279         // on nodes[2]'s RAA.
3280         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3281         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3282                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3283         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3284         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3285         check_added_monitors!(nodes[1], 0);
3286
3287         if deliver_bs_raa {
3288                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3289                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3290                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3291                 check_added_monitors!(nodes[1], 1);
3292                 let events = nodes[1].node.get_and_clear_pending_events();
3293                 assert_eq!(events.len(), 2);
3294                 match events[0] {
3295                         Event::PendingHTLCsForwardable { .. } => { },
3296                         _ => panic!("Unexpected event"),
3297                 };
3298                 match events[1] {
3299                         Event::HTLCHandlingFailed { .. } => { },
3300                         _ => panic!("Unexpected event"),
3301                 }
3302                 // Deliberately don't process the pending fail-back so they all fail back at once after
3303                 // block connection just like the !deliver_bs_raa case
3304         }
3305
3306         let mut failed_htlcs = HashSet::new();
3307         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3308
3309         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3310         check_added_monitors!(nodes[1], 1);
3311         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3312
3313         let events = nodes[1].node.get_and_clear_pending_events();
3314         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3315         match events[0] {
3316                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3317                 _ => panic!("Unexepected event"),
3318         }
3319         match events[1] {
3320                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3321                         assert_eq!(*payment_hash, fourth_payment_hash);
3322                 },
3323                 _ => panic!("Unexpected event"),
3324         }
3325         match events[2] {
3326                 Event::PaymentFailed { ref payment_hash, .. } => {
3327                         assert_eq!(*payment_hash, fourth_payment_hash);
3328                 },
3329                 _ => panic!("Unexpected event"),
3330         }
3331
3332         nodes[1].node.process_pending_htlc_forwards();
3333         check_added_monitors!(nodes[1], 1);
3334
3335         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3336         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3337
3338         if deliver_bs_raa {
3339                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3340                 match nodes_2_event {
3341                         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, .. } } => {
3342                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3343                                 assert_eq!(update_add_htlcs.len(), 1);
3344                                 assert!(update_fulfill_htlcs.is_empty());
3345                                 assert!(update_fail_htlcs.is_empty());
3346                                 assert!(update_fail_malformed_htlcs.is_empty());
3347                         },
3348                         _ => panic!("Unexpected event"),
3349                 }
3350         }
3351
3352         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3353         match nodes_2_event {
3354                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3355                         assert_eq!(channel_id, chan_2.2);
3356                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3357                 },
3358                 _ => panic!("Unexpected event"),
3359         }
3360
3361         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3362         match nodes_0_event {
3363                 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, .. } } => {
3364                         assert!(update_add_htlcs.is_empty());
3365                         assert_eq!(update_fail_htlcs.len(), 3);
3366                         assert!(update_fulfill_htlcs.is_empty());
3367                         assert!(update_fail_malformed_htlcs.is_empty());
3368                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3369
3370                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3371                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3372                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3373
3374                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3375
3376                         let events = nodes[0].node.get_and_clear_pending_events();
3377                         assert_eq!(events.len(), 6);
3378                         match events[0] {
3379                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3380                                         assert!(failed_htlcs.insert(payment_hash.0));
3381                                         // If we delivered B's RAA we got an unknown preimage error, not something
3382                                         // that we should update our routing table for.
3383                                         if !deliver_bs_raa {
3384                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3385                                         }
3386                                 },
3387                                 _ => panic!("Unexpected event"),
3388                         }
3389                         match events[1] {
3390                                 Event::PaymentFailed { ref payment_hash, .. } => {
3391                                         assert_eq!(*payment_hash, first_payment_hash);
3392                                 },
3393                                 _ => panic!("Unexpected event"),
3394                         }
3395                         match events[2] {
3396                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3397                                         assert!(failed_htlcs.insert(payment_hash.0));
3398                                 },
3399                                 _ => panic!("Unexpected event"),
3400                         }
3401                         match events[3] {
3402                                 Event::PaymentFailed { ref payment_hash, .. } => {
3403                                         assert_eq!(*payment_hash, second_payment_hash);
3404                                 },
3405                                 _ => panic!("Unexpected event"),
3406                         }
3407                         match events[4] {
3408                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3409                                         assert!(failed_htlcs.insert(payment_hash.0));
3410                                 },
3411                                 _ => panic!("Unexpected event"),
3412                         }
3413                         match events[5] {
3414                                 Event::PaymentFailed { ref payment_hash, .. } => {
3415                                         assert_eq!(*payment_hash, third_payment_hash);
3416                                 },
3417                                 _ => panic!("Unexpected event"),
3418                         }
3419                 },
3420                 _ => panic!("Unexpected event"),
3421         }
3422
3423         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3424         match events[0] {
3425                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3426                 _ => panic!("Unexpected event"),
3427         }
3428
3429         assert!(failed_htlcs.contains(&first_payment_hash.0));
3430         assert!(failed_htlcs.contains(&second_payment_hash.0));
3431         assert!(failed_htlcs.contains(&third_payment_hash.0));
3432 }
3433
3434 #[test]
3435 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3436         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3437         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3438         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3439         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3440 }
3441
3442 #[test]
3443 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3444         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3445         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3446         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3447         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3448 }
3449
3450 #[test]
3451 fn fail_backward_pending_htlc_upon_channel_failure() {
3452         let chanmon_cfgs = create_chanmon_cfgs(2);
3453         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3454         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3455         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3456         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3457
3458         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3459         {
3460                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3461                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3462                         PaymentId(payment_hash.0)).unwrap();
3463                 check_added_monitors!(nodes[0], 1);
3464
3465                 let payment_event = {
3466                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3467                         assert_eq!(events.len(), 1);
3468                         SendEvent::from_event(events.remove(0))
3469                 };
3470                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3471                 assert_eq!(payment_event.msgs.len(), 1);
3472         }
3473
3474         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3475         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3476         {
3477                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3478                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3479                 check_added_monitors!(nodes[0], 0);
3480
3481                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3482         }
3483
3484         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3485         {
3486                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3487
3488                 let secp_ctx = Secp256k1::new();
3489                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3490                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3491                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3492                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3493                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3494                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3495
3496                 // Send a 0-msat update_add_htlc to fail the channel.
3497                 let update_add_htlc = msgs::UpdateAddHTLC {
3498                         channel_id: chan.2,
3499                         htlc_id: 0,
3500                         amount_msat: 0,
3501                         payment_hash,
3502                         cltv_expiry,
3503                         onion_routing_packet,
3504                         skimmed_fee_msat: None,
3505                 };
3506                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3507         }
3508         let events = nodes[0].node.get_and_clear_pending_events();
3509         assert_eq!(events.len(), 3);
3510         // Check that Alice fails backward the pending HTLC from the second payment.
3511         match events[0] {
3512                 Event::PaymentPathFailed { payment_hash, .. } => {
3513                         assert_eq!(payment_hash, failed_payment_hash);
3514                 },
3515                 _ => panic!("Unexpected event"),
3516         }
3517         match events[1] {
3518                 Event::PaymentFailed { payment_hash, .. } => {
3519                         assert_eq!(payment_hash, failed_payment_hash);
3520                 },
3521                 _ => panic!("Unexpected event"),
3522         }
3523         match events[2] {
3524                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3525                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3526                 },
3527                 _ => panic!("Unexpected event {:?}", events[1]),
3528         }
3529         check_closed_broadcast!(nodes[0], true);
3530         check_added_monitors!(nodes[0], 1);
3531 }
3532
3533 #[test]
3534 fn test_htlc_ignore_latest_remote_commitment() {
3535         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3536         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3537         let chanmon_cfgs = create_chanmon_cfgs(2);
3538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3540         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3541         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3542                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3543                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3544                 // connect_style.
3545                 return;
3546         }
3547         create_announced_chan_between_nodes(&nodes, 0, 1);
3548
3549         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3550         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3551         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3552         check_closed_broadcast!(nodes[0], true);
3553         check_added_monitors!(nodes[0], 1);
3554         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3555
3556         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3557         assert_eq!(node_txn.len(), 3);
3558         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3559
3560         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3561         connect_block(&nodes[1], &block);
3562         check_closed_broadcast!(nodes[1], true);
3563         check_added_monitors!(nodes[1], 1);
3564         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3565
3566         // Duplicate the connect_block call since this may happen due to other listeners
3567         // registering new transactions
3568         connect_block(&nodes[1], &block);
3569 }
3570
3571 #[test]
3572 fn test_force_close_fail_back() {
3573         // Check which HTLCs are failed-backwards on channel force-closure
3574         let chanmon_cfgs = create_chanmon_cfgs(3);
3575         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3576         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3577         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3578         create_announced_chan_between_nodes(&nodes, 0, 1);
3579         create_announced_chan_between_nodes(&nodes, 1, 2);
3580
3581         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3582
3583         let mut payment_event = {
3584                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3585                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3586                 check_added_monitors!(nodes[0], 1);
3587
3588                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3589                 assert_eq!(events.len(), 1);
3590                 SendEvent::from_event(events.remove(0))
3591         };
3592
3593         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3594         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3595
3596         expect_pending_htlcs_forwardable!(nodes[1]);
3597
3598         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3599         assert_eq!(events_2.len(), 1);
3600         payment_event = SendEvent::from_event(events_2.remove(0));
3601         assert_eq!(payment_event.msgs.len(), 1);
3602
3603         check_added_monitors!(nodes[1], 1);
3604         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3605         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3606         check_added_monitors!(nodes[2], 1);
3607         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3608
3609         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3610         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3611         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3612
3613         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3614         check_closed_broadcast!(nodes[2], true);
3615         check_added_monitors!(nodes[2], 1);
3616         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3617         let tx = {
3618                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3619                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3620                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3621                 // back to nodes[1] upon timeout otherwise.
3622                 assert_eq!(node_txn.len(), 1);
3623                 node_txn.remove(0)
3624         };
3625
3626         mine_transaction(&nodes[1], &tx);
3627
3628         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3629         check_closed_broadcast!(nodes[1], true);
3630         check_added_monitors!(nodes[1], 1);
3631         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3632
3633         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3634         {
3635                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3636                         .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);
3637         }
3638         mine_transaction(&nodes[2], &tx);
3639         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3640         assert_eq!(node_txn.len(), 1);
3641         assert_eq!(node_txn[0].input.len(), 1);
3642         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3643         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3644         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3645
3646         check_spends!(node_txn[0], tx);
3647 }
3648
3649 #[test]
3650 fn test_dup_events_on_peer_disconnect() {
3651         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3652         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3653         // as we used to generate the event immediately upon receipt of the payment preimage in the
3654         // update_fulfill_htlc message.
3655
3656         let chanmon_cfgs = create_chanmon_cfgs(2);
3657         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3658         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3659         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3660         create_announced_chan_between_nodes(&nodes, 0, 1);
3661
3662         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3663
3664         nodes[1].node.claim_funds(payment_preimage);
3665         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3666         check_added_monitors!(nodes[1], 1);
3667         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3668         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3669         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3670
3671         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3672         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3673
3674         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3675         reconnect_args.pending_htlc_claims.0 = 1;
3676         reconnect_nodes(reconnect_args);
3677         expect_payment_path_successful!(nodes[0]);
3678 }
3679
3680 #[test]
3681 fn test_peer_disconnected_before_funding_broadcasted() {
3682         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3683         // before the funding transaction has been broadcasted.
3684         let chanmon_cfgs = create_chanmon_cfgs(2);
3685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3687         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3688
3689         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3690         // broadcasted, even though it's created by `nodes[0]`.
3691         let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3692         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3693         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3694         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3695         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3696
3697         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3698         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3699
3700         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3701
3702         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3703         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3704
3705         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3706         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3707         // broadcasted.
3708         {
3709                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3710         }
3711
3712         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3713         // disconnected before the funding transaction was broadcasted.
3714         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3715         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3716
3717         check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3718                 , [nodes[1].node.get_our_node_id()], 1000000);
3719         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3720                 , [nodes[0].node.get_our_node_id()], 1000000);
3721 }
3722
3723 #[test]
3724 fn test_simple_peer_disconnect() {
3725         // Test that we can reconnect when there are no lost messages
3726         let chanmon_cfgs = create_chanmon_cfgs(3);
3727         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3728         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3729         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3730         create_announced_chan_between_nodes(&nodes, 0, 1);
3731         create_announced_chan_between_nodes(&nodes, 1, 2);
3732
3733         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3734         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3735         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3736         reconnect_args.send_channel_ready = (true, true);
3737         reconnect_nodes(reconnect_args);
3738
3739         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3740         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3741         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3742         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3743
3744         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3745         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3746         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3747
3748         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3749         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3750         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3751         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3752
3753         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3754         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3755
3756         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3757         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3758
3759         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3760         reconnect_args.pending_cell_htlc_fails.0 = 1;
3761         reconnect_args.pending_cell_htlc_claims.0 = 1;
3762         reconnect_nodes(reconnect_args);
3763         {
3764                 let events = nodes[0].node.get_and_clear_pending_events();
3765                 assert_eq!(events.len(), 4);
3766                 match events[0] {
3767                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3768                                 assert_eq!(payment_preimage, payment_preimage_3);
3769                                 assert_eq!(payment_hash, payment_hash_3);
3770                         },
3771                         _ => panic!("Unexpected event"),
3772                 }
3773                 match events[1] {
3774                         Event::PaymentPathSuccessful { .. } => {},
3775                         _ => panic!("Unexpected event"),
3776                 }
3777                 match events[2] {
3778                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3779                                 assert_eq!(payment_hash, payment_hash_5);
3780                                 assert!(payment_failed_permanently);
3781                         },
3782                         _ => panic!("Unexpected event"),
3783                 }
3784                 match events[3] {
3785                         Event::PaymentFailed { payment_hash, .. } => {
3786                                 assert_eq!(payment_hash, payment_hash_5);
3787                         },
3788                         _ => panic!("Unexpected event"),
3789                 }
3790         }
3791         check_added_monitors(&nodes[0], 1);
3792
3793         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3794         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3795 }
3796
3797 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3798         // Test that we can reconnect when in-flight HTLC updates get dropped
3799         let chanmon_cfgs = create_chanmon_cfgs(2);
3800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3802         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3803
3804         let mut as_channel_ready = None;
3805         let channel_id = if messages_delivered == 0 {
3806                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3807                 as_channel_ready = Some(channel_ready);
3808                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3809                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3810                 // it before the channel_reestablish message.
3811                 chan_id
3812         } else {
3813                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3814         };
3815
3816         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3817
3818         let payment_event = {
3819                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3820                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3821                 check_added_monitors!(nodes[0], 1);
3822
3823                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3824                 assert_eq!(events.len(), 1);
3825                 SendEvent::from_event(events.remove(0))
3826         };
3827         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3828
3829         if messages_delivered < 2 {
3830                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3831         } else {
3832                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3833                 if messages_delivered >= 3 {
3834                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3835                         check_added_monitors!(nodes[1], 1);
3836                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3837
3838                         if messages_delivered >= 4 {
3839                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3840                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3841                                 check_added_monitors!(nodes[0], 1);
3842
3843                                 if messages_delivered >= 5 {
3844                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3845                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3846                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3847                                         check_added_monitors!(nodes[0], 1);
3848
3849                                         if messages_delivered >= 6 {
3850                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3851                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3852                                                 check_added_monitors!(nodes[1], 1);
3853                                         }
3854                                 }
3855                         }
3856                 }
3857         }
3858
3859         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3860         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3861         if messages_delivered < 3 {
3862                 if simulate_broken_lnd {
3863                         // lnd has a long-standing bug where they send a channel_ready prior to a
3864                         // channel_reestablish if you reconnect prior to channel_ready time.
3865                         //
3866                         // Here we simulate that behavior, delivering a channel_ready immediately on
3867                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3868                         // in `reconnect_nodes` but we currently don't fail based on that.
3869                         //
3870                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3871                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3872                 }
3873                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3874                 // received on either side, both sides will need to resend them.
3875                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3876                 reconnect_args.send_channel_ready = (true, true);
3877                 reconnect_args.pending_htlc_adds.1 = 1;
3878                 reconnect_nodes(reconnect_args);
3879         } else if messages_delivered == 3 {
3880                 // nodes[0] still wants its RAA + commitment_signed
3881                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3882                 reconnect_args.pending_htlc_adds.0 = -1;
3883                 reconnect_args.pending_raa.0 = true;
3884                 reconnect_nodes(reconnect_args);
3885         } else if messages_delivered == 4 {
3886                 // nodes[0] still wants its commitment_signed
3887                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3888                 reconnect_args.pending_htlc_adds.0 = -1;
3889                 reconnect_nodes(reconnect_args);
3890         } else if messages_delivered == 5 {
3891                 // nodes[1] still wants its final RAA
3892                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3893                 reconnect_args.pending_raa.1 = true;
3894                 reconnect_nodes(reconnect_args);
3895         } else if messages_delivered == 6 {
3896                 // Everything was delivered...
3897                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3898         }
3899
3900         let events_1 = nodes[1].node.get_and_clear_pending_events();
3901         if messages_delivered == 0 {
3902                 assert_eq!(events_1.len(), 2);
3903                 match events_1[0] {
3904                         Event::ChannelReady { .. } => { },
3905                         _ => panic!("Unexpected event"),
3906                 };
3907                 match events_1[1] {
3908                         Event::PendingHTLCsForwardable { .. } => { },
3909                         _ => panic!("Unexpected event"),
3910                 };
3911         } else {
3912                 assert_eq!(events_1.len(), 1);
3913                 match events_1[0] {
3914                         Event::PendingHTLCsForwardable { .. } => { },
3915                         _ => panic!("Unexpected event"),
3916                 };
3917         }
3918
3919         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3920         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3921         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3922
3923         nodes[1].node.process_pending_htlc_forwards();
3924
3925         let events_2 = nodes[1].node.get_and_clear_pending_events();
3926         assert_eq!(events_2.len(), 1);
3927         match events_2[0] {
3928                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3929                         assert_eq!(payment_hash_1, *payment_hash);
3930                         assert_eq!(amount_msat, 1_000_000);
3931                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3932                         assert_eq!(via_channel_id, Some(channel_id));
3933                         match &purpose {
3934                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3935                                         assert!(payment_preimage.is_none());
3936                                         assert_eq!(payment_secret_1, *payment_secret);
3937                                 },
3938                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3939                         }
3940                 },
3941                 _ => panic!("Unexpected event"),
3942         }
3943
3944         nodes[1].node.claim_funds(payment_preimage_1);
3945         check_added_monitors!(nodes[1], 1);
3946         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3947
3948         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3949         assert_eq!(events_3.len(), 1);
3950         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3951                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3952                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3953                         assert!(updates.update_add_htlcs.is_empty());
3954                         assert!(updates.update_fail_htlcs.is_empty());
3955                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3956                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3957                         assert!(updates.update_fee.is_none());
3958                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3959                 },
3960                 _ => panic!("Unexpected event"),
3961         };
3962
3963         if messages_delivered >= 1 {
3964                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3965
3966                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3967                 assert_eq!(events_4.len(), 1);
3968                 match events_4[0] {
3969                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3970                                 assert_eq!(payment_preimage_1, *payment_preimage);
3971                                 assert_eq!(payment_hash_1, *payment_hash);
3972                         },
3973                         _ => panic!("Unexpected event"),
3974                 }
3975
3976                 if messages_delivered >= 2 {
3977                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3978                         check_added_monitors!(nodes[0], 1);
3979                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3980
3981                         if messages_delivered >= 3 {
3982                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3983                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3984                                 check_added_monitors!(nodes[1], 1);
3985
3986                                 if messages_delivered >= 4 {
3987                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3988                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3989                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3990                                         check_added_monitors!(nodes[1], 1);
3991
3992                                         if messages_delivered >= 5 {
3993                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3994                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3995                                                 check_added_monitors!(nodes[0], 1);
3996                                         }
3997                                 }
3998                         }
3999                 }
4000         }
4001
4002         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4003         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4004         if messages_delivered < 2 {
4005                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4006                 reconnect_args.pending_htlc_claims.0 = 1;
4007                 reconnect_nodes(reconnect_args);
4008                 if messages_delivered < 1 {
4009                         expect_payment_sent!(nodes[0], payment_preimage_1);
4010                 } else {
4011                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4012                 }
4013         } else if messages_delivered == 2 {
4014                 // nodes[0] still wants its RAA + commitment_signed
4015                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4016                 reconnect_args.pending_htlc_adds.1 = -1;
4017                 reconnect_args.pending_raa.1 = true;
4018                 reconnect_nodes(reconnect_args);
4019         } else if messages_delivered == 3 {
4020                 // nodes[0] still wants its commitment_signed
4021                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4022                 reconnect_args.pending_htlc_adds.1 = -1;
4023                 reconnect_nodes(reconnect_args);
4024         } else if messages_delivered == 4 {
4025                 // nodes[1] still wants its final RAA
4026                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4027                 reconnect_args.pending_raa.0 = true;
4028                 reconnect_nodes(reconnect_args);
4029         } else if messages_delivered == 5 {
4030                 // Everything was delivered...
4031                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4032         }
4033
4034         if messages_delivered == 1 || messages_delivered == 2 {
4035                 expect_payment_path_successful!(nodes[0]);
4036         }
4037         if messages_delivered <= 5 {
4038                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4039                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4040         }
4041         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4042
4043         if messages_delivered > 2 {
4044                 expect_payment_path_successful!(nodes[0]);
4045         }
4046
4047         // Channel should still work fine...
4048         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4049         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4050         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4051 }
4052
4053 #[test]
4054 fn test_drop_messages_peer_disconnect_a() {
4055         do_test_drop_messages_peer_disconnect(0, true);
4056         do_test_drop_messages_peer_disconnect(0, false);
4057         do_test_drop_messages_peer_disconnect(1, false);
4058         do_test_drop_messages_peer_disconnect(2, false);
4059 }
4060
4061 #[test]
4062 fn test_drop_messages_peer_disconnect_b() {
4063         do_test_drop_messages_peer_disconnect(3, false);
4064         do_test_drop_messages_peer_disconnect(4, false);
4065         do_test_drop_messages_peer_disconnect(5, false);
4066         do_test_drop_messages_peer_disconnect(6, false);
4067 }
4068
4069 #[test]
4070 fn test_channel_ready_without_best_block_updated() {
4071         // Previously, if we were offline when a funding transaction was locked in, and then we came
4072         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4073         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4074         // channel_ready immediately instead.
4075         let chanmon_cfgs = create_chanmon_cfgs(2);
4076         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4077         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4078         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4079         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4080
4081         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4082
4083         let conf_height = nodes[0].best_block_info().1 + 1;
4084         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4085         let block_txn = [funding_tx];
4086         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4087         let conf_block_header = nodes[0].get_block_header(conf_height);
4088         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4089
4090         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4091         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4092         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4093 }
4094
4095 #[test]
4096 fn test_drop_messages_peer_disconnect_dual_htlc() {
4097         // Test that we can handle reconnecting when both sides of a channel have pending
4098         // commitment_updates when we disconnect.
4099         let chanmon_cfgs = create_chanmon_cfgs(2);
4100         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4101         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4102         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4103         create_announced_chan_between_nodes(&nodes, 0, 1);
4104
4105         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4106
4107         // Now try to send a second payment which will fail to send
4108         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4109         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4110                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4111         check_added_monitors!(nodes[0], 1);
4112
4113         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4114         assert_eq!(events_1.len(), 1);
4115         match events_1[0] {
4116                 MessageSendEvent::UpdateHTLCs { .. } => {},
4117                 _ => panic!("Unexpected event"),
4118         }
4119
4120         nodes[1].node.claim_funds(payment_preimage_1);
4121         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4122         check_added_monitors!(nodes[1], 1);
4123
4124         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4125         assert_eq!(events_2.len(), 1);
4126         match events_2[0] {
4127                 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 } } => {
4128                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4129                         assert!(update_add_htlcs.is_empty());
4130                         assert_eq!(update_fulfill_htlcs.len(), 1);
4131                         assert!(update_fail_htlcs.is_empty());
4132                         assert!(update_fail_malformed_htlcs.is_empty());
4133                         assert!(update_fee.is_none());
4134
4135                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4136                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4137                         assert_eq!(events_3.len(), 1);
4138                         match events_3[0] {
4139                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4140                                         assert_eq!(*payment_preimage, payment_preimage_1);
4141                                         assert_eq!(*payment_hash, payment_hash_1);
4142                                 },
4143                                 _ => panic!("Unexpected event"),
4144                         }
4145
4146                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4147                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4148                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4149                         check_added_monitors!(nodes[0], 1);
4150                 },
4151                 _ => panic!("Unexpected event"),
4152         }
4153
4154         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4155         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4156
4157         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4158                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4159         }, true).unwrap();
4160         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4161         assert_eq!(reestablish_1.len(), 1);
4162         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4163                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4164         }, false).unwrap();
4165         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4166         assert_eq!(reestablish_2.len(), 1);
4167
4168         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4169         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4170         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4171         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4172
4173         assert!(as_resp.0.is_none());
4174         assert!(bs_resp.0.is_none());
4175
4176         assert!(bs_resp.1.is_none());
4177         assert!(bs_resp.2.is_none());
4178
4179         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4180
4181         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4182         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4183         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4184         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4185         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4186         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4187         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4188         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4189         // No commitment_signed so get_event_msg's assert(len == 1) passes
4190         check_added_monitors!(nodes[1], 1);
4191
4192         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4193         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4194         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4195         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4196         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4197         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4198         assert!(bs_second_commitment_signed.update_fee.is_none());
4199         check_added_monitors!(nodes[1], 1);
4200
4201         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4202         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4203         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4204         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4205         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4206         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4207         assert!(as_commitment_signed.update_fee.is_none());
4208         check_added_monitors!(nodes[0], 1);
4209
4210         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4211         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4212         // No commitment_signed so get_event_msg's assert(len == 1) passes
4213         check_added_monitors!(nodes[0], 1);
4214
4215         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4216         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4217         // No commitment_signed so get_event_msg's assert(len == 1) passes
4218         check_added_monitors!(nodes[1], 1);
4219
4220         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4221         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4222         check_added_monitors!(nodes[1], 1);
4223
4224         expect_pending_htlcs_forwardable!(nodes[1]);
4225
4226         let events_5 = nodes[1].node.get_and_clear_pending_events();
4227         assert_eq!(events_5.len(), 1);
4228         match events_5[0] {
4229                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4230                         assert_eq!(payment_hash_2, *payment_hash);
4231                         match &purpose {
4232                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4233                                         assert!(payment_preimage.is_none());
4234                                         assert_eq!(payment_secret_2, *payment_secret);
4235                                 },
4236                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4237                         }
4238                 },
4239                 _ => panic!("Unexpected event"),
4240         }
4241
4242         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4243         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4244         check_added_monitors!(nodes[0], 1);
4245
4246         expect_payment_path_successful!(nodes[0]);
4247         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4248 }
4249
4250 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4251         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4252         // to avoid our counterparty failing the channel.
4253         let chanmon_cfgs = create_chanmon_cfgs(2);
4254         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4256         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4257
4258         create_announced_chan_between_nodes(&nodes, 0, 1);
4259
4260         let our_payment_hash = if send_partial_mpp {
4261                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4262                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4263                 // indicates there are more HTLCs coming.
4264                 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.
4265                 let payment_id = PaymentId([42; 32]);
4266                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4267                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4268                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4269                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4270                         &None, session_privs[0]).unwrap();
4271                 check_added_monitors!(nodes[0], 1);
4272                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4273                 assert_eq!(events.len(), 1);
4274                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4275                 // hop should *not* yet generate any PaymentClaimable event(s).
4276                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4277                 our_payment_hash
4278         } else {
4279                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4280         };
4281
4282         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4283         connect_block(&nodes[0], &block);
4284         connect_block(&nodes[1], &block);
4285         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4286         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4287                 block.header.prev_blockhash = block.block_hash();
4288                 connect_block(&nodes[0], &block);
4289                 connect_block(&nodes[1], &block);
4290         }
4291
4292         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4293
4294         check_added_monitors!(nodes[1], 1);
4295         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4296         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4297         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4298         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4299         assert!(htlc_timeout_updates.update_fee.is_none());
4300
4301         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4302         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4303         // 100_000 msat as u64, followed by the height at which we failed back above
4304         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4305         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4306         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4307 }
4308
4309 #[test]
4310 fn test_htlc_timeout() {
4311         do_test_htlc_timeout(true);
4312         do_test_htlc_timeout(false);
4313 }
4314
4315 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4316         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4317         let chanmon_cfgs = create_chanmon_cfgs(3);
4318         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4319         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4320         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4321         create_announced_chan_between_nodes(&nodes, 0, 1);
4322         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4323
4324         // Make sure all nodes are at the same starting height
4325         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4326         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4327         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4328
4329         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4330         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4331         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4332                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4333         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4334         check_added_monitors!(nodes[1], 1);
4335
4336         // Now attempt to route a second payment, which should be placed in the holding cell
4337         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4338         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4339         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4340                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4341         if forwarded_htlc {
4342                 check_added_monitors!(nodes[0], 1);
4343                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4344                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4345                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4346                 expect_pending_htlcs_forwardable!(nodes[1]);
4347         }
4348         check_added_monitors!(nodes[1], 0);
4349
4350         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4351         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4352         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4353         connect_blocks(&nodes[1], 1);
4354
4355         if forwarded_htlc {
4356                 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 }]);
4357                 check_added_monitors!(nodes[1], 1);
4358                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4359                 assert_eq!(fail_commit.len(), 1);
4360                 match fail_commit[0] {
4361                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4362                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4363                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4364                         },
4365                         _ => unreachable!(),
4366                 }
4367                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4368         } else {
4369                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4370         }
4371 }
4372
4373 #[test]
4374 fn test_holding_cell_htlc_add_timeouts() {
4375         do_test_holding_cell_htlc_add_timeouts(false);
4376         do_test_holding_cell_htlc_add_timeouts(true);
4377 }
4378
4379 macro_rules! check_spendable_outputs {
4380         ($node: expr, $keysinterface: expr) => {
4381                 {
4382                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4383                         let mut txn = Vec::new();
4384                         let mut all_outputs = Vec::new();
4385                         let secp_ctx = Secp256k1::new();
4386                         for event in events.drain(..) {
4387                                 match event {
4388                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4389                                                 for outp in outputs.drain(..) {
4390                                                         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());
4391                                                         all_outputs.push(outp);
4392                                                 }
4393                                         },
4394                                         _ => panic!("Unexpected event"),
4395                                 };
4396                         }
4397                         if all_outputs.len() > 1 {
4398                                 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) {
4399                                         txn.push(tx);
4400                                 }
4401                         }
4402                         txn
4403                 }
4404         }
4405 }
4406
4407 #[test]
4408 fn test_claim_sizeable_push_msat() {
4409         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4410         let chanmon_cfgs = create_chanmon_cfgs(2);
4411         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4412         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4413         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4414
4415         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4416         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4417         check_closed_broadcast!(nodes[1], true);
4418         check_added_monitors!(nodes[1], 1);
4419         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4420         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4421         assert_eq!(node_txn.len(), 1);
4422         check_spends!(node_txn[0], chan.3);
4423         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
4424
4425         mine_transaction(&nodes[1], &node_txn[0]);
4426         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4427
4428         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4429         assert_eq!(spend_txn.len(), 1);
4430         assert_eq!(spend_txn[0].input.len(), 1);
4431         check_spends!(spend_txn[0], node_txn[0]);
4432         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4433 }
4434
4435 #[test]
4436 fn test_claim_on_remote_sizeable_push_msat() {
4437         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4438         // to_remote output is encumbered by a P2WPKH
4439         let chanmon_cfgs = create_chanmon_cfgs(2);
4440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4442         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4443
4444         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4445         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4446         check_closed_broadcast!(nodes[0], true);
4447         check_added_monitors!(nodes[0], 1);
4448         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4449
4450         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4451         assert_eq!(node_txn.len(), 1);
4452         check_spends!(node_txn[0], chan.3);
4453         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
4454
4455         mine_transaction(&nodes[1], &node_txn[0]);
4456         check_closed_broadcast!(nodes[1], true);
4457         check_added_monitors!(nodes[1], 1);
4458         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4459         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4460
4461         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4462         assert_eq!(spend_txn.len(), 1);
4463         check_spends!(spend_txn[0], node_txn[0]);
4464 }
4465
4466 #[test]
4467 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4468         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4469         // to_remote output is encumbered by a P2WPKH
4470
4471         let chanmon_cfgs = create_chanmon_cfgs(2);
4472         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4473         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4474         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4475
4476         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4477         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4478         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4479         assert_eq!(revoked_local_txn[0].input.len(), 1);
4480         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4481
4482         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4483         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4484         check_closed_broadcast!(nodes[1], true);
4485         check_added_monitors!(nodes[1], 1);
4486         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4487
4488         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4489         mine_transaction(&nodes[1], &node_txn[0]);
4490         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4491
4492         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4493         assert_eq!(spend_txn.len(), 3);
4494         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4495         check_spends!(spend_txn[1], node_txn[0]);
4496         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4497 }
4498
4499 #[test]
4500 fn test_static_spendable_outputs_preimage_tx() {
4501         let chanmon_cfgs = create_chanmon_cfgs(2);
4502         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4503         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4504         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4505
4506         // Create some initial channels
4507         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4508
4509         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4510
4511         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4512         assert_eq!(commitment_tx[0].input.len(), 1);
4513         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4514
4515         // Settle A's commitment tx on B's chain
4516         nodes[1].node.claim_funds(payment_preimage);
4517         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4518         check_added_monitors!(nodes[1], 1);
4519         mine_transaction(&nodes[1], &commitment_tx[0]);
4520         check_added_monitors!(nodes[1], 1);
4521         let events = nodes[1].node.get_and_clear_pending_msg_events();
4522         match events[0] {
4523                 MessageSendEvent::UpdateHTLCs { .. } => {},
4524                 _ => panic!("Unexpected event"),
4525         }
4526         match events[1] {
4527                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4528                 _ => panic!("Unexepected event"),
4529         }
4530
4531         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4532         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4533         assert_eq!(node_txn.len(), 1);
4534         check_spends!(node_txn[0], commitment_tx[0]);
4535         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4536
4537         mine_transaction(&nodes[1], &node_txn[0]);
4538         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4539         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4540
4541         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4542         assert_eq!(spend_txn.len(), 1);
4543         check_spends!(spend_txn[0], node_txn[0]);
4544 }
4545
4546 #[test]
4547 fn test_static_spendable_outputs_timeout_tx() {
4548         let chanmon_cfgs = create_chanmon_cfgs(2);
4549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4551         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4552
4553         // Create some initial channels
4554         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4555
4556         // Rebalance the network a bit by relaying one payment through all the channels ...
4557         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4558
4559         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4560
4561         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4562         assert_eq!(commitment_tx[0].input.len(), 1);
4563         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4564
4565         // Settle A's commitment tx on B' chain
4566         mine_transaction(&nodes[1], &commitment_tx[0]);
4567         check_added_monitors!(nodes[1], 1);
4568         let events = nodes[1].node.get_and_clear_pending_msg_events();
4569         match events[0] {
4570                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4571                 _ => panic!("Unexpected event"),
4572         }
4573         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4574
4575         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4576         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4577         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4578         check_spends!(node_txn[0],  commitment_tx[0].clone());
4579         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4580
4581         mine_transaction(&nodes[1], &node_txn[0]);
4582         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4583         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4584         expect_payment_failed!(nodes[1], our_payment_hash, false);
4585
4586         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4587         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4588         check_spends!(spend_txn[0], commitment_tx[0]);
4589         check_spends!(spend_txn[1], node_txn[0]);
4590         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4591 }
4592
4593 #[test]
4594 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4595         let chanmon_cfgs = create_chanmon_cfgs(2);
4596         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4597         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4598         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4599
4600         // Create some initial channels
4601         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4602
4603         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4604         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4605         assert_eq!(revoked_local_txn[0].input.len(), 1);
4606         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4607
4608         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4609
4610         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4611         check_closed_broadcast!(nodes[1], true);
4612         check_added_monitors!(nodes[1], 1);
4613         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4614
4615         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4616         assert_eq!(node_txn.len(), 1);
4617         assert_eq!(node_txn[0].input.len(), 2);
4618         check_spends!(node_txn[0], revoked_local_txn[0]);
4619
4620         mine_transaction(&nodes[1], &node_txn[0]);
4621         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4622
4623         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4624         assert_eq!(spend_txn.len(), 1);
4625         check_spends!(spend_txn[0], node_txn[0]);
4626 }
4627
4628 #[test]
4629 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4630         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4631         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4635
4636         // Create some initial channels
4637         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4638
4639         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4640         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4641         assert_eq!(revoked_local_txn[0].input.len(), 1);
4642         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4643
4644         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4645
4646         // A will generate HTLC-Timeout from revoked commitment tx
4647         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4648         check_closed_broadcast!(nodes[0], true);
4649         check_added_monitors!(nodes[0], 1);
4650         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4651         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4652
4653         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4654         assert_eq!(revoked_htlc_txn.len(), 1);
4655         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4656         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4657         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4658         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4659
4660         // B will generate justice tx from A's revoked commitment/HTLC tx
4661         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4662         check_closed_broadcast!(nodes[1], true);
4663         check_added_monitors!(nodes[1], 1);
4664         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4665
4666         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4667         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4668         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4669         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4670         // transactions next...
4671         assert_eq!(node_txn[0].input.len(), 3);
4672         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4673
4674         assert_eq!(node_txn[1].input.len(), 2);
4675         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4676         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4677                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4678         } else {
4679                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4680                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4681         }
4682
4683         mine_transaction(&nodes[1], &node_txn[1]);
4684         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4685
4686         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4687         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4688         assert_eq!(spend_txn.len(), 1);
4689         assert_eq!(spend_txn[0].input.len(), 1);
4690         check_spends!(spend_txn[0], node_txn[1]);
4691 }
4692
4693 #[test]
4694 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4695         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4696         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4699         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4700
4701         // Create some initial channels
4702         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4703
4704         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4705         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4706         assert_eq!(revoked_local_txn[0].input.len(), 1);
4707         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4708
4709         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4710         assert_eq!(revoked_local_txn[0].output.len(), 2);
4711
4712         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4713
4714         // B will generate HTLC-Success from revoked commitment tx
4715         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4716         check_closed_broadcast!(nodes[1], true);
4717         check_added_monitors!(nodes[1], 1);
4718         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4719         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4720
4721         assert_eq!(revoked_htlc_txn.len(), 1);
4722         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4723         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4724         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4725
4726         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4727         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4728         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4729
4730         // A will generate justice tx from B's revoked commitment/HTLC tx
4731         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4732         check_closed_broadcast!(nodes[0], true);
4733         check_added_monitors!(nodes[0], 1);
4734         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4735
4736         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4737         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4738
4739         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4740         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4741         // transactions next...
4742         assert_eq!(node_txn[0].input.len(), 2);
4743         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4744         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4745                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4746         } else {
4747                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4748                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4749         }
4750
4751         assert_eq!(node_txn[1].input.len(), 1);
4752         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4753
4754         mine_transaction(&nodes[0], &node_txn[1]);
4755         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4756
4757         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4758         // didn't try to generate any new transactions.
4759
4760         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4761         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4762         assert_eq!(spend_txn.len(), 3);
4763         assert_eq!(spend_txn[0].input.len(), 1);
4764         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4765         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4766         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4767         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4768 }
4769
4770 #[test]
4771 fn test_onchain_to_onchain_claim() {
4772         // Test that in case of channel closure, we detect the state of output and claim HTLC
4773         // on downstream peer's remote commitment tx.
4774         // First, have C claim an HTLC against its own latest commitment transaction.
4775         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4776         // channel.
4777         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4778         // gets broadcast.
4779
4780         let chanmon_cfgs = create_chanmon_cfgs(3);
4781         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4782         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4783         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4784
4785         // Create some initial channels
4786         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4787         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4788
4789         // Ensure all nodes are at the same height
4790         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4791         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4792         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4793         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4794
4795         // Rebalance the network a bit by relaying one payment through all the channels ...
4796         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4797         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4798
4799         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4800         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4801         check_spends!(commitment_tx[0], chan_2.3);
4802         nodes[2].node.claim_funds(payment_preimage);
4803         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4804         check_added_monitors!(nodes[2], 1);
4805         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4806         assert!(updates.update_add_htlcs.is_empty());
4807         assert!(updates.update_fail_htlcs.is_empty());
4808         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4809         assert!(updates.update_fail_malformed_htlcs.is_empty());
4810
4811         mine_transaction(&nodes[2], &commitment_tx[0]);
4812         check_closed_broadcast!(nodes[2], true);
4813         check_added_monitors!(nodes[2], 1);
4814         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4815
4816         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4817         assert_eq!(c_txn.len(), 1);
4818         check_spends!(c_txn[0], commitment_tx[0]);
4819         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4820         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4821         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4822
4823         // 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
4824         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4825         check_added_monitors!(nodes[1], 1);
4826         let events = nodes[1].node.get_and_clear_pending_events();
4827         assert_eq!(events.len(), 2);
4828         match events[0] {
4829                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4830                 _ => panic!("Unexpected event"),
4831         }
4832         match events[1] {
4833                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4834                         assert_eq!(fee_earned_msat, Some(1000));
4835                         assert_eq!(prev_channel_id, Some(chan_1.2));
4836                         assert_eq!(claim_from_onchain_tx, true);
4837                         assert_eq!(next_channel_id, Some(chan_2.2));
4838                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4839                 },
4840                 _ => panic!("Unexpected event"),
4841         }
4842         check_added_monitors!(nodes[1], 1);
4843         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4844         assert_eq!(msg_events.len(), 3);
4845         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4846         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4847
4848         match nodes_2_event {
4849                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4850                 _ => panic!("Unexpected event"),
4851         }
4852
4853         match nodes_0_event {
4854                 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, .. } } => {
4855                         assert!(update_add_htlcs.is_empty());
4856                         assert!(update_fail_htlcs.is_empty());
4857                         assert_eq!(update_fulfill_htlcs.len(), 1);
4858                         assert!(update_fail_malformed_htlcs.is_empty());
4859                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4860                 },
4861                 _ => panic!("Unexpected event"),
4862         };
4863
4864         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4865         match msg_events[0] {
4866                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4867                 _ => panic!("Unexpected event"),
4868         }
4869
4870         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4871         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4872         mine_transaction(&nodes[1], &commitment_tx[0]);
4873         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4874         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4875         // ChannelMonitor: HTLC-Success tx
4876         assert_eq!(b_txn.len(), 1);
4877         check_spends!(b_txn[0], commitment_tx[0]);
4878         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4879         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4880         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4881
4882         check_closed_broadcast!(nodes[1], true);
4883         check_added_monitors!(nodes[1], 1);
4884 }
4885
4886 #[test]
4887 fn test_duplicate_payment_hash_one_failure_one_success() {
4888         // Topology : A --> B --> C --> D
4889         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4890         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4891         // we forward one of the payments onwards to D.
4892         let chanmon_cfgs = create_chanmon_cfgs(4);
4893         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4894         // When this test was written, the default base fee floated based on the HTLC count.
4895         // It is now fixed, so we simply set the fee to the expected value here.
4896         let mut config = test_default_channel_config();
4897         config.channel_config.forwarding_fee_base_msat = 196;
4898         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4899                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4900         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4901
4902         create_announced_chan_between_nodes(&nodes, 0, 1);
4903         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4904         create_announced_chan_between_nodes(&nodes, 2, 3);
4905
4906         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4907         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4908         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4909         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4910         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4911
4912         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4913
4914         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4915         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4916         // script push size limit so that the below script length checks match
4917         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4918         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4919                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4920         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4921         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4922
4923         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4924         assert_eq!(commitment_txn[0].input.len(), 1);
4925         check_spends!(commitment_txn[0], chan_2.3);
4926
4927         mine_transaction(&nodes[1], &commitment_txn[0]);
4928         check_closed_broadcast!(nodes[1], true);
4929         check_added_monitors!(nodes[1], 1);
4930         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4931         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4932
4933         let htlc_timeout_tx;
4934         { // Extract one of the two HTLC-Timeout transaction
4935                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4936                 // ChannelMonitor: timeout tx * 2-or-3
4937                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4938
4939                 check_spends!(node_txn[0], commitment_txn[0]);
4940                 assert_eq!(node_txn[0].input.len(), 1);
4941                 assert_eq!(node_txn[0].output.len(), 1);
4942
4943                 if node_txn.len() > 2 {
4944                         check_spends!(node_txn[1], commitment_txn[0]);
4945                         assert_eq!(node_txn[1].input.len(), 1);
4946                         assert_eq!(node_txn[1].output.len(), 1);
4947                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4948
4949                         check_spends!(node_txn[2], commitment_txn[0]);
4950                         assert_eq!(node_txn[2].input.len(), 1);
4951                         assert_eq!(node_txn[2].output.len(), 1);
4952                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4953                 } else {
4954                         check_spends!(node_txn[1], commitment_txn[0]);
4955                         assert_eq!(node_txn[1].input.len(), 1);
4956                         assert_eq!(node_txn[1].output.len(), 1);
4957                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4958                 }
4959
4960                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4961                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4962                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4963                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4964                 if node_txn.len() > 2 {
4965                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4966                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4967                 } else {
4968                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4969                 }
4970         }
4971
4972         nodes[2].node.claim_funds(our_payment_preimage);
4973         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4974
4975         mine_transaction(&nodes[2], &commitment_txn[0]);
4976         check_added_monitors!(nodes[2], 2);
4977         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4978         let events = nodes[2].node.get_and_clear_pending_msg_events();
4979         match events[0] {
4980                 MessageSendEvent::UpdateHTLCs { .. } => {},
4981                 _ => panic!("Unexpected event"),
4982         }
4983         match events[1] {
4984                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4985                 _ => panic!("Unexepected event"),
4986         }
4987         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4988         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4989         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4990         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4991         assert_eq!(htlc_success_txn[0].input.len(), 1);
4992         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4993         assert_eq!(htlc_success_txn[1].input.len(), 1);
4994         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4995         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4996         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4997
4998         mine_transaction(&nodes[1], &htlc_timeout_tx);
4999         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5000         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 }]);
5001         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5002         assert!(htlc_updates.update_add_htlcs.is_empty());
5003         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5004         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5005         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5006         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5007         check_added_monitors!(nodes[1], 1);
5008
5009         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5010         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5011         {
5012                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5013         }
5014         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5015
5016         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5017         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5018         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5019         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5020         assert!(updates.update_add_htlcs.is_empty());
5021         assert!(updates.update_fail_htlcs.is_empty());
5022         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5023         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5024         assert!(updates.update_fail_malformed_htlcs.is_empty());
5025         check_added_monitors!(nodes[1], 1);
5026
5027         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5028         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5029         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5030 }
5031
5032 #[test]
5033 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5034         let chanmon_cfgs = create_chanmon_cfgs(2);
5035         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5036         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5037         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5038
5039         // Create some initial channels
5040         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5041
5042         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5043         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5044         assert_eq!(local_txn.len(), 1);
5045         assert_eq!(local_txn[0].input.len(), 1);
5046         check_spends!(local_txn[0], chan_1.3);
5047
5048         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5049         nodes[1].node.claim_funds(payment_preimage);
5050         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5051         check_added_monitors!(nodes[1], 1);
5052
5053         mine_transaction(&nodes[1], &local_txn[0]);
5054         check_added_monitors!(nodes[1], 1);
5055         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5056         let events = nodes[1].node.get_and_clear_pending_msg_events();
5057         match events[0] {
5058                 MessageSendEvent::UpdateHTLCs { .. } => {},
5059                 _ => panic!("Unexpected event"),
5060         }
5061         match events[1] {
5062                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5063                 _ => panic!("Unexepected event"),
5064         }
5065         let node_tx = {
5066                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5067                 assert_eq!(node_txn.len(), 1);
5068                 assert_eq!(node_txn[0].input.len(), 1);
5069                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5070                 check_spends!(node_txn[0], local_txn[0]);
5071                 node_txn[0].clone()
5072         };
5073
5074         mine_transaction(&nodes[1], &node_tx);
5075         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5076
5077         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5078         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5079         assert_eq!(spend_txn.len(), 1);
5080         assert_eq!(spend_txn[0].input.len(), 1);
5081         check_spends!(spend_txn[0], node_tx);
5082         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5083 }
5084
5085 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5086         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5087         // unrevoked commitment transaction.
5088         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5089         // a remote RAA before they could be failed backwards (and combinations thereof).
5090         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5091         // use the same payment hashes.
5092         // Thus, we use a six-node network:
5093         //
5094         // A \         / E
5095         //    - C - D -
5096         // B /         \ F
5097         // And test where C fails back to A/B when D announces its latest commitment transaction
5098         let chanmon_cfgs = create_chanmon_cfgs(6);
5099         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5100         // When this test was written, the default base fee floated based on the HTLC count.
5101         // It is now fixed, so we simply set the fee to the expected value here.
5102         let mut config = test_default_channel_config();
5103         config.channel_config.forwarding_fee_base_msat = 196;
5104         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5105                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5106         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5107
5108         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5109         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5110         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5111         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5112         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5113
5114         // Rebalance and check output sanity...
5115         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5116         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5117         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5118
5119         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5120                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5121         // 0th HTLC:
5122         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
5123         // 1st HTLC:
5124         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
5125         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5126         // 2nd HTLC:
5127         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
5128         // 3rd HTLC:
5129         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
5130         // 4th HTLC:
5131         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5132         // 5th HTLC:
5133         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5134         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5135         // 6th HTLC:
5136         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());
5137         // 7th HTLC:
5138         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());
5139
5140         // 8th HTLC:
5141         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5142         // 9th HTLC:
5143         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5144         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
5145
5146         // 10th HTLC:
5147         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
5148         // 11th HTLC:
5149         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5150         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());
5151
5152         // Double-check that six of the new HTLC were added
5153         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5154         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5155         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5156         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5157
5158         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5159         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5160         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5161         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5162         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5163         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5164         check_added_monitors!(nodes[4], 0);
5165
5166         let failed_destinations = vec![
5167                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5168                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5169                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5170                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5171         ];
5172         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5173         check_added_monitors!(nodes[4], 1);
5174
5175         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5176         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5177         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5178         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5179         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5180         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5181
5182         // Fail 3rd below-dust and 7th above-dust HTLCs
5183         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5184         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5185         check_added_monitors!(nodes[5], 0);
5186
5187         let failed_destinations_2 = vec![
5188                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5189                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5190         ];
5191         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5192         check_added_monitors!(nodes[5], 1);
5193
5194         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5195         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5196         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5197         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5198
5199         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5200
5201         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5202         let failed_destinations_3 = vec![
5203                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5204                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5205                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5206                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5207                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5208                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5209         ];
5210         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5211         check_added_monitors!(nodes[3], 1);
5212         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5213         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5214         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5215         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5216         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5217         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5218         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5219         if deliver_last_raa {
5220                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5221         } else {
5222                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5223         }
5224
5225         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5226         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5227         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5228         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5229         //
5230         // We now broadcast the latest commitment transaction, which *should* result in failures for
5231         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5232         // the non-broadcast above-dust HTLCs.
5233         //
5234         // Alternatively, we may broadcast the previous commitment transaction, which should only
5235         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5236         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5237
5238         if announce_latest {
5239                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5240         } else {
5241                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5242         }
5243         let events = nodes[2].node.get_and_clear_pending_events();
5244         let close_event = if deliver_last_raa {
5245                 assert_eq!(events.len(), 2 + 6);
5246                 events.last().clone().unwrap()
5247         } else {
5248                 assert_eq!(events.len(), 1);
5249                 events.last().clone().unwrap()
5250         };
5251         match close_event {
5252                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5253                 _ => panic!("Unexpected event"),
5254         }
5255
5256         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5257         check_closed_broadcast!(nodes[2], true);
5258         if deliver_last_raa {
5259                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5260
5261                 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();
5262                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5263         } else {
5264                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5265                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5266                 } else {
5267                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5268                 };
5269
5270                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5271         }
5272         check_added_monitors!(nodes[2], 3);
5273
5274         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5275         assert_eq!(cs_msgs.len(), 2);
5276         let mut a_done = false;
5277         for msg in cs_msgs {
5278                 match msg {
5279                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5280                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5281                                 // should be failed-backwards here.
5282                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5283                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5284                                         for htlc in &updates.update_fail_htlcs {
5285                                                 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 });
5286                                         }
5287                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5288                                         assert!(!a_done);
5289                                         a_done = true;
5290                                         &nodes[0]
5291                                 } else {
5292                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5293                                         for htlc in &updates.update_fail_htlcs {
5294                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5295                                         }
5296                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5297                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5298                                         &nodes[1]
5299                                 };
5300                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5301                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5302                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5303                                 if announce_latest {
5304                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5305                                         if *node_id == nodes[0].node.get_our_node_id() {
5306                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5307                                         }
5308                                 }
5309                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5310                         },
5311                         _ => panic!("Unexpected event"),
5312                 }
5313         }
5314
5315         let as_events = nodes[0].node.get_and_clear_pending_events();
5316         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5317         let mut as_failds = HashSet::new();
5318         let mut as_updates = 0;
5319         for event in as_events.iter() {
5320                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5321                         assert!(as_failds.insert(*payment_hash));
5322                         if *payment_hash != payment_hash_2 {
5323                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5324                         } else {
5325                                 assert!(!payment_failed_permanently);
5326                         }
5327                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5328                                 as_updates += 1;
5329                         }
5330                 } else if let &Event::PaymentFailed { .. } = event {
5331                 } else { panic!("Unexpected event"); }
5332         }
5333         assert!(as_failds.contains(&payment_hash_1));
5334         assert!(as_failds.contains(&payment_hash_2));
5335         if announce_latest {
5336                 assert!(as_failds.contains(&payment_hash_3));
5337                 assert!(as_failds.contains(&payment_hash_5));
5338         }
5339         assert!(as_failds.contains(&payment_hash_6));
5340
5341         let bs_events = nodes[1].node.get_and_clear_pending_events();
5342         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5343         let mut bs_failds = HashSet::new();
5344         let mut bs_updates = 0;
5345         for event in bs_events.iter() {
5346                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5347                         assert!(bs_failds.insert(*payment_hash));
5348                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5349                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5350                         } else {
5351                                 assert!(!payment_failed_permanently);
5352                         }
5353                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5354                                 bs_updates += 1;
5355                         }
5356                 } else if let &Event::PaymentFailed { .. } = event {
5357                 } else { panic!("Unexpected event"); }
5358         }
5359         assert!(bs_failds.contains(&payment_hash_1));
5360         assert!(bs_failds.contains(&payment_hash_2));
5361         if announce_latest {
5362                 assert!(bs_failds.contains(&payment_hash_4));
5363         }
5364         assert!(bs_failds.contains(&payment_hash_5));
5365
5366         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5367         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5368         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5369         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5370         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5371         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5372 }
5373
5374 #[test]
5375 fn test_fail_backwards_latest_remote_announce_a() {
5376         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5377 }
5378
5379 #[test]
5380 fn test_fail_backwards_latest_remote_announce_b() {
5381         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5382 }
5383
5384 #[test]
5385 fn test_fail_backwards_previous_remote_announce() {
5386         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5387         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5388         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5389 }
5390
5391 #[test]
5392 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5393         let chanmon_cfgs = create_chanmon_cfgs(2);
5394         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5395         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5396         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5397
5398         // Create some initial channels
5399         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5400
5401         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5402         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5403         assert_eq!(local_txn[0].input.len(), 1);
5404         check_spends!(local_txn[0], chan_1.3);
5405
5406         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5407         mine_transaction(&nodes[0], &local_txn[0]);
5408         check_closed_broadcast!(nodes[0], true);
5409         check_added_monitors!(nodes[0], 1);
5410         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5411         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5412
5413         let htlc_timeout = {
5414                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5415                 assert_eq!(node_txn.len(), 1);
5416                 assert_eq!(node_txn[0].input.len(), 1);
5417                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5418                 check_spends!(node_txn[0], local_txn[0]);
5419                 node_txn[0].clone()
5420         };
5421
5422         mine_transaction(&nodes[0], &htlc_timeout);
5423         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5424         expect_payment_failed!(nodes[0], our_payment_hash, false);
5425
5426         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5427         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5428         assert_eq!(spend_txn.len(), 3);
5429         check_spends!(spend_txn[0], local_txn[0]);
5430         assert_eq!(spend_txn[1].input.len(), 1);
5431         check_spends!(spend_txn[1], htlc_timeout);
5432         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5433         assert_eq!(spend_txn[2].input.len(), 2);
5434         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5435         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5436                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5437 }
5438
5439 #[test]
5440 fn test_key_derivation_params() {
5441         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5442         // manager rotation to test that `channel_keys_id` returned in
5443         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5444         // then derive a `delayed_payment_key`.
5445
5446         let chanmon_cfgs = create_chanmon_cfgs(3);
5447
5448         // We manually create the node configuration to backup the seed.
5449         let seed = [42; 32];
5450         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5451         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);
5452         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5453         let scorer = RwLock::new(test_utils::TestScorer::new());
5454         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5455         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)) };
5456         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5457         node_cfgs.remove(0);
5458         node_cfgs.insert(0, node);
5459
5460         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5461         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5462
5463         // Create some initial channels
5464         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5465         // for node 0
5466         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5467         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5468         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5469
5470         // Ensure all nodes are at the same height
5471         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5472         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5473         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5474         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5475
5476         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5477         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5478         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5479         assert_eq!(local_txn_1[0].input.len(), 1);
5480         check_spends!(local_txn_1[0], chan_1.3);
5481
5482         // We check funding pubkey are unique
5483         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]));
5484         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]));
5485         if from_0_funding_key_0 == from_1_funding_key_0
5486             || from_0_funding_key_0 == from_1_funding_key_1
5487             || from_0_funding_key_1 == from_1_funding_key_0
5488             || from_0_funding_key_1 == from_1_funding_key_1 {
5489                 panic!("Funding pubkeys aren't unique");
5490         }
5491
5492         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5493         mine_transaction(&nodes[0], &local_txn_1[0]);
5494         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5495         check_closed_broadcast!(nodes[0], true);
5496         check_added_monitors!(nodes[0], 1);
5497         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5498
5499         let htlc_timeout = {
5500                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5501                 assert_eq!(node_txn.len(), 1);
5502                 assert_eq!(node_txn[0].input.len(), 1);
5503                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5504                 check_spends!(node_txn[0], local_txn_1[0]);
5505                 node_txn[0].clone()
5506         };
5507
5508         mine_transaction(&nodes[0], &htlc_timeout);
5509         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5510         expect_payment_failed!(nodes[0], our_payment_hash, false);
5511
5512         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5513         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5514         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5515         assert_eq!(spend_txn.len(), 3);
5516         check_spends!(spend_txn[0], local_txn_1[0]);
5517         assert_eq!(spend_txn[1].input.len(), 1);
5518         check_spends!(spend_txn[1], htlc_timeout);
5519         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5520         assert_eq!(spend_txn[2].input.len(), 2);
5521         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5522         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5523                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5524 }
5525
5526 #[test]
5527 fn test_static_output_closing_tx() {
5528         let chanmon_cfgs = create_chanmon_cfgs(2);
5529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5532
5533         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5534
5535         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5536         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5537
5538         mine_transaction(&nodes[0], &closing_tx);
5539         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5540         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5541
5542         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5543         assert_eq!(spend_txn.len(), 1);
5544         check_spends!(spend_txn[0], closing_tx);
5545
5546         mine_transaction(&nodes[1], &closing_tx);
5547         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5548         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5549
5550         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5551         assert_eq!(spend_txn.len(), 1);
5552         check_spends!(spend_txn[0], closing_tx);
5553 }
5554
5555 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5556         let chanmon_cfgs = create_chanmon_cfgs(2);
5557         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5558         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5559         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5560         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5561
5562         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5563
5564         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5565         // present in B's local commitment transaction, but none of A's commitment transactions.
5566         nodes[1].node.claim_funds(payment_preimage);
5567         check_added_monitors!(nodes[1], 1);
5568         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5569
5570         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5571         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5572         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5573
5574         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5575         check_added_monitors!(nodes[0], 1);
5576         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5577         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5578         check_added_monitors!(nodes[1], 1);
5579
5580         let starting_block = nodes[1].best_block_info();
5581         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5582         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5583                 connect_block(&nodes[1], &block);
5584                 block.header.prev_blockhash = block.block_hash();
5585         }
5586         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5587         check_closed_broadcast!(nodes[1], true);
5588         check_added_monitors!(nodes[1], 1);
5589         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5590 }
5591
5592 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5593         let chanmon_cfgs = create_chanmon_cfgs(2);
5594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5596         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5597         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5598
5599         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5600         nodes[0].node.send_payment_with_route(&route, payment_hash,
5601                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5602         check_added_monitors!(nodes[0], 1);
5603
5604         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5605
5606         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5607         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5608         // to "time out" the HTLC.
5609
5610         let starting_block = nodes[1].best_block_info();
5611         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5612
5613         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5614                 connect_block(&nodes[0], &block);
5615                 block.header.prev_blockhash = block.block_hash();
5616         }
5617         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5618         check_closed_broadcast!(nodes[0], true);
5619         check_added_monitors!(nodes[0], 1);
5620         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5621 }
5622
5623 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5624         let chanmon_cfgs = create_chanmon_cfgs(3);
5625         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5626         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5627         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5628         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5629
5630         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5631         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5632         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5633         // actually revoked.
5634         let htlc_value = if use_dust { 50000 } else { 3000000 };
5635         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5636         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5637         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5638         check_added_monitors!(nodes[1], 1);
5639
5640         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5641         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5642         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5643         check_added_monitors!(nodes[0], 1);
5644         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5645         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5646         check_added_monitors!(nodes[1], 1);
5647         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5648         check_added_monitors!(nodes[1], 1);
5649         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5650
5651         if check_revoke_no_close {
5652                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5653                 check_added_monitors!(nodes[0], 1);
5654         }
5655
5656         let starting_block = nodes[1].best_block_info();
5657         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5658         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5659                 connect_block(&nodes[0], &block);
5660                 block.header.prev_blockhash = block.block_hash();
5661         }
5662         if !check_revoke_no_close {
5663                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5664                 check_closed_broadcast!(nodes[0], true);
5665                 check_added_monitors!(nodes[0], 1);
5666                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5667         } else {
5668                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5669         }
5670 }
5671
5672 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5673 // There are only a few cases to test here:
5674 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5675 //    broadcastable commitment transactions result in channel closure,
5676 //  * its included in an unrevoked-but-previous remote commitment transaction,
5677 //  * its included in the latest remote or local commitment transactions.
5678 // We test each of the three possible commitment transactions individually and use both dust and
5679 // non-dust HTLCs.
5680 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5681 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5682 // tested for at least one of the cases in other tests.
5683 #[test]
5684 fn htlc_claim_single_commitment_only_a() {
5685         do_htlc_claim_local_commitment_only(true);
5686         do_htlc_claim_local_commitment_only(false);
5687
5688         do_htlc_claim_current_remote_commitment_only(true);
5689         do_htlc_claim_current_remote_commitment_only(false);
5690 }
5691
5692 #[test]
5693 fn htlc_claim_single_commitment_only_b() {
5694         do_htlc_claim_previous_remote_commitment_only(true, false);
5695         do_htlc_claim_previous_remote_commitment_only(false, false);
5696         do_htlc_claim_previous_remote_commitment_only(true, true);
5697         do_htlc_claim_previous_remote_commitment_only(false, true);
5698 }
5699
5700 #[test]
5701 #[should_panic]
5702 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5703         let chanmon_cfgs = create_chanmon_cfgs(2);
5704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5706         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5707         // Force duplicate randomness for every get-random call
5708         for node in nodes.iter() {
5709                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5710         }
5711
5712         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5713         let channel_value_satoshis=10000;
5714         let push_msat=10001;
5715         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5716         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5717         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5718         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5719
5720         // Create a second channel with the same random values. This used to panic due to a colliding
5721         // channel_id, but now panics due to a colliding outbound SCID alias.
5722         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5723 }
5724
5725 #[test]
5726 fn bolt2_open_channel_sending_node_checks_part2() {
5727         let chanmon_cfgs = create_chanmon_cfgs(2);
5728         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5729         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5730         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5731
5732         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5733         let channel_value_satoshis=2^24;
5734         let push_msat=10001;
5735         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5736
5737         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5738         let channel_value_satoshis=10000;
5739         // Test when push_msat is equal to 1000 * funding_satoshis.
5740         let push_msat=1000*channel_value_satoshis+1;
5741         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5742
5743         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5744         let channel_value_satoshis=10000;
5745         let push_msat=10001;
5746         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5747         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5748         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5749
5750         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5751         // 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
5752         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5753
5754         // 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.
5755         assert!(BREAKDOWN_TIMEOUT>0);
5756         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5757
5758         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5759         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5760         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5761
5762         // 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.
5763         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5764         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5765         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5766         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5767         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5768 }
5769
5770 #[test]
5771 fn bolt2_open_channel_sane_dust_limit() {
5772         let chanmon_cfgs = create_chanmon_cfgs(2);
5773         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5774         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5775         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5776
5777         let channel_value_satoshis=1000000;
5778         let push_msat=10001;
5779         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5780         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5781         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5782         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5783
5784         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5785         let events = nodes[1].node.get_and_clear_pending_msg_events();
5786         let err_msg = match events[0] {
5787                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5788                         msg.clone()
5789                 },
5790                 _ => panic!("Unexpected event"),
5791         };
5792         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5793 }
5794
5795 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5796 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5797 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5798 // is no longer affordable once it's freed.
5799 #[test]
5800 fn test_fail_holding_cell_htlc_upon_free() {
5801         let chanmon_cfgs = create_chanmon_cfgs(2);
5802         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5803         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5804         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5805         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5806
5807         // First nodes[0] generates an update_fee, setting the channel's
5808         // pending_update_fee.
5809         {
5810                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5811                 *feerate_lock += 20;
5812         }
5813         nodes[0].node.timer_tick_occurred();
5814         check_added_monitors!(nodes[0], 1);
5815
5816         let events = nodes[0].node.get_and_clear_pending_msg_events();
5817         assert_eq!(events.len(), 1);
5818         let (update_msg, commitment_signed) = match events[0] {
5819                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5820                         (update_fee.as_ref(), commitment_signed)
5821                 },
5822                 _ => panic!("Unexpected event"),
5823         };
5824
5825         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5826
5827         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5828         let channel_reserve = chan_stat.channel_reserve_msat;
5829         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5830         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5831
5832         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5833         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5834         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5835
5836         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5837         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5838                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5839         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5840         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5841
5842         // Flush the pending fee update.
5843         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5844         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5845         check_added_monitors!(nodes[1], 1);
5846         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5847         check_added_monitors!(nodes[0], 1);
5848
5849         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5850         // HTLC, but now that the fee has been raised the payment will now fail, causing
5851         // us to surface its failure to the user.
5852         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5853         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5854         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5855
5856         // Check that the payment failed to be sent out.
5857         let events = nodes[0].node.get_and_clear_pending_events();
5858         assert_eq!(events.len(), 2);
5859         match &events[0] {
5860                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5861                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5862                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5863                         assert_eq!(*payment_failed_permanently, false);
5864                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5865                 },
5866                 _ => panic!("Unexpected event"),
5867         }
5868         match &events[1] {
5869                 &Event::PaymentFailed { ref payment_hash, .. } => {
5870                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5871                 },
5872                 _ => panic!("Unexpected event"),
5873         }
5874 }
5875
5876 // Test that if multiple HTLCs are released from the holding cell and one is
5877 // valid but the other is no longer valid upon release, the valid HTLC can be
5878 // successfully completed while the other one fails as expected.
5879 #[test]
5880 fn test_free_and_fail_holding_cell_htlcs() {
5881         let chanmon_cfgs = create_chanmon_cfgs(2);
5882         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5883         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5884         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5885         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5886
5887         // First nodes[0] generates an update_fee, setting the channel's
5888         // pending_update_fee.
5889         {
5890                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5891                 *feerate_lock += 200;
5892         }
5893         nodes[0].node.timer_tick_occurred();
5894         check_added_monitors!(nodes[0], 1);
5895
5896         let events = nodes[0].node.get_and_clear_pending_msg_events();
5897         assert_eq!(events.len(), 1);
5898         let (update_msg, commitment_signed) = match events[0] {
5899                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5900                         (update_fee.as_ref(), commitment_signed)
5901                 },
5902                 _ => panic!("Unexpected event"),
5903         };
5904
5905         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5906
5907         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5908         let channel_reserve = chan_stat.channel_reserve_msat;
5909         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5910         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5911
5912         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5913         let amt_1 = 20000;
5914         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5915         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5916         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5917
5918         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5919         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5920                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5921         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5922         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5923         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5924         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5925                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5926         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5927         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5928
5929         // Flush the pending fee update.
5930         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5931         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5932         check_added_monitors!(nodes[1], 1);
5933         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5934         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5935         check_added_monitors!(nodes[0], 2);
5936
5937         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5938         // but now that the fee has been raised the second payment will now fail, causing us
5939         // to surface its failure to the user. The first payment should succeed.
5940         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5941         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5942         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
5943
5944         // Check that the second payment failed to be sent out.
5945         let events = nodes[0].node.get_and_clear_pending_events();
5946         assert_eq!(events.len(), 2);
5947         match &events[0] {
5948                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5949                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5950                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5951                         assert_eq!(*payment_failed_permanently, false);
5952                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5953                 },
5954                 _ => panic!("Unexpected event"),
5955         }
5956         match &events[1] {
5957                 &Event::PaymentFailed { ref payment_hash, .. } => {
5958                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5959                 },
5960                 _ => panic!("Unexpected event"),
5961         }
5962
5963         // Complete the first payment and the RAA from the fee update.
5964         let (payment_event, send_raa_event) = {
5965                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5966                 assert_eq!(msgs.len(), 2);
5967                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5968         };
5969         let raa = match send_raa_event {
5970                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5971                 _ => panic!("Unexpected event"),
5972         };
5973         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5974         check_added_monitors!(nodes[1], 1);
5975         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5976         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5977         let events = nodes[1].node.get_and_clear_pending_events();
5978         assert_eq!(events.len(), 1);
5979         match events[0] {
5980                 Event::PendingHTLCsForwardable { .. } => {},
5981                 _ => panic!("Unexpected event"),
5982         }
5983         nodes[1].node.process_pending_htlc_forwards();
5984         let events = nodes[1].node.get_and_clear_pending_events();
5985         assert_eq!(events.len(), 1);
5986         match events[0] {
5987                 Event::PaymentClaimable { .. } => {},
5988                 _ => panic!("Unexpected event"),
5989         }
5990         nodes[1].node.claim_funds(payment_preimage_1);
5991         check_added_monitors!(nodes[1], 1);
5992         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5993
5994         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5995         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5996         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5997         expect_payment_sent!(nodes[0], payment_preimage_1);
5998 }
5999
6000 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6001 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6002 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6003 // once it's freed.
6004 #[test]
6005 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6006         let chanmon_cfgs = create_chanmon_cfgs(3);
6007         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6008         // Avoid having to include routing fees in calculations
6009         let mut config = test_default_channel_config();
6010         config.channel_config.forwarding_fee_base_msat = 0;
6011         config.channel_config.forwarding_fee_proportional_millionths = 0;
6012         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6013         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6014         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6015         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6016
6017         // First nodes[1] generates an update_fee, setting the channel's
6018         // pending_update_fee.
6019         {
6020                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6021                 *feerate_lock += 20;
6022         }
6023         nodes[1].node.timer_tick_occurred();
6024         check_added_monitors!(nodes[1], 1);
6025
6026         let events = nodes[1].node.get_and_clear_pending_msg_events();
6027         assert_eq!(events.len(), 1);
6028         let (update_msg, commitment_signed) = match events[0] {
6029                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6030                         (update_fee.as_ref(), commitment_signed)
6031                 },
6032                 _ => panic!("Unexpected event"),
6033         };
6034
6035         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6036
6037         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6038         let channel_reserve = chan_stat.channel_reserve_msat;
6039         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6040         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6041
6042         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6043         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6044         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6045         let payment_event = {
6046                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6047                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6048                 check_added_monitors!(nodes[0], 1);
6049
6050                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6051                 assert_eq!(events.len(), 1);
6052
6053                 SendEvent::from_event(events.remove(0))
6054         };
6055         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6056         check_added_monitors!(nodes[1], 0);
6057         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6058         expect_pending_htlcs_forwardable!(nodes[1]);
6059
6060         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6061         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6062
6063         // Flush the pending fee update.
6064         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6065         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6066         check_added_monitors!(nodes[2], 1);
6067         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6068         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6069         check_added_monitors!(nodes[1], 2);
6070
6071         // A final RAA message is generated to finalize the fee update.
6072         let events = nodes[1].node.get_and_clear_pending_msg_events();
6073         assert_eq!(events.len(), 1);
6074
6075         let raa_msg = match &events[0] {
6076                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6077                         msg.clone()
6078                 },
6079                 _ => panic!("Unexpected event"),
6080         };
6081
6082         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6083         check_added_monitors!(nodes[2], 1);
6084         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6085
6086         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6087         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6088         assert_eq!(process_htlc_forwards_event.len(), 2);
6089         match &process_htlc_forwards_event[0] {
6090                 &Event::PendingHTLCsForwardable { .. } => {},
6091                 _ => panic!("Unexpected event"),
6092         }
6093
6094         // In response, we call ChannelManager's process_pending_htlc_forwards
6095         nodes[1].node.process_pending_htlc_forwards();
6096         check_added_monitors!(nodes[1], 1);
6097
6098         // This causes the HTLC to be failed backwards.
6099         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6100         assert_eq!(fail_event.len(), 1);
6101         let (fail_msg, commitment_signed) = match &fail_event[0] {
6102                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6103                         assert_eq!(updates.update_add_htlcs.len(), 0);
6104                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6105                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6106                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6107                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6108                 },
6109                 _ => panic!("Unexpected event"),
6110         };
6111
6112         // Pass the failure messages back to nodes[0].
6113         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6114         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6115
6116         // Complete the HTLC failure+removal process.
6117         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6118         check_added_monitors!(nodes[0], 1);
6119         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6120         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6121         check_added_monitors!(nodes[1], 2);
6122         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6123         assert_eq!(final_raa_event.len(), 1);
6124         let raa = match &final_raa_event[0] {
6125                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6126                 _ => panic!("Unexpected event"),
6127         };
6128         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6129         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6130         check_added_monitors!(nodes[0], 1);
6131 }
6132
6133 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6134 // 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.
6135 //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.
6136
6137 #[test]
6138 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6139         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6140         let chanmon_cfgs = create_chanmon_cfgs(2);
6141         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6142         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6143         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6144         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6145
6146         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6147         route.paths[0].hops[0].fee_msat = 100;
6148
6149         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6150                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6151                 ), true, APIError::ChannelUnavailable { .. }, {});
6152         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6153 }
6154
6155 #[test]
6156 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6157         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6158         let chanmon_cfgs = create_chanmon_cfgs(2);
6159         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6160         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6161         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6162         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6163
6164         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6165         route.paths[0].hops[0].fee_msat = 0;
6166         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6167                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6168                 true, APIError::ChannelUnavailable { ref err },
6169                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6170
6171         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6172         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6173 }
6174
6175 #[test]
6176 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6177         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6178         let chanmon_cfgs = create_chanmon_cfgs(2);
6179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6181         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6182         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6183
6184         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6185         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6186                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6187         check_added_monitors!(nodes[0], 1);
6188         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6189         updates.update_add_htlcs[0].amount_msat = 0;
6190
6191         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6192         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6193         check_closed_broadcast!(nodes[1], true).unwrap();
6194         check_added_monitors!(nodes[1], 1);
6195         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6196                 [nodes[0].node.get_our_node_id()], 100000);
6197 }
6198
6199 #[test]
6200 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6201         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6202         //It is enforced when constructing a route.
6203         let chanmon_cfgs = create_chanmon_cfgs(2);
6204         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6205         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6206         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6207         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6208
6209         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6210                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6211         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6212         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6213         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6214                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6215                 ), true, APIError::InvalidRoute { ref err },
6216                 assert_eq!(err, &"Channel CLTV overflowed?"));
6217 }
6218
6219 #[test]
6220 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6221         //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.
6222         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6223         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6224         let chanmon_cfgs = create_chanmon_cfgs(2);
6225         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6226         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6227         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6228         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6229         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6230                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6231
6232         // Fetch a route in advance as we will be unable to once we're unable to send.
6233         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6234         for i in 0..max_accepted_htlcs {
6235                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6236                 let payment_event = {
6237                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6238                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6239                         check_added_monitors!(nodes[0], 1);
6240
6241                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6242                         assert_eq!(events.len(), 1);
6243                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6244                                 assert_eq!(htlcs[0].htlc_id, i);
6245                         } else {
6246                                 assert!(false);
6247                         }
6248                         SendEvent::from_event(events.remove(0))
6249                 };
6250                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6251                 check_added_monitors!(nodes[1], 0);
6252                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6253
6254                 expect_pending_htlcs_forwardable!(nodes[1]);
6255                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6256         }
6257         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6258                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6259                 ), true, APIError::ChannelUnavailable { .. }, {});
6260
6261         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6262 }
6263
6264 #[test]
6265 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6266         //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.
6267         let chanmon_cfgs = create_chanmon_cfgs(2);
6268         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6269         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6270         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6271         let channel_value = 100000;
6272         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6273         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6274
6275         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6276
6277         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6278         // Manually create a route over our max in flight (which our router normally automatically
6279         // limits us to.
6280         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6281         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6282                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6283                 ), true, APIError::ChannelUnavailable { .. }, {});
6284         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6285
6286         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6287 }
6288
6289 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6290 #[test]
6291 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6292         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6293         let chanmon_cfgs = create_chanmon_cfgs(2);
6294         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6295         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6296         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6297         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6298         let htlc_minimum_msat: u64;
6299         {
6300                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6301                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6302                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6303                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6304         }
6305
6306         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6307         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6308                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6309         check_added_monitors!(nodes[0], 1);
6310         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6311         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6312         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6313         assert!(nodes[1].node.list_channels().is_empty());
6314         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6315         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()));
6316         check_added_monitors!(nodes[1], 1);
6317         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6318 }
6319
6320 #[test]
6321 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6322         //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
6323         let chanmon_cfgs = create_chanmon_cfgs(2);
6324         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6325         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6326         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6327         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6328
6329         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6330         let channel_reserve = chan_stat.channel_reserve_msat;
6331         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6332         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6333         // The 2* and +1 are for the fee spike reserve.
6334         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6335
6336         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6337         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6338         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6339                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6340         check_added_monitors!(nodes[0], 1);
6341         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6342
6343         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6344         // at this time channel-initiatee receivers are not required to enforce that senders
6345         // respect the fee_spike_reserve.
6346         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6347         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6348
6349         assert!(nodes[1].node.list_channels().is_empty());
6350         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6351         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6352         check_added_monitors!(nodes[1], 1);
6353         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6354 }
6355
6356 #[test]
6357 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6358         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6359         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6360         let chanmon_cfgs = create_chanmon_cfgs(2);
6361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6365
6366         let send_amt = 3999999;
6367         let (mut route, our_payment_hash, _, our_payment_secret) =
6368                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6369         route.paths[0].hops[0].fee_msat = send_amt;
6370         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6371         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6372         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6373         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6374                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6375         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6376
6377         let mut msg = msgs::UpdateAddHTLC {
6378                 channel_id: chan.2,
6379                 htlc_id: 0,
6380                 amount_msat: 1000,
6381                 payment_hash: our_payment_hash,
6382                 cltv_expiry: htlc_cltv,
6383                 onion_routing_packet: onion_packet.clone(),
6384                 skimmed_fee_msat: None,
6385         };
6386
6387         for i in 0..50 {
6388                 msg.htlc_id = i as u64;
6389                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6390         }
6391         msg.htlc_id = (50) as u64;
6392         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6393
6394         assert!(nodes[1].node.list_channels().is_empty());
6395         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6396         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6397         check_added_monitors!(nodes[1], 1);
6398         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6399 }
6400
6401 #[test]
6402 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6403         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6404         let chanmon_cfgs = create_chanmon_cfgs(2);
6405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6407         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6408         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6409
6410         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6411         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6412                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6413         check_added_monitors!(nodes[0], 1);
6414         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6415         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;
6416         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6417
6418         assert!(nodes[1].node.list_channels().is_empty());
6419         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6420         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6421         check_added_monitors!(nodes[1], 1);
6422         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6423 }
6424
6425 #[test]
6426 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6427         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6428         let chanmon_cfgs = create_chanmon_cfgs(2);
6429         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6430         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6431         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6432
6433         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6434         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6435         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6436                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6437         check_added_monitors!(nodes[0], 1);
6438         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6439         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6440         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6441
6442         assert!(nodes[1].node.list_channels().is_empty());
6443         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6444         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6445         check_added_monitors!(nodes[1], 1);
6446         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6447 }
6448
6449 #[test]
6450 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6451         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6452         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6453         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6454         let chanmon_cfgs = create_chanmon_cfgs(2);
6455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6457         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6458
6459         create_announced_chan_between_nodes(&nodes, 0, 1);
6460         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6461         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6462                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6463         check_added_monitors!(nodes[0], 1);
6464         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6465         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6466
6467         //Disconnect and Reconnect
6468         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6469         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6470         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6471                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6472         }, true).unwrap();
6473         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6474         assert_eq!(reestablish_1.len(), 1);
6475         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6476                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6477         }, false).unwrap();
6478         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6479         assert_eq!(reestablish_2.len(), 1);
6480         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6481         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6482         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6483         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6484
6485         //Resend HTLC
6486         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6487         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6488         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6489         check_added_monitors!(nodes[1], 1);
6490         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6491
6492         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6493
6494         assert!(nodes[1].node.list_channels().is_empty());
6495         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6496         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6497         check_added_monitors!(nodes[1], 1);
6498         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6499 }
6500
6501 #[test]
6502 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6503         //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.
6504
6505         let chanmon_cfgs = create_chanmon_cfgs(2);
6506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6508         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6509         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6510         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6511         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6512                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6513
6514         check_added_monitors!(nodes[0], 1);
6515         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6516         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6517
6518         let update_msg = msgs::UpdateFulfillHTLC{
6519                 channel_id: chan.2,
6520                 htlc_id: 0,
6521                 payment_preimage: our_payment_preimage,
6522         };
6523
6524         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6525
6526         assert!(nodes[0].node.list_channels().is_empty());
6527         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6528         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()));
6529         check_added_monitors!(nodes[0], 1);
6530         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6531 }
6532
6533 #[test]
6534 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6535         //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.
6536
6537         let chanmon_cfgs = create_chanmon_cfgs(2);
6538         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6539         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6540         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6541         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6542
6543         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6544         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6545                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6546         check_added_monitors!(nodes[0], 1);
6547         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6548         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6549
6550         let update_msg = msgs::UpdateFailHTLC{
6551                 channel_id: chan.2,
6552                 htlc_id: 0,
6553                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6554         };
6555
6556         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6557
6558         assert!(nodes[0].node.list_channels().is_empty());
6559         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6560         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()));
6561         check_added_monitors!(nodes[0], 1);
6562         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6563 }
6564
6565 #[test]
6566 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6567         //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.
6568
6569         let chanmon_cfgs = create_chanmon_cfgs(2);
6570         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6574
6575         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6576         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6577                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6578         check_added_monitors!(nodes[0], 1);
6579         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6580         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6581         let update_msg = msgs::UpdateFailMalformedHTLC{
6582                 channel_id: chan.2,
6583                 htlc_id: 0,
6584                 sha256_of_onion: [1; 32],
6585                 failure_code: 0x8000,
6586         };
6587
6588         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6589
6590         assert!(nodes[0].node.list_channels().is_empty());
6591         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6592         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()));
6593         check_added_monitors!(nodes[0], 1);
6594         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6595 }
6596
6597 #[test]
6598 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6599         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6600
6601         let chanmon_cfgs = create_chanmon_cfgs(2);
6602         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6603         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6604         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6605         create_announced_chan_between_nodes(&nodes, 0, 1);
6606
6607         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6608
6609         nodes[1].node.claim_funds(our_payment_preimage);
6610         check_added_monitors!(nodes[1], 1);
6611         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6612
6613         let events = nodes[1].node.get_and_clear_pending_msg_events();
6614         assert_eq!(events.len(), 1);
6615         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6616                 match events[0] {
6617                         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, .. } } => {
6618                                 assert!(update_add_htlcs.is_empty());
6619                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6620                                 assert!(update_fail_htlcs.is_empty());
6621                                 assert!(update_fail_malformed_htlcs.is_empty());
6622                                 assert!(update_fee.is_none());
6623                                 update_fulfill_htlcs[0].clone()
6624                         },
6625                         _ => panic!("Unexpected event"),
6626                 }
6627         };
6628
6629         update_fulfill_msg.htlc_id = 1;
6630
6631         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6632
6633         assert!(nodes[0].node.list_channels().is_empty());
6634         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6635         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6636         check_added_monitors!(nodes[0], 1);
6637         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6638 }
6639
6640 #[test]
6641 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6642         //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.
6643
6644         let chanmon_cfgs = create_chanmon_cfgs(2);
6645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6648         create_announced_chan_between_nodes(&nodes, 0, 1);
6649
6650         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6651
6652         nodes[1].node.claim_funds(our_payment_preimage);
6653         check_added_monitors!(nodes[1], 1);
6654         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6655
6656         let events = nodes[1].node.get_and_clear_pending_msg_events();
6657         assert_eq!(events.len(), 1);
6658         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6659                 match events[0] {
6660                         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, .. } } => {
6661                                 assert!(update_add_htlcs.is_empty());
6662                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6663                                 assert!(update_fail_htlcs.is_empty());
6664                                 assert!(update_fail_malformed_htlcs.is_empty());
6665                                 assert!(update_fee.is_none());
6666                                 update_fulfill_htlcs[0].clone()
6667                         },
6668                         _ => panic!("Unexpected event"),
6669                 }
6670         };
6671
6672         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6673
6674         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6675
6676         assert!(nodes[0].node.list_channels().is_empty());
6677         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6678         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6679         check_added_monitors!(nodes[0], 1);
6680         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6681 }
6682
6683 #[test]
6684 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6685         //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.
6686
6687         let chanmon_cfgs = create_chanmon_cfgs(2);
6688         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6692
6693         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6694         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6695                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6696         check_added_monitors!(nodes[0], 1);
6697
6698         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6699         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6700
6701         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6702         check_added_monitors!(nodes[1], 0);
6703         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6704
6705         let events = nodes[1].node.get_and_clear_pending_msg_events();
6706
6707         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6708                 match events[0] {
6709                         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, .. } } => {
6710                                 assert!(update_add_htlcs.is_empty());
6711                                 assert!(update_fulfill_htlcs.is_empty());
6712                                 assert!(update_fail_htlcs.is_empty());
6713                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6714                                 assert!(update_fee.is_none());
6715                                 update_fail_malformed_htlcs[0].clone()
6716                         },
6717                         _ => panic!("Unexpected event"),
6718                 }
6719         };
6720         update_msg.failure_code &= !0x8000;
6721         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6722
6723         assert!(nodes[0].node.list_channels().is_empty());
6724         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6725         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6726         check_added_monitors!(nodes[0], 1);
6727         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6728 }
6729
6730 #[test]
6731 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6732         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6733         //    * 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.
6734
6735         let chanmon_cfgs = create_chanmon_cfgs(3);
6736         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6737         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6738         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6739         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6740         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6741
6742         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6743
6744         //First hop
6745         let mut payment_event = {
6746                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6747                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6748                 check_added_monitors!(nodes[0], 1);
6749                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6750                 assert_eq!(events.len(), 1);
6751                 SendEvent::from_event(events.remove(0))
6752         };
6753         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6754         check_added_monitors!(nodes[1], 0);
6755         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6756         expect_pending_htlcs_forwardable!(nodes[1]);
6757         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6758         assert_eq!(events_2.len(), 1);
6759         check_added_monitors!(nodes[1], 1);
6760         payment_event = SendEvent::from_event(events_2.remove(0));
6761         assert_eq!(payment_event.msgs.len(), 1);
6762
6763         //Second Hop
6764         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6765         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6766         check_added_monitors!(nodes[2], 0);
6767         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6768
6769         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6770         assert_eq!(events_3.len(), 1);
6771         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6772                 match events_3[0] {
6773                         MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6774                                 assert!(update_add_htlcs.is_empty());
6775                                 assert!(update_fulfill_htlcs.is_empty());
6776                                 assert!(update_fail_htlcs.is_empty());
6777                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6778                                 assert!(update_fee.is_none());
6779                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6780                         },
6781                         _ => panic!("Unexpected event"),
6782                 }
6783         };
6784
6785         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6786
6787         check_added_monitors!(nodes[1], 0);
6788         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6789         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 }]);
6790         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6791         assert_eq!(events_4.len(), 1);
6792
6793         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6794         match events_4[0] {
6795                 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, .. } } => {
6796                         assert!(update_add_htlcs.is_empty());
6797                         assert!(update_fulfill_htlcs.is_empty());
6798                         assert_eq!(update_fail_htlcs.len(), 1);
6799                         assert!(update_fail_malformed_htlcs.is_empty());
6800                         assert!(update_fee.is_none());
6801                 },
6802                 _ => panic!("Unexpected event"),
6803         };
6804
6805         check_added_monitors!(nodes[1], 1);
6806 }
6807
6808 #[test]
6809 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6810         let chanmon_cfgs = create_chanmon_cfgs(3);
6811         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6812         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6813         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6814         create_announced_chan_between_nodes(&nodes, 0, 1);
6815         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6816
6817         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6818
6819         // First hop
6820         let mut payment_event = {
6821                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6822                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6823                 check_added_monitors!(nodes[0], 1);
6824                 SendEvent::from_node(&nodes[0])
6825         };
6826
6827         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6828         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6829         expect_pending_htlcs_forwardable!(nodes[1]);
6830         check_added_monitors!(nodes[1], 1);
6831         payment_event = SendEvent::from_node(&nodes[1]);
6832         assert_eq!(payment_event.msgs.len(), 1);
6833
6834         // Second Hop
6835         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6836         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6837         check_added_monitors!(nodes[2], 0);
6838         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6839
6840         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6841         assert_eq!(events_3.len(), 1);
6842         match events_3[0] {
6843                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6844                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6845                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6846                         update_msg.failure_code |= 0x2000;
6847
6848                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6849                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6850                 },
6851                 _ => panic!("Unexpected event"),
6852         }
6853
6854         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6855                 vec![HTLCDestination::NextHopChannel {
6856                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6857         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6858         assert_eq!(events_4.len(), 1);
6859         check_added_monitors!(nodes[1], 1);
6860
6861         match events_4[0] {
6862                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6863                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6864                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6865                 },
6866                 _ => panic!("Unexpected event"),
6867         }
6868
6869         let events_5 = nodes[0].node.get_and_clear_pending_events();
6870         assert_eq!(events_5.len(), 2);
6871
6872         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6873         // the node originating the error to its next hop.
6874         match events_5[0] {
6875                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6876                 } => {
6877                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6878                         assert!(is_permanent);
6879                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6880                 },
6881                 _ => panic!("Unexpected event"),
6882         }
6883         match events_5[1] {
6884                 Event::PaymentFailed { payment_hash, .. } => {
6885                         assert_eq!(payment_hash, our_payment_hash);
6886                 },
6887                 _ => panic!("Unexpected event"),
6888         }
6889
6890         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6891 }
6892
6893 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6894         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6895         // 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
6896         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6897
6898         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6899         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6900         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6901         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6902         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6903         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6904
6905         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6906                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
6907
6908         // We route 2 dust-HTLCs between A and B
6909         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6910         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6911         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6912
6913         // Cache one local commitment tx as previous
6914         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6915
6916         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6917         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6918         check_added_monitors!(nodes[1], 0);
6919         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6920         check_added_monitors!(nodes[1], 1);
6921
6922         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6923         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6924         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6925         check_added_monitors!(nodes[0], 1);
6926
6927         // Cache one local commitment tx as lastest
6928         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6929
6930         let events = nodes[0].node.get_and_clear_pending_msg_events();
6931         match events[0] {
6932                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6933                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6934                 },
6935                 _ => panic!("Unexpected event"),
6936         }
6937         match events[1] {
6938                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6939                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6940                 },
6941                 _ => panic!("Unexpected event"),
6942         }
6943
6944         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6945         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6946         if announce_latest {
6947                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6948         } else {
6949                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6950         }
6951
6952         check_closed_broadcast!(nodes[0], true);
6953         check_added_monitors!(nodes[0], 1);
6954         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6955
6956         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6957         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6958         let events = nodes[0].node.get_and_clear_pending_events();
6959         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6960         assert_eq!(events.len(), 4);
6961         let mut first_failed = false;
6962         for event in events {
6963                 match event {
6964                         Event::PaymentPathFailed { payment_hash, .. } => {
6965                                 if payment_hash == payment_hash_1 {
6966                                         assert!(!first_failed);
6967                                         first_failed = true;
6968                                 } else {
6969                                         assert_eq!(payment_hash, payment_hash_2);
6970                                 }
6971                         },
6972                         Event::PaymentFailed { .. } => {}
6973                         _ => panic!("Unexpected event"),
6974                 }
6975         }
6976 }
6977
6978 #[test]
6979 fn test_failure_delay_dust_htlc_local_commitment() {
6980         do_test_failure_delay_dust_htlc_local_commitment(true);
6981         do_test_failure_delay_dust_htlc_local_commitment(false);
6982 }
6983
6984 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6985         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6986         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6987         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6988         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6989         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6990         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6991
6992         let chanmon_cfgs = create_chanmon_cfgs(3);
6993         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6994         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6995         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6996         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6997
6998         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6999                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7000
7001         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7002         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7003
7004         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7005         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7006
7007         // We revoked bs_commitment_tx
7008         if revoked {
7009                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7010                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7011         }
7012
7013         let mut timeout_tx = Vec::new();
7014         if local {
7015                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7016                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7017                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7018                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7019                 expect_payment_failed!(nodes[0], dust_hash, false);
7020
7021                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7022                 check_closed_broadcast!(nodes[0], true);
7023                 check_added_monitors!(nodes[0], 1);
7024                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7025                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7026                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7027                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7028                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7029                 mine_transaction(&nodes[0], &timeout_tx[0]);
7030                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7031                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7032         } else {
7033                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7034                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7035                 check_closed_broadcast!(nodes[0], true);
7036                 check_added_monitors!(nodes[0], 1);
7037                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7038                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7039
7040                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7041                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7042                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7043                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7044                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7045                 // dust HTLC should have been failed.
7046                 expect_payment_failed!(nodes[0], dust_hash, false);
7047
7048                 if !revoked {
7049                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7050                 } else {
7051                         assert_eq!(timeout_tx[0].lock_time.0, 11);
7052                 }
7053                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7054                 mine_transaction(&nodes[0], &timeout_tx[0]);
7055                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7056                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7057                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7058         }
7059 }
7060
7061 #[test]
7062 fn test_sweep_outbound_htlc_failure_update() {
7063         do_test_sweep_outbound_htlc_failure_update(false, true);
7064         do_test_sweep_outbound_htlc_failure_update(false, false);
7065         do_test_sweep_outbound_htlc_failure_update(true, false);
7066 }
7067
7068 #[test]
7069 fn test_user_configurable_csv_delay() {
7070         // We test our channel constructors yield errors when we pass them absurd csv delay
7071
7072         let mut low_our_to_self_config = UserConfig::default();
7073         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7074         let mut high_their_to_self_config = UserConfig::default();
7075         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7076         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7077         let chanmon_cfgs = create_chanmon_cfgs(2);
7078         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7079         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7080         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7081
7082         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7083         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7084                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7085                 &low_our_to_self_config, 0, 42)
7086         {
7087                 match error {
7088                         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())); },
7089                         _ => panic!("Unexpected event"),
7090                 }
7091         } else { assert!(false) }
7092
7093         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7094         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7095         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7096         open_channel.to_self_delay = 200;
7097         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7098                 &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,
7099                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7100         {
7101                 match error {
7102                         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()));  },
7103                         _ => panic!("Unexpected event"),
7104                 }
7105         } else { assert!(false); }
7106
7107         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7108         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7109         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()));
7110         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7111         accept_channel.to_self_delay = 200;
7112         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7113         let reason_msg;
7114         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7115                 match action {
7116                         &ErrorAction::SendErrorMessage { ref msg } => {
7117                                 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()));
7118                                 reason_msg = msg.data.clone();
7119                         },
7120                         _ => { panic!(); }
7121                 }
7122         } else { panic!(); }
7123         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7124
7125         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7126         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7127         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7128         open_channel.to_self_delay = 200;
7129         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7130                 &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,
7131                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7132         {
7133                 match error {
7134                         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())); },
7135                         _ => panic!("Unexpected event"),
7136                 }
7137         } else { assert!(false); }
7138 }
7139
7140 #[test]
7141 fn test_check_htlc_underpaying() {
7142         // Send payment through A -> B but A is maliciously
7143         // sending a probe payment (i.e less than expected value0
7144         // to B, B should refuse payment.
7145
7146         let chanmon_cfgs = create_chanmon_cfgs(2);
7147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7149         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7150
7151         // Create some initial channels
7152         create_announced_chan_between_nodes(&nodes, 0, 1);
7153
7154         let scorer = test_utils::TestScorer::new();
7155         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7156         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7157                 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7158         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7159         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7160                 None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7161         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7162         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7163         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7164                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7165         check_added_monitors!(nodes[0], 1);
7166
7167         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7168         assert_eq!(events.len(), 1);
7169         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7170         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7171         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7172
7173         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7174         // and then will wait a second random delay before failing the HTLC back:
7175         expect_pending_htlcs_forwardable!(nodes[1]);
7176         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7177
7178         // Node 3 is expecting payment of 100_000 but received 10_000,
7179         // it should fail htlc like we didn't know the preimage.
7180         nodes[1].node.process_pending_htlc_forwards();
7181
7182         let events = nodes[1].node.get_and_clear_pending_msg_events();
7183         assert_eq!(events.len(), 1);
7184         let (update_fail_htlc, commitment_signed) = match events[0] {
7185                 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 } } => {
7186                         assert!(update_add_htlcs.is_empty());
7187                         assert!(update_fulfill_htlcs.is_empty());
7188                         assert_eq!(update_fail_htlcs.len(), 1);
7189                         assert!(update_fail_malformed_htlcs.is_empty());
7190                         assert!(update_fee.is_none());
7191                         (update_fail_htlcs[0].clone(), commitment_signed)
7192                 },
7193                 _ => panic!("Unexpected event"),
7194         };
7195         check_added_monitors!(nodes[1], 1);
7196
7197         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7198         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7199
7200         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7201         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7202         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7203         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7204 }
7205
7206 #[test]
7207 fn test_announce_disable_channels() {
7208         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7209         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7210
7211         let chanmon_cfgs = create_chanmon_cfgs(2);
7212         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7213         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7214         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7215
7216         create_announced_chan_between_nodes(&nodes, 0, 1);
7217         create_announced_chan_between_nodes(&nodes, 1, 0);
7218         create_announced_chan_between_nodes(&nodes, 0, 1);
7219
7220         // Disconnect peers
7221         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7222         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7223
7224         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7225                 nodes[0].node.timer_tick_occurred();
7226         }
7227         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7228         assert_eq!(msg_events.len(), 3);
7229         let mut chans_disabled = HashMap::new();
7230         for e in msg_events {
7231                 match e {
7232                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7233                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7234                                 // Check that each channel gets updated exactly once
7235                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7236                                         panic!("Generated ChannelUpdate for wrong chan!");
7237                                 }
7238                         },
7239                         _ => panic!("Unexpected event"),
7240                 }
7241         }
7242         // Reconnect peers
7243         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7244                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7245         }, true).unwrap();
7246         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7247         assert_eq!(reestablish_1.len(), 3);
7248         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7249                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7250         }, false).unwrap();
7251         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7252         assert_eq!(reestablish_2.len(), 3);
7253
7254         // Reestablish chan_1
7255         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7256         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7257         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7258         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7259         // Reestablish chan_2
7260         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7261         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7262         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7263         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7264         // Reestablish chan_3
7265         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7266         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7267         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7268         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7269
7270         for _ in 0..ENABLE_GOSSIP_TICKS {
7271                 nodes[0].node.timer_tick_occurred();
7272         }
7273         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7274         nodes[0].node.timer_tick_occurred();
7275         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7276         assert_eq!(msg_events.len(), 3);
7277         for e in msg_events {
7278                 match e {
7279                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7280                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7281                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7282                                         // Each update should have a higher timestamp than the previous one, replacing
7283                                         // the old one.
7284                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7285                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7286                                 }
7287                         },
7288                         _ => panic!("Unexpected event"),
7289                 }
7290         }
7291         // Check that each channel gets updated exactly once
7292         assert!(chans_disabled.is_empty());
7293 }
7294
7295 #[test]
7296 fn test_bump_penalty_txn_on_revoked_commitment() {
7297         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7298         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7299
7300         let chanmon_cfgs = create_chanmon_cfgs(2);
7301         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7302         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7303         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7304
7305         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7306
7307         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7308         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7309                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7310         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7311         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7312
7313         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7314         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7315         assert_eq!(revoked_txn[0].output.len(), 4);
7316         assert_eq!(revoked_txn[0].input.len(), 1);
7317         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7318         let revoked_txid = revoked_txn[0].txid();
7319
7320         let mut penalty_sum = 0;
7321         for outp in revoked_txn[0].output.iter() {
7322                 if outp.script_pubkey.is_v0_p2wsh() {
7323                         penalty_sum += outp.value;
7324                 }
7325         }
7326
7327         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7328         let header_114 = connect_blocks(&nodes[1], 14);
7329
7330         // Actually revoke tx by claiming a HTLC
7331         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7332         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7333         check_added_monitors!(nodes[1], 1);
7334
7335         // One or more justice tx should have been broadcast, check it
7336         let penalty_1;
7337         let feerate_1;
7338         {
7339                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7340                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7341                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7342                 assert_eq!(node_txn[0].output.len(), 1);
7343                 check_spends!(node_txn[0], revoked_txn[0]);
7344                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7345                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7346                 penalty_1 = node_txn[0].txid();
7347                 node_txn.clear();
7348         };
7349
7350         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7351         connect_blocks(&nodes[1], 15);
7352         let mut penalty_2 = penalty_1;
7353         let mut feerate_2 = 0;
7354         {
7355                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7356                 assert_eq!(node_txn.len(), 1);
7357                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7358                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7359                         assert_eq!(node_txn[0].output.len(), 1);
7360                         check_spends!(node_txn[0], revoked_txn[0]);
7361                         penalty_2 = node_txn[0].txid();
7362                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7363                         assert_ne!(penalty_2, penalty_1);
7364                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7365                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7366                         // Verify 25% bump heuristic
7367                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7368                         node_txn.clear();
7369                 }
7370         }
7371         assert_ne!(feerate_2, 0);
7372
7373         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7374         connect_blocks(&nodes[1], 1);
7375         let penalty_3;
7376         let mut feerate_3 = 0;
7377         {
7378                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7379                 assert_eq!(node_txn.len(), 1);
7380                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7381                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7382                         assert_eq!(node_txn[0].output.len(), 1);
7383                         check_spends!(node_txn[0], revoked_txn[0]);
7384                         penalty_3 = node_txn[0].txid();
7385                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7386                         assert_ne!(penalty_3, penalty_2);
7387                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7388                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7389                         // Verify 25% bump heuristic
7390                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7391                         node_txn.clear();
7392                 }
7393         }
7394         assert_ne!(feerate_3, 0);
7395
7396         nodes[1].node.get_and_clear_pending_events();
7397         nodes[1].node.get_and_clear_pending_msg_events();
7398 }
7399
7400 #[test]
7401 fn test_bump_penalty_txn_on_revoked_htlcs() {
7402         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7403         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7404
7405         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7406         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7407         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7408         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7409         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7410
7411         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7412         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7413         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7414         let scorer = test_utils::TestScorer::new();
7415         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7416         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7417         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7418                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7419         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7420         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7421         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7422         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7423                 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7424         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7425
7426         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7427         assert_eq!(revoked_local_txn[0].input.len(), 1);
7428         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7429
7430         // Revoke local commitment tx
7431         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7432
7433         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7434         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7435         check_closed_broadcast!(nodes[1], true);
7436         check_added_monitors!(nodes[1], 1);
7437         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7438         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7439
7440         let revoked_htlc_txn = {
7441                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7442                 assert_eq!(txn.len(), 2);
7443
7444                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7445                 assert_eq!(txn[0].input.len(), 1);
7446                 check_spends!(txn[0], revoked_local_txn[0]);
7447
7448                 assert_eq!(txn[1].input.len(), 1);
7449                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7450                 assert_eq!(txn[1].output.len(), 1);
7451                 check_spends!(txn[1], revoked_local_txn[0]);
7452
7453                 txn
7454         };
7455
7456         // Broadcast set of revoked txn on A
7457         let hash_128 = connect_blocks(&nodes[0], 40);
7458         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7459         connect_block(&nodes[0], &block_11);
7460         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7461         connect_block(&nodes[0], &block_129);
7462         let events = nodes[0].node.get_and_clear_pending_events();
7463         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7464         match events.last().unwrap() {
7465                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7466                 _ => panic!("Unexpected event"),
7467         }
7468         let first;
7469         let feerate_1;
7470         let penalty_txn;
7471         {
7472                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7473                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7474                 // Verify claim tx are spending revoked HTLC txn
7475
7476                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7477                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7478                 // which are included in the same block (they are broadcasted because we scan the
7479                 // transactions linearly and generate claims as we go, they likely should be removed in the
7480                 // future).
7481                 assert_eq!(node_txn[0].input.len(), 1);
7482                 check_spends!(node_txn[0], revoked_local_txn[0]);
7483                 assert_eq!(node_txn[1].input.len(), 1);
7484                 check_spends!(node_txn[1], revoked_local_txn[0]);
7485                 assert_eq!(node_txn[2].input.len(), 1);
7486                 check_spends!(node_txn[2], revoked_local_txn[0]);
7487
7488                 // Each of the three justice transactions claim a separate (single) output of the three
7489                 // available, which we check here:
7490                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7491                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7492                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7493
7494                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7495                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7496
7497                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7498                 // output, checked above).
7499                 assert_eq!(node_txn[3].input.len(), 2);
7500                 assert_eq!(node_txn[3].output.len(), 1);
7501                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7502
7503                 first = node_txn[3].txid();
7504                 // Store both feerates for later comparison
7505                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7506                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7507                 penalty_txn = vec![node_txn[2].clone()];
7508                 node_txn.clear();
7509         }
7510
7511         // Connect one more block to see if bumped penalty are issued for HTLC txn
7512         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7513         connect_block(&nodes[0], &block_130);
7514         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7515         connect_block(&nodes[0], &block_131);
7516
7517         // Few more blocks to confirm penalty txn
7518         connect_blocks(&nodes[0], 4);
7519         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7520         let header_144 = connect_blocks(&nodes[0], 9);
7521         let node_txn = {
7522                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7523                 assert_eq!(node_txn.len(), 1);
7524
7525                 assert_eq!(node_txn[0].input.len(), 2);
7526                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7527                 // Verify bumped tx is different and 25% bump heuristic
7528                 assert_ne!(first, node_txn[0].txid());
7529                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7530                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7531                 assert!(feerate_2 * 100 > feerate_1 * 125);
7532                 let txn = vec![node_txn[0].clone()];
7533                 node_txn.clear();
7534                 txn
7535         };
7536         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7537         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7538         connect_blocks(&nodes[0], 20);
7539         {
7540                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7541                 // We verify than no new transaction has been broadcast because previously
7542                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7543                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7544                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7545                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7546                 // up bumped justice generation.
7547                 assert_eq!(node_txn.len(), 0);
7548                 node_txn.clear();
7549         }
7550         check_closed_broadcast!(nodes[0], true);
7551         check_added_monitors!(nodes[0], 1);
7552 }
7553
7554 #[test]
7555 fn test_bump_penalty_txn_on_remote_commitment() {
7556         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7557         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7558
7559         // Create 2 HTLCs
7560         // Provide preimage for one
7561         // Check aggregation
7562
7563         let chanmon_cfgs = create_chanmon_cfgs(2);
7564         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7565         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7566         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7567
7568         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7569         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7570         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7571
7572         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7573         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7574         assert_eq!(remote_txn[0].output.len(), 4);
7575         assert_eq!(remote_txn[0].input.len(), 1);
7576         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7577
7578         // Claim a HTLC without revocation (provide B monitor with preimage)
7579         nodes[1].node.claim_funds(payment_preimage);
7580         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7581         mine_transaction(&nodes[1], &remote_txn[0]);
7582         check_added_monitors!(nodes[1], 2);
7583         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7584
7585         // One or more claim tx should have been broadcast, check it
7586         let timeout;
7587         let preimage;
7588         let preimage_bump;
7589         let feerate_timeout;
7590         let feerate_preimage;
7591         {
7592                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7593                 // 3 transactions including:
7594                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7595                 assert_eq!(node_txn.len(), 3);
7596                 assert_eq!(node_txn[0].input.len(), 1);
7597                 assert_eq!(node_txn[1].input.len(), 1);
7598                 assert_eq!(node_txn[2].input.len(), 1);
7599                 check_spends!(node_txn[0], remote_txn[0]);
7600                 check_spends!(node_txn[1], remote_txn[0]);
7601                 check_spends!(node_txn[2], remote_txn[0]);
7602
7603                 preimage = node_txn[0].txid();
7604                 let index = node_txn[0].input[0].previous_output.vout;
7605                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7606                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7607
7608                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7609                         (node_txn[2].clone(), node_txn[1].clone())
7610                 } else {
7611                         (node_txn[1].clone(), node_txn[2].clone())
7612                 };
7613
7614                 preimage_bump = preimage_bump_tx;
7615                 check_spends!(preimage_bump, remote_txn[0]);
7616                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7617
7618                 timeout = timeout_tx.txid();
7619                 let index = timeout_tx.input[0].previous_output.vout;
7620                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7621                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7622
7623                 node_txn.clear();
7624         };
7625         assert_ne!(feerate_timeout, 0);
7626         assert_ne!(feerate_preimage, 0);
7627
7628         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7629         connect_blocks(&nodes[1], 1);
7630         {
7631                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7632                 assert_eq!(node_txn.len(), 1);
7633                 assert_eq!(node_txn[0].input.len(), 1);
7634                 assert_eq!(preimage_bump.input.len(), 1);
7635                 check_spends!(node_txn[0], remote_txn[0]);
7636                 check_spends!(preimage_bump, remote_txn[0]);
7637
7638                 let index = preimage_bump.input[0].previous_output.vout;
7639                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7640                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7641                 assert!(new_feerate * 100 > feerate_timeout * 125);
7642                 assert_ne!(timeout, preimage_bump.txid());
7643
7644                 let index = node_txn[0].input[0].previous_output.vout;
7645                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7646                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7647                 assert!(new_feerate * 100 > feerate_preimage * 125);
7648                 assert_ne!(preimage, node_txn[0].txid());
7649
7650                 node_txn.clear();
7651         }
7652
7653         nodes[1].node.get_and_clear_pending_events();
7654         nodes[1].node.get_and_clear_pending_msg_events();
7655 }
7656
7657 #[test]
7658 fn test_counterparty_raa_skip_no_crash() {
7659         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7660         // commitment transaction, we would have happily carried on and provided them the next
7661         // commitment transaction based on one RAA forward. This would probably eventually have led to
7662         // channel closure, but it would not have resulted in funds loss. Still, our
7663         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7664         // check simply that the channel is closed in response to such an RAA, but don't check whether
7665         // we decide to punish our counterparty for revoking their funds (as we don't currently
7666         // implement that).
7667         let chanmon_cfgs = create_chanmon_cfgs(2);
7668         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7669         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7670         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7671         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7672
7673         let per_commitment_secret;
7674         let next_per_commitment_point;
7675         {
7676                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7677                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7678                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7679                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7680                 ).flatten().unwrap().get_signer();
7681
7682                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7683
7684                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7685                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7686                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7687
7688                 // Must revoke without gaps
7689                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7690                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7691
7692                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7693                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7694                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7695         }
7696
7697         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7698                 &msgs::RevokeAndACK {
7699                         channel_id,
7700                         per_commitment_secret,
7701                         next_per_commitment_point,
7702                         #[cfg(taproot)]
7703                         next_local_nonce: None,
7704                 });
7705         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7706         check_added_monitors!(nodes[1], 1);
7707         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7708                 , [nodes[0].node.get_our_node_id()], 100000);
7709 }
7710
7711 #[test]
7712 fn test_bump_txn_sanitize_tracking_maps() {
7713         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7714         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7715
7716         let chanmon_cfgs = create_chanmon_cfgs(2);
7717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7719         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7720
7721         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7722         // Lock HTLC in both directions
7723         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7724         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7725
7726         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7727         assert_eq!(revoked_local_txn[0].input.len(), 1);
7728         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7729
7730         // Revoke local commitment tx
7731         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7732
7733         // Broadcast set of revoked txn on A
7734         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7735         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7736         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7737
7738         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7739         check_closed_broadcast!(nodes[0], true);
7740         check_added_monitors!(nodes[0], 1);
7741         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7742         let penalty_txn = {
7743                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7744                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7745                 check_spends!(node_txn[0], revoked_local_txn[0]);
7746                 check_spends!(node_txn[1], revoked_local_txn[0]);
7747                 check_spends!(node_txn[2], revoked_local_txn[0]);
7748                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7749                 node_txn.clear();
7750                 penalty_txn
7751         };
7752         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7753         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7754         {
7755                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7756                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7757                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7758         }
7759 }
7760
7761 #[test]
7762 fn test_channel_conf_timeout() {
7763         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7764         // confirm within 2016 blocks, as recommended by BOLT 2.
7765         let chanmon_cfgs = create_chanmon_cfgs(2);
7766         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7767         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7768         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7769
7770         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7771
7772         // The outbound node should wait forever for confirmation:
7773         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7774         // copied here instead of directly referencing the constant.
7775         connect_blocks(&nodes[0], 2016);
7776         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7777
7778         // The inbound node should fail the channel after exactly 2016 blocks
7779         connect_blocks(&nodes[1], 2015);
7780         check_added_monitors!(nodes[1], 0);
7781         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7782
7783         connect_blocks(&nodes[1], 1);
7784         check_added_monitors!(nodes[1], 1);
7785         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7786         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7787         assert_eq!(close_ev.len(), 1);
7788         match close_ev[0] {
7789                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7790                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7791                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7792                 },
7793                 _ => panic!("Unexpected event"),
7794         }
7795 }
7796
7797 #[test]
7798 fn test_override_channel_config() {
7799         let chanmon_cfgs = create_chanmon_cfgs(2);
7800         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7801         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7802         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7803
7804         // Node0 initiates a channel to node1 using the override config.
7805         let mut override_config = UserConfig::default();
7806         override_config.channel_handshake_config.our_to_self_delay = 200;
7807
7808         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7809
7810         // Assert the channel created by node0 is using the override config.
7811         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7812         assert_eq!(res.channel_flags, 0);
7813         assert_eq!(res.to_self_delay, 200);
7814 }
7815
7816 #[test]
7817 fn test_override_0msat_htlc_minimum() {
7818         let mut zero_config = UserConfig::default();
7819         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7820         let chanmon_cfgs = create_chanmon_cfgs(2);
7821         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7822         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7823         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7824
7825         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7826         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7827         assert_eq!(res.htlc_minimum_msat, 1);
7828
7829         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7830         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7831         assert_eq!(res.htlc_minimum_msat, 1);
7832 }
7833
7834 #[test]
7835 fn test_channel_update_has_correct_htlc_maximum_msat() {
7836         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7837         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7838         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7839         // 90% of the `channel_value`.
7840         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7841
7842         let mut config_30_percent = UserConfig::default();
7843         config_30_percent.channel_handshake_config.announced_channel = true;
7844         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7845         let mut config_50_percent = UserConfig::default();
7846         config_50_percent.channel_handshake_config.announced_channel = true;
7847         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7848         let mut config_95_percent = UserConfig::default();
7849         config_95_percent.channel_handshake_config.announced_channel = true;
7850         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7851         let mut config_100_percent = UserConfig::default();
7852         config_100_percent.channel_handshake_config.announced_channel = true;
7853         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7854
7855         let chanmon_cfgs = create_chanmon_cfgs(4);
7856         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7857         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)]);
7858         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7859
7860         let channel_value_satoshis = 100000;
7861         let channel_value_msat = channel_value_satoshis * 1000;
7862         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7863         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7864         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7865
7866         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7867         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7868
7869         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7870         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7871         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7872         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7873         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7874         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7875
7876         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7877         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7878         // `channel_value`.
7879         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7880         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7881         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7882         // `channel_value`.
7883         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7884 }
7885
7886 #[test]
7887 fn test_manually_accept_inbound_channel_request() {
7888         let mut manually_accept_conf = UserConfig::default();
7889         manually_accept_conf.manually_accept_inbound_channels = true;
7890         let chanmon_cfgs = create_chanmon_cfgs(2);
7891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7893         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7894
7895         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7896         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7897
7898         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7899
7900         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7901         // accepting the inbound channel request.
7902         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7903
7904         let events = nodes[1].node.get_and_clear_pending_events();
7905         match events[0] {
7906                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7907                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7908                 }
7909                 _ => panic!("Unexpected event"),
7910         }
7911
7912         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7913         assert_eq!(accept_msg_ev.len(), 1);
7914
7915         match accept_msg_ev[0] {
7916                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7917                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7918                 }
7919                 _ => panic!("Unexpected event"),
7920         }
7921
7922         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7923
7924         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7925         assert_eq!(close_msg_ev.len(), 1);
7926
7927         let events = nodes[1].node.get_and_clear_pending_events();
7928         match events[0] {
7929                 Event::ChannelClosed { user_channel_id, .. } => {
7930                         assert_eq!(user_channel_id, 23);
7931                 }
7932                 _ => panic!("Unexpected event"),
7933         }
7934 }
7935
7936 #[test]
7937 fn test_manually_reject_inbound_channel_request() {
7938         let mut manually_accept_conf = UserConfig::default();
7939         manually_accept_conf.manually_accept_inbound_channels = true;
7940         let chanmon_cfgs = create_chanmon_cfgs(2);
7941         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7942         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7943         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7944
7945         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7946         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7947
7948         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7949
7950         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7951         // rejecting the inbound channel request.
7952         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7953
7954         let events = nodes[1].node.get_and_clear_pending_events();
7955         match events[0] {
7956                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7957                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7958                 }
7959                 _ => panic!("Unexpected event"),
7960         }
7961
7962         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7963         assert_eq!(close_msg_ev.len(), 1);
7964
7965         match close_msg_ev[0] {
7966                 MessageSendEvent::HandleError { ref node_id, .. } => {
7967                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7968                 }
7969                 _ => panic!("Unexpected event"),
7970         }
7971
7972         // There should be no more events to process, as the channel was never opened.
7973         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7974 }
7975
7976 #[test]
7977 fn test_can_not_accept_inbound_channel_twice() {
7978         let mut manually_accept_conf = UserConfig::default();
7979         manually_accept_conf.manually_accept_inbound_channels = true;
7980         let chanmon_cfgs = create_chanmon_cfgs(2);
7981         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7982         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7983         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7984
7985         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7986         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7987
7988         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7989
7990         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7991         // accepting the inbound channel request.
7992         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7993
7994         let events = nodes[1].node.get_and_clear_pending_events();
7995         match events[0] {
7996                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7997                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7998                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7999                         match api_res {
8000                                 Err(APIError::APIMisuseError { err }) => {
8001                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8002                                 },
8003                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8004                                 Err(e) => panic!("Unexpected Error {:?}", e),
8005                         }
8006                 }
8007                 _ => panic!("Unexpected event"),
8008         }
8009
8010         // Ensure that the channel wasn't closed after attempting to accept it twice.
8011         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8012         assert_eq!(accept_msg_ev.len(), 1);
8013
8014         match accept_msg_ev[0] {
8015                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8016                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8017                 }
8018                 _ => panic!("Unexpected event"),
8019         }
8020 }
8021
8022 #[test]
8023 fn test_can_not_accept_unknown_inbound_channel() {
8024         let chanmon_cfg = create_chanmon_cfgs(2);
8025         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8026         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8027         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8028
8029         let unknown_channel_id = ChannelId::new_zero();
8030         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8031         match api_res {
8032                 Err(APIError::APIMisuseError { err }) => {
8033                         assert_eq!(err, "No such channel awaiting to be accepted.");
8034                 },
8035                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8036                 Err(e) => panic!("Unexpected Error: {:?}", e),
8037         }
8038 }
8039
8040 #[test]
8041 fn test_onion_value_mpp_set_calculation() {
8042         // Test that we use the onion value `amt_to_forward` when
8043         // calculating whether we've reached the `total_msat` of an MPP
8044         // by having a routing node forward more than `amt_to_forward`
8045         // and checking that the receiving node doesn't generate
8046         // a PaymentClaimable event too early
8047         let node_count = 4;
8048         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8049         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8050         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8051         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8052
8053         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8054         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8055         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8056         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8057
8058         let total_msat = 100_000;
8059         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8060         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8061         let sample_path = route.paths.pop().unwrap();
8062
8063         let mut path_1 = sample_path.clone();
8064         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8065         path_1.hops[0].short_channel_id = chan_1_id;
8066         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8067         path_1.hops[1].short_channel_id = chan_3_id;
8068         path_1.hops[1].fee_msat = 100_000;
8069         route.paths.push(path_1);
8070
8071         let mut path_2 = sample_path.clone();
8072         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8073         path_2.hops[0].short_channel_id = chan_2_id;
8074         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8075         path_2.hops[1].short_channel_id = chan_4_id;
8076         path_2.hops[1].fee_msat = 1_000;
8077         route.paths.push(path_2);
8078
8079         // Send payment
8080         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8081         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8082                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8083         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8084                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8085         check_added_monitors!(nodes[0], expected_paths.len());
8086
8087         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8088         assert_eq!(events.len(), expected_paths.len());
8089
8090         // First path
8091         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8092         let mut payment_event = SendEvent::from_event(ev);
8093         let mut prev_node = &nodes[0];
8094
8095         for (idx, &node) in expected_paths[0].iter().enumerate() {
8096                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8097
8098                 if idx == 0 { // routing node
8099                         let session_priv = [3; 32];
8100                         let height = nodes[0].best_block_info().1;
8101                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8102                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8103                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8104                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8105                         // Edit amt_to_forward to simulate the sender having set
8106                         // the final amount and the routing node taking less fee
8107                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8108                                 *amt_msat = 99_000;
8109                         } else { panic!() }
8110                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8111                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8112                 }
8113
8114                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8115                 check_added_monitors!(node, 0);
8116                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8117                 expect_pending_htlcs_forwardable!(node);
8118
8119                 if idx == 0 {
8120                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8121                         assert_eq!(events_2.len(), 1);
8122                         check_added_monitors!(node, 1);
8123                         payment_event = SendEvent::from_event(events_2.remove(0));
8124                         assert_eq!(payment_event.msgs.len(), 1);
8125                 } else {
8126                         let events_2 = node.node.get_and_clear_pending_events();
8127                         assert!(events_2.is_empty());
8128                 }
8129
8130                 prev_node = node;
8131         }
8132
8133         // Second path
8134         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8135         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8136
8137         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8138 }
8139
8140 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8141
8142         let routing_node_count = msat_amounts.len();
8143         let node_count = routing_node_count + 2;
8144
8145         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8146         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8147         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8148         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8149
8150         let src_idx = 0;
8151         let dst_idx = 1;
8152
8153         // Create channels for each amount
8154         let mut expected_paths = Vec::with_capacity(routing_node_count);
8155         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8156         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8157         for i in 0..routing_node_count {
8158                 let routing_node = 2 + i;
8159                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8160                 src_chan_ids.push(src_chan_id);
8161                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8162                 dst_chan_ids.push(dst_chan_id);
8163                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8164                 expected_paths.push(path);
8165         }
8166         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8167
8168         // Create a route for each amount
8169         let example_amount = 100000;
8170         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);
8171         let sample_path = route.paths.pop().unwrap();
8172         for i in 0..routing_node_count {
8173                 let routing_node = 2 + i;
8174                 let mut path = sample_path.clone();
8175                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8176                 path.hops[0].short_channel_id = src_chan_ids[i];
8177                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8178                 path.hops[1].short_channel_id = dst_chan_ids[i];
8179                 path.hops[1].fee_msat = msat_amounts[i];
8180                 route.paths.push(path);
8181         }
8182
8183         // Send payment with manually set total_msat
8184         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8185         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8186                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8187         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8188                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8189         check_added_monitors!(nodes[src_idx], expected_paths.len());
8190
8191         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8192         assert_eq!(events.len(), expected_paths.len());
8193         let mut amount_received = 0;
8194         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8195                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8196
8197                 let current_path_amount = msat_amounts[path_idx];
8198                 amount_received += current_path_amount;
8199                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8200                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8201         }
8202
8203         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8204 }
8205
8206 #[test]
8207 fn test_overshoot_mpp() {
8208         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8209         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8210 }
8211
8212 #[test]
8213 fn test_simple_mpp() {
8214         // Simple test of sending a multi-path payment.
8215         let chanmon_cfgs = create_chanmon_cfgs(4);
8216         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8217         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8218         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8219
8220         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8221         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8222         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8223         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8224
8225         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8226         let path = route.paths[0].clone();
8227         route.paths.push(path);
8228         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8229         route.paths[0].hops[0].short_channel_id = chan_1_id;
8230         route.paths[0].hops[1].short_channel_id = chan_3_id;
8231         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8232         route.paths[1].hops[0].short_channel_id = chan_2_id;
8233         route.paths[1].hops[1].short_channel_id = chan_4_id;
8234         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8235         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8236 }
8237
8238 #[test]
8239 fn test_preimage_storage() {
8240         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8241         let chanmon_cfgs = create_chanmon_cfgs(2);
8242         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8243         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8244         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8245
8246         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8247
8248         {
8249                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8250                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8251                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8252                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8253                 check_added_monitors!(nodes[0], 1);
8254                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8255                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8256                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8257                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8258         }
8259         // Note that after leaving the above scope we have no knowledge of any arguments or return
8260         // values from previous calls.
8261         expect_pending_htlcs_forwardable!(nodes[1]);
8262         let events = nodes[1].node.get_and_clear_pending_events();
8263         assert_eq!(events.len(), 1);
8264         match events[0] {
8265                 Event::PaymentClaimable { ref purpose, .. } => {
8266                         match &purpose {
8267                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8268                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8269                                 },
8270                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8271                         }
8272                 },
8273                 _ => panic!("Unexpected event"),
8274         }
8275 }
8276
8277 #[test]
8278 fn test_bad_secret_hash() {
8279         // Simple test of unregistered payment hash/invalid payment secret handling
8280         let chanmon_cfgs = create_chanmon_cfgs(2);
8281         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8282         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8283         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8284
8285         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8286
8287         let random_payment_hash = PaymentHash([42; 32]);
8288         let random_payment_secret = PaymentSecret([43; 32]);
8289         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8290         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8291
8292         // All the below cases should end up being handled exactly identically, so we macro the
8293         // resulting events.
8294         macro_rules! handle_unknown_invalid_payment_data {
8295                 ($payment_hash: expr) => {
8296                         check_added_monitors!(nodes[0], 1);
8297                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8298                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8299                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8300                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8301
8302                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8303                         // again to process the pending backwards-failure of the HTLC
8304                         expect_pending_htlcs_forwardable!(nodes[1]);
8305                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8306                         check_added_monitors!(nodes[1], 1);
8307
8308                         // We should fail the payment back
8309                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8310                         match events.pop().unwrap() {
8311                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8312                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8313                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8314                                 },
8315                                 _ => panic!("Unexpected event"),
8316                         }
8317                 }
8318         }
8319
8320         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8321         // Error data is the HTLC value (100,000) and current block height
8322         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8323
8324         // Send a payment with the right payment hash but the wrong payment secret
8325         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8326                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8327         handle_unknown_invalid_payment_data!(our_payment_hash);
8328         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8329
8330         // Send a payment with a random payment hash, but the right payment secret
8331         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8332                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8333         handle_unknown_invalid_payment_data!(random_payment_hash);
8334         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8335
8336         // Send a payment with a random payment hash and random payment secret
8337         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8338                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8339         handle_unknown_invalid_payment_data!(random_payment_hash);
8340         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8341 }
8342
8343 #[test]
8344 fn test_update_err_monitor_lockdown() {
8345         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8346         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8347         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8348         // error.
8349         //
8350         // This scenario may happen in a watchtower setup, where watchtower process a block height
8351         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8352         // commitment at same time.
8353
8354         let chanmon_cfgs = create_chanmon_cfgs(2);
8355         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8356         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8357         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8358
8359         // Create some initial channel
8360         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8361         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8362
8363         // Rebalance the network to generate htlc in the two directions
8364         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8365
8366         // Route a HTLC from node 0 to node 1 (but don't settle)
8367         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8368
8369         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8370         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8371         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8372         let persister = test_utils::TestPersister::new();
8373         let watchtower = {
8374                 let new_monitor = {
8375                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8376                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8377                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8378                         assert!(new_monitor == *monitor);
8379                         new_monitor
8380                 };
8381                 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);
8382                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8383                 watchtower
8384         };
8385         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8386         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8387         // transaction lock time requirements here.
8388         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8389         watchtower.chain_monitor.block_connected(&block, 200);
8390
8391         // Try to update ChannelMonitor
8392         nodes[1].node.claim_funds(preimage);
8393         check_added_monitors!(nodes[1], 1);
8394         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8395
8396         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8397         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8398         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8399         {
8400                 let mut node_0_per_peer_lock;
8401                 let mut node_0_peer_state_lock;
8402                 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) {
8403                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8404                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8405                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8406                         } else { assert!(false); }
8407                 } else {
8408                         assert!(false);
8409                 }
8410         }
8411         // Our local monitor is in-sync and hasn't processed yet timeout
8412         check_added_monitors!(nodes[0], 1);
8413         let events = nodes[0].node.get_and_clear_pending_events();
8414         assert_eq!(events.len(), 1);
8415 }
8416
8417 #[test]
8418 fn test_concurrent_monitor_claim() {
8419         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8420         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8421         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8422         // state N+1 confirms. Alice claims output from state N+1.
8423
8424         let chanmon_cfgs = create_chanmon_cfgs(2);
8425         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8426         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8427         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8428
8429         // Create some initial channel
8430         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8431         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8432
8433         // Rebalance the network to generate htlc in the two directions
8434         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8435
8436         // Route a HTLC from node 0 to node 1 (but don't settle)
8437         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8438
8439         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8440         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8441         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8442         let persister = test_utils::TestPersister::new();
8443         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8444                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8445         );
8446         let watchtower_alice = {
8447                 let new_monitor = {
8448                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8449                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8450                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8451                         assert!(new_monitor == *monitor);
8452                         new_monitor
8453                 };
8454                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8455                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8456                 watchtower
8457         };
8458         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8459         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8460         // requirements here.
8461         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8462         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8463         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8464
8465         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8466         let alice_state = {
8467                 let mut txn = alice_broadcaster.txn_broadcast();
8468                 assert_eq!(txn.len(), 2);
8469                 txn.remove(0)
8470         };
8471
8472         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8473         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8474         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8475         let persister = test_utils::TestPersister::new();
8476         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8477         let watchtower_bob = {
8478                 let new_monitor = {
8479                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8480                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8481                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8482                         assert!(new_monitor == *monitor);
8483                         new_monitor
8484                 };
8485                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8486                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8487                 watchtower
8488         };
8489         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8490
8491         // Route another payment to generate another update with still previous HTLC pending
8492         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8493         nodes[1].node.send_payment_with_route(&route, payment_hash,
8494                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8495         check_added_monitors!(nodes[1], 1);
8496
8497         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8498         assert_eq!(updates.update_add_htlcs.len(), 1);
8499         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8500         {
8501                 let mut node_0_per_peer_lock;
8502                 let mut node_0_peer_state_lock;
8503                 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) {
8504                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8505                                 // Watchtower Alice should already have seen the block and reject the update
8506                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8507                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8508                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8509                         } else { assert!(false); }
8510                 } else {
8511                         assert!(false);
8512                 }
8513         }
8514         // Our local monitor is in-sync and hasn't processed yet timeout
8515         check_added_monitors!(nodes[0], 1);
8516
8517         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8518         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8519
8520         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8521         let bob_state_y;
8522         {
8523                 let mut txn = bob_broadcaster.txn_broadcast();
8524                 assert_eq!(txn.len(), 2);
8525                 bob_state_y = txn.remove(0);
8526         };
8527
8528         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8529         let height = HTLC_TIMEOUT_BROADCAST + 1;
8530         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8531         check_closed_broadcast(&nodes[0], 1, true);
8532         check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8533                 [nodes[1].node.get_our_node_id()], 100000);
8534         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8535         check_added_monitors(&nodes[0], 1);
8536         {
8537                 let htlc_txn = alice_broadcaster.txn_broadcast();
8538                 assert_eq!(htlc_txn.len(), 2);
8539                 check_spends!(htlc_txn[0], bob_state_y);
8540                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8541                 // it. However, she should, because it now has an invalid parent.
8542                 check_spends!(htlc_txn[1], alice_state);
8543         }
8544 }
8545
8546 #[test]
8547 fn test_pre_lockin_no_chan_closed_update() {
8548         // Test that if a peer closes a channel in response to a funding_created message we don't
8549         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8550         // message).
8551         //
8552         // Doing so would imply a channel monitor update before the initial channel monitor
8553         // registration, violating our API guarantees.
8554         //
8555         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8556         // then opening a second channel with the same funding output as the first (which is not
8557         // rejected because the first channel does not exist in the ChannelManager) and closing it
8558         // before receiving funding_signed.
8559         let chanmon_cfgs = create_chanmon_cfgs(2);
8560         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8561         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8562         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8563
8564         // Create an initial channel
8565         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8566         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8567         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8568         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8569         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8570
8571         // Move the first channel through the funding flow...
8572         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8573
8574         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8575         check_added_monitors!(nodes[0], 0);
8576
8577         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8578         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8579         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8580         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8581         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8582                 [nodes[1].node.get_our_node_id(); 2], 100000);
8583 }
8584
8585 #[test]
8586 fn test_htlc_no_detection() {
8587         // This test is a mutation to underscore the detection logic bug we had
8588         // before #653. HTLC value routed is above the remaining balance, thus
8589         // inverting HTLC and `to_remote` output. HTLC will come second and
8590         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8591         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8592         // outputs order detection for correct spending children filtring.
8593
8594         let chanmon_cfgs = create_chanmon_cfgs(2);
8595         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8596         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8597         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8598
8599         // Create some initial channels
8600         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8601
8602         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8603         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8604         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8605         assert_eq!(local_txn[0].input.len(), 1);
8606         assert_eq!(local_txn[0].output.len(), 3);
8607         check_spends!(local_txn[0], chan_1.3);
8608
8609         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8610         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8611         connect_block(&nodes[0], &block);
8612         // We deliberately connect the local tx twice as this should provoke a failure calling
8613         // this test before #653 fix.
8614         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8615         check_closed_broadcast!(nodes[0], true);
8616         check_added_monitors!(nodes[0], 1);
8617         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8618         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8619
8620         let htlc_timeout = {
8621                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8622                 assert_eq!(node_txn.len(), 1);
8623                 assert_eq!(node_txn[0].input.len(), 1);
8624                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8625                 check_spends!(node_txn[0], local_txn[0]);
8626                 node_txn[0].clone()
8627         };
8628
8629         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8630         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8631         expect_payment_failed!(nodes[0], our_payment_hash, false);
8632 }
8633
8634 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8635         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8636         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8637         // Carol, Alice would be the upstream node, and Carol the downstream.)
8638         //
8639         // Steps of the test:
8640         // 1) Alice sends a HTLC to Carol through Bob.
8641         // 2) Carol doesn't settle the HTLC.
8642         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8643         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8644         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8645         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8646         // 5) Carol release the preimage to Bob off-chain.
8647         // 6) Bob claims the offered output on the broadcasted commitment.
8648         let chanmon_cfgs = create_chanmon_cfgs(3);
8649         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8650         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8651         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8652
8653         // Create some initial channels
8654         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8655         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8656
8657         // Steps (1) and (2):
8658         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8659         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8660
8661         // Check that Alice's commitment transaction now contains an output for this HTLC.
8662         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8663         check_spends!(alice_txn[0], chan_ab.3);
8664         assert_eq!(alice_txn[0].output.len(), 2);
8665         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8666         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8667         assert_eq!(alice_txn.len(), 2);
8668
8669         // Steps (3) and (4):
8670         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8671         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8672         let mut force_closing_node = 0; // Alice force-closes
8673         let mut counterparty_node = 1; // Bob if Alice force-closes
8674
8675         // Bob force-closes
8676         if !broadcast_alice {
8677                 force_closing_node = 1;
8678                 counterparty_node = 0;
8679         }
8680         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8681         check_closed_broadcast!(nodes[force_closing_node], true);
8682         check_added_monitors!(nodes[force_closing_node], 1);
8683         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8684         if go_onchain_before_fulfill {
8685                 let txn_to_broadcast = match broadcast_alice {
8686                         true => alice_txn.clone(),
8687                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8688                 };
8689                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8690                 if broadcast_alice {
8691                         check_closed_broadcast!(nodes[1], true);
8692                         check_added_monitors!(nodes[1], 1);
8693                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8694                 }
8695         }
8696
8697         // Step (5):
8698         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8699         // process of removing the HTLC from their commitment transactions.
8700         nodes[2].node.claim_funds(payment_preimage);
8701         check_added_monitors!(nodes[2], 1);
8702         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8703
8704         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8705         assert!(carol_updates.update_add_htlcs.is_empty());
8706         assert!(carol_updates.update_fail_htlcs.is_empty());
8707         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8708         assert!(carol_updates.update_fee.is_none());
8709         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8710
8711         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8712         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8713         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8714         if !go_onchain_before_fulfill && broadcast_alice {
8715                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8716                 assert_eq!(events.len(), 1);
8717                 match events[0] {
8718                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8719                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8720                         },
8721                         _ => panic!("Unexpected event"),
8722                 };
8723         }
8724         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8725         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8726         // Carol<->Bob's updated commitment transaction info.
8727         check_added_monitors!(nodes[1], 2);
8728
8729         let events = nodes[1].node.get_and_clear_pending_msg_events();
8730         assert_eq!(events.len(), 2);
8731         let bob_revocation = match events[0] {
8732                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8733                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8734                         (*msg).clone()
8735                 },
8736                 _ => panic!("Unexpected event"),
8737         };
8738         let bob_updates = match events[1] {
8739                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8740                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8741                         (*updates).clone()
8742                 },
8743                 _ => panic!("Unexpected event"),
8744         };
8745
8746         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8747         check_added_monitors!(nodes[2], 1);
8748         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8749         check_added_monitors!(nodes[2], 1);
8750
8751         let events = nodes[2].node.get_and_clear_pending_msg_events();
8752         assert_eq!(events.len(), 1);
8753         let carol_revocation = match events[0] {
8754                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8755                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8756                         (*msg).clone()
8757                 },
8758                 _ => panic!("Unexpected event"),
8759         };
8760         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8761         check_added_monitors!(nodes[1], 1);
8762
8763         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8764         // here's where we put said channel's commitment tx on-chain.
8765         let mut txn_to_broadcast = alice_txn.clone();
8766         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8767         if !go_onchain_before_fulfill {
8768                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8769                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8770                 if broadcast_alice {
8771                         check_closed_broadcast!(nodes[1], true);
8772                         check_added_monitors!(nodes[1], 1);
8773                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8774                 }
8775                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8776                 if broadcast_alice {
8777                         assert_eq!(bob_txn.len(), 1);
8778                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8779                 } else {
8780                         assert_eq!(bob_txn.len(), 2);
8781                         check_spends!(bob_txn[0], chan_ab.3);
8782                 }
8783         }
8784
8785         // Step (6):
8786         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8787         // broadcasted commitment transaction.
8788         {
8789                 let script_weight = match broadcast_alice {
8790                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8791                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8792                 };
8793                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8794                 // Bob force-closed and broadcasts the commitment transaction along with a
8795                 // HTLC-output-claiming transaction.
8796                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8797                 if broadcast_alice {
8798                         assert_eq!(bob_txn.len(), 1);
8799                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8800                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8801                 } else {
8802                         assert_eq!(bob_txn.len(), 2);
8803                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8804                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8805                 }
8806         }
8807 }
8808
8809 #[test]
8810 fn test_onchain_htlc_settlement_after_close() {
8811         do_test_onchain_htlc_settlement_after_close(true, true);
8812         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8813         do_test_onchain_htlc_settlement_after_close(true, false);
8814         do_test_onchain_htlc_settlement_after_close(false, false);
8815 }
8816
8817 #[test]
8818 fn test_duplicate_temporary_channel_id_from_different_peers() {
8819         // Tests that we can accept two different `OpenChannel` requests with the same
8820         // `temporary_channel_id`, as long as they are from different peers.
8821         let chanmon_cfgs = create_chanmon_cfgs(3);
8822         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8823         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8824         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8825
8826         // Create an first channel channel
8827         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8828         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8829
8830         // Create an second channel
8831         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8832         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8833
8834         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8835         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8836         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8837
8838         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8839         // `temporary_channel_id` as they are from different peers.
8840         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8841         {
8842                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8843                 assert_eq!(events.len(), 1);
8844                 match &events[0] {
8845                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8846                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8847                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8848                         },
8849                         _ => panic!("Unexpected event"),
8850                 }
8851         }
8852
8853         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8854         {
8855                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8856                 assert_eq!(events.len(), 1);
8857                 match &events[0] {
8858                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8859                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8860                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8861                         },
8862                         _ => panic!("Unexpected event"),
8863                 }
8864         }
8865 }
8866
8867 #[test]
8868 fn test_duplicate_chan_id() {
8869         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8870         // already open we reject it and keep the old channel.
8871         //
8872         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8873         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8874         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8875         // updating logic for the existing channel.
8876         let chanmon_cfgs = create_chanmon_cfgs(2);
8877         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8878         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8879         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8880
8881         // Create an initial channel
8882         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8883         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8884         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8885         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()));
8886
8887         // Try to create a second channel with the same temporary_channel_id as the first and check
8888         // that it is rejected.
8889         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8890         {
8891                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8892                 assert_eq!(events.len(), 1);
8893                 match events[0] {
8894                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8895                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8896                                 // first (valid) and second (invalid) channels are closed, given they both have
8897                                 // the same non-temporary channel_id. However, currently we do not, so we just
8898                                 // move forward with it.
8899                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8900                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8901                         },
8902                         _ => panic!("Unexpected event"),
8903                 }
8904         }
8905
8906         // Move the first channel through the funding flow...
8907         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8908
8909         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8910         check_added_monitors!(nodes[0], 0);
8911
8912         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8913         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8914         {
8915                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8916                 assert_eq!(added_monitors.len(), 1);
8917                 assert_eq!(added_monitors[0].0, funding_output);
8918                 added_monitors.clear();
8919         }
8920         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8921
8922         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8923
8924         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8925         let channel_id = funding_outpoint.to_channel_id();
8926
8927         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8928         // temporary one).
8929
8930         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8931         // Technically this is allowed by the spec, but we don't support it and there's little reason
8932         // to. Still, it shouldn't cause any other issues.
8933         open_chan_msg.temporary_channel_id = channel_id;
8934         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8935         {
8936                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8937                 assert_eq!(events.len(), 1);
8938                 match events[0] {
8939                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8940                                 // Technically, at this point, nodes[1] would be justified in thinking both
8941                                 // channels are closed, but currently we do not, so we just move forward with it.
8942                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8943                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8944                         },
8945                         _ => panic!("Unexpected event"),
8946                 }
8947         }
8948
8949         // Now try to create a second channel which has a duplicate funding output.
8950         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8951         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8952         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8953         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()));
8954         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8955
8956         let (_, funding_created) = {
8957                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8958                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8959                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8960                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8961                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8962                 // channelmanager in a possibly nonsense state instead).
8963                 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8964                 let logger = test_utils::TestLogger::new();
8965                 as_chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8966         };
8967         check_added_monitors!(nodes[0], 0);
8968         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8969         // At this point we'll look up if the channel_id is present and immediately fail the channel
8970         // without trying to persist the `ChannelMonitor`.
8971         check_added_monitors!(nodes[1], 0);
8972
8973         // ...still, nodes[1] will reject the duplicate channel.
8974         {
8975                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8976                 assert_eq!(events.len(), 1);
8977                 match events[0] {
8978                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8979                                 // Technically, at this point, nodes[1] would be justified in thinking both
8980                                 // channels are closed, but currently we do not, so we just move forward with it.
8981                                 assert_eq!(msg.channel_id, channel_id);
8982                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8983                         },
8984                         _ => panic!("Unexpected event"),
8985                 }
8986         }
8987
8988         // finally, finish creating the original channel and send a payment over it to make sure
8989         // everything is functional.
8990         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8991         {
8992                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8993                 assert_eq!(added_monitors.len(), 1);
8994                 assert_eq!(added_monitors[0].0, funding_output);
8995                 added_monitors.clear();
8996         }
8997         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8998
8999         let events_4 = nodes[0].node.get_and_clear_pending_events();
9000         assert_eq!(events_4.len(), 0);
9001         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9002         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9003
9004         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9005         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9006         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9007
9008         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9009 }
9010
9011 #[test]
9012 fn test_error_chans_closed() {
9013         // Test that we properly handle error messages, closing appropriate channels.
9014         //
9015         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9016         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9017         // we can test various edge cases around it to ensure we don't regress.
9018         let chanmon_cfgs = create_chanmon_cfgs(3);
9019         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9020         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9021         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9022
9023         // Create some initial channels
9024         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9025         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9026         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9027
9028         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9029         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9030         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9031
9032         // Closing a channel from a different peer has no effect
9033         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9034         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9035
9036         // Closing one channel doesn't impact others
9037         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9038         check_added_monitors!(nodes[0], 1);
9039         check_closed_broadcast!(nodes[0], false);
9040         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9041                 [nodes[1].node.get_our_node_id()], 100000);
9042         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9043         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9044         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);
9045         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);
9046
9047         // A null channel ID should close all channels
9048         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9049         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9050         check_added_monitors!(nodes[0], 2);
9051         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9052                 [nodes[1].node.get_our_node_id(); 2], 100000);
9053         let events = nodes[0].node.get_and_clear_pending_msg_events();
9054         assert_eq!(events.len(), 2);
9055         match events[0] {
9056                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9057                         assert_eq!(msg.contents.flags & 2, 2);
9058                 },
9059                 _ => panic!("Unexpected event"),
9060         }
9061         match events[1] {
9062                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9063                         assert_eq!(msg.contents.flags & 2, 2);
9064                 },
9065                 _ => panic!("Unexpected event"),
9066         }
9067         // Note that at this point users of a standard PeerHandler will end up calling
9068         // peer_disconnected.
9069         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9070         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9071
9072         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9073         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9074         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9075 }
9076
9077 #[test]
9078 fn test_invalid_funding_tx() {
9079         // Test that we properly handle invalid funding transactions sent to us from a peer.
9080         //
9081         // Previously, all other major lightning implementations had failed to properly sanitize
9082         // funding transactions from their counterparties, leading to a multi-implementation critical
9083         // security vulnerability (though we always sanitized properly, we've previously had
9084         // un-released crashes in the sanitization process).
9085         //
9086         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9087         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9088         // gave up on it. We test this here by generating such a transaction.
9089         let chanmon_cfgs = create_chanmon_cfgs(2);
9090         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9091         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9092         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9093
9094         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9095         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()));
9096         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()));
9097
9098         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9099
9100         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9101         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9102         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9103         // its length.
9104         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9105         let wit_program_script: Script = wit_program.into();
9106         for output in tx.output.iter_mut() {
9107                 // Make the confirmed funding transaction have a bogus script_pubkey
9108                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9109         }
9110
9111         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9112         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()));
9113         check_added_monitors!(nodes[1], 1);
9114         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9115
9116         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()));
9117         check_added_monitors!(nodes[0], 1);
9118         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9119
9120         let events_1 = nodes[0].node.get_and_clear_pending_events();
9121         assert_eq!(events_1.len(), 0);
9122
9123         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9124         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9125         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9126
9127         let expected_err = "funding tx had wrong script/value or output index";
9128         confirm_transaction_at(&nodes[1], &tx, 1);
9129         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9130                 [nodes[0].node.get_our_node_id()], 100000);
9131         check_added_monitors!(nodes[1], 1);
9132         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9133         assert_eq!(events_2.len(), 1);
9134         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9135                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9136                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9137                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9138                 } else { panic!(); }
9139         } else { panic!(); }
9140         assert_eq!(nodes[1].node.list_channels().len(), 0);
9141
9142         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9143         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9144         // as its not 32 bytes long.
9145         let mut spend_tx = Transaction {
9146                 version: 2i32, lock_time: PackedLockTime::ZERO,
9147                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9148                         previous_output: BitcoinOutPoint {
9149                                 txid: tx.txid(),
9150                                 vout: idx as u32,
9151                         },
9152                         script_sig: Script::new(),
9153                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9154                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9155                 }).collect(),
9156                 output: vec![TxOut {
9157                         value: 1000,
9158                         script_pubkey: Script::new(),
9159                 }]
9160         };
9161         check_spends!(spend_tx, tx);
9162         mine_transaction(&nodes[1], &spend_tx);
9163 }
9164
9165 #[test]
9166 fn test_coinbase_funding_tx() {
9167         // Miners are able to fund channels directly from coinbase transactions, however
9168         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9169         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9170         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9171         //
9172         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9173         // immediately operational after opening.
9174         let chanmon_cfgs = create_chanmon_cfgs(2);
9175         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9176         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9177         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9178
9179         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9180         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9181
9182         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9183         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9184
9185         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9186
9187         // Create the coinbase funding transaction.
9188         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9189
9190         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9191         check_added_monitors!(nodes[0], 0);
9192         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9193
9194         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9195         check_added_monitors!(nodes[1], 1);
9196         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9197
9198         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9199
9200         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9201         check_added_monitors!(nodes[0], 1);
9202
9203         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9204         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9205
9206         // Starting at height 0, we "confirm" the coinbase at height 1.
9207         confirm_transaction_at(&nodes[0], &tx, 1);
9208         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9209         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9210         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9211         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9212         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9213         connect_blocks(&nodes[0], 1);
9214         // There should now be a `channel_ready` which can be handled.
9215         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()));
9216
9217         confirm_transaction_at(&nodes[1], &tx, 1);
9218         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9219         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9220         connect_blocks(&nodes[1], 1);
9221         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9222         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9223 }
9224
9225 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9226         // In the first version of the chain::Confirm interface, after a refactor was made to not
9227         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9228         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9229         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9230         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9231         // spending transaction until height N+1 (or greater). This was due to the way
9232         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9233         // spending transaction at the height the input transaction was confirmed at, not whether we
9234         // should broadcast a spending transaction at the current height.
9235         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9236         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9237         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9238         // until we learned about an additional block.
9239         //
9240         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9241         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9242         let chanmon_cfgs = create_chanmon_cfgs(3);
9243         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9244         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9245         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9246         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9247
9248         create_announced_chan_between_nodes(&nodes, 0, 1);
9249         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9250         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9251         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9252         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9253
9254         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9255         check_closed_broadcast!(nodes[1], true);
9256         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9257         check_added_monitors!(nodes[1], 1);
9258         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9259         assert_eq!(node_txn.len(), 1);
9260
9261         let conf_height = nodes[1].best_block_info().1;
9262         if !test_height_before_timelock {
9263                 connect_blocks(&nodes[1], 24 * 6);
9264         }
9265         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9266                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9267         if test_height_before_timelock {
9268                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9269                 // generate any events or broadcast any transactions
9270                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9271                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9272         } else {
9273                 // We should broadcast an HTLC transaction spending our funding transaction first
9274                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9275                 assert_eq!(spending_txn.len(), 2);
9276                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9277                 check_spends!(spending_txn[1], node_txn[0]);
9278                 // We should also generate a SpendableOutputs event with the to_self output (as its
9279                 // timelock is up).
9280                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9281                 assert_eq!(descriptor_spend_txn.len(), 1);
9282
9283                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9284                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9285                 // additional block built on top of the current chain.
9286                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9287                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9288                 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 }]);
9289                 check_added_monitors!(nodes[1], 1);
9290
9291                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9292                 assert!(updates.update_add_htlcs.is_empty());
9293                 assert!(updates.update_fulfill_htlcs.is_empty());
9294                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9295                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9296                 assert!(updates.update_fee.is_none());
9297                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9298                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9299                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9300         }
9301 }
9302
9303 #[test]
9304 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9305         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9306         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9307 }
9308
9309 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9310         let chanmon_cfgs = create_chanmon_cfgs(2);
9311         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9312         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9313         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9314
9315         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9316
9317         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9318                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9319         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9320
9321         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9322
9323         {
9324                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9325                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9326                 check_added_monitors!(nodes[0], 1);
9327                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9328                 assert_eq!(events.len(), 1);
9329                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9330                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9331                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9332         }
9333         expect_pending_htlcs_forwardable!(nodes[1]);
9334         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9335
9336         {
9337                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9338                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9339                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9340                 check_added_monitors!(nodes[0], 1);
9341                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9342                 assert_eq!(events.len(), 1);
9343                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9344                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9345                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9346                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9347                 // assume the second is a privacy attack (no longer particularly relevant
9348                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9349                 // the first HTLC delivered above.
9350         }
9351
9352         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9353         nodes[1].node.process_pending_htlc_forwards();
9354
9355         if test_for_second_fail_panic {
9356                 // Now we go fail back the first HTLC from the user end.
9357                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9358
9359                 let expected_destinations = vec![
9360                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9361                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9362                 ];
9363                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9364                 nodes[1].node.process_pending_htlc_forwards();
9365
9366                 check_added_monitors!(nodes[1], 1);
9367                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9368                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9369
9370                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9371                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9372                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9373
9374                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9375                 assert_eq!(failure_events.len(), 4);
9376                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9377                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9378                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9379                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9380         } else {
9381                 // Let the second HTLC fail and claim the first
9382                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9383                 nodes[1].node.process_pending_htlc_forwards();
9384
9385                 check_added_monitors!(nodes[1], 1);
9386                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9387                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9388                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9389
9390                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9391
9392                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9393         }
9394 }
9395
9396 #[test]
9397 fn test_dup_htlc_second_fail_panic() {
9398         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9399         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9400         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9401         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9402         do_test_dup_htlc_second_rejected(true);
9403 }
9404
9405 #[test]
9406 fn test_dup_htlc_second_rejected() {
9407         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9408         // simply reject the second HTLC but are still able to claim the first HTLC.
9409         do_test_dup_htlc_second_rejected(false);
9410 }
9411
9412 #[test]
9413 fn test_inconsistent_mpp_params() {
9414         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9415         // such HTLC and allow the second to stay.
9416         let chanmon_cfgs = create_chanmon_cfgs(4);
9417         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9418         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9419         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9420
9421         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9422         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9423         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9424         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9425
9426         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9427                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9428         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9429         assert_eq!(route.paths.len(), 2);
9430         route.paths.sort_by(|path_a, _| {
9431                 // Sort the path so that the path through nodes[1] comes first
9432                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9433                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9434         });
9435
9436         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9437
9438         let cur_height = nodes[0].best_block_info().1;
9439         let payment_id = PaymentId([42; 32]);
9440
9441         let session_privs = {
9442                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9443                 // ultimately have, just not right away.
9444                 let mut dup_route = route.clone();
9445                 dup_route.paths.push(route.paths[1].clone());
9446                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9447                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9448         };
9449         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9450                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9451                 &None, session_privs[0]).unwrap();
9452         check_added_monitors!(nodes[0], 1);
9453
9454         {
9455                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9456                 assert_eq!(events.len(), 1);
9457                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9458         }
9459         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9460
9461         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9462                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9463         check_added_monitors!(nodes[0], 1);
9464
9465         {
9466                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9467                 assert_eq!(events.len(), 1);
9468                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9469
9470                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9471                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9472
9473                 expect_pending_htlcs_forwardable!(nodes[2]);
9474                 check_added_monitors!(nodes[2], 1);
9475
9476                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9477                 assert_eq!(events.len(), 1);
9478                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9479
9480                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9481                 check_added_monitors!(nodes[3], 0);
9482                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9483
9484                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9485                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9486                 // post-payment_secrets) and fail back the new HTLC.
9487         }
9488         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9489         nodes[3].node.process_pending_htlc_forwards();
9490         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9491         nodes[3].node.process_pending_htlc_forwards();
9492
9493         check_added_monitors!(nodes[3], 1);
9494
9495         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9496         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9497         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9498
9499         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 }]);
9500         check_added_monitors!(nodes[2], 1);
9501
9502         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9503         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9504         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9505
9506         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9507
9508         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9509                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9510                 &None, session_privs[2]).unwrap();
9511         check_added_monitors!(nodes[0], 1);
9512
9513         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9514         assert_eq!(events.len(), 1);
9515         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9516
9517         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9518         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9519 }
9520
9521 #[test]
9522 fn test_double_partial_claim() {
9523         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9524         // time out, the sender resends only some of the MPP parts, then the user processes the
9525         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9526         // amount.
9527         let chanmon_cfgs = create_chanmon_cfgs(4);
9528         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9529         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9530         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9531
9532         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9533         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9534         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9535         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9536
9537         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9538         assert_eq!(route.paths.len(), 2);
9539         route.paths.sort_by(|path_a, _| {
9540                 // Sort the path so that the path through nodes[1] comes first
9541                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9542                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9543         });
9544
9545         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9546         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9547         // amount of time to respond to.
9548
9549         // Connect some blocks to time out the payment
9550         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9551         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9552
9553         let failed_destinations = vec![
9554                 HTLCDestination::FailedPayment { payment_hash },
9555                 HTLCDestination::FailedPayment { payment_hash },
9556         ];
9557         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9558
9559         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9560
9561         // nodes[1] now retries one of the two paths...
9562         nodes[0].node.send_payment_with_route(&route, payment_hash,
9563                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9564         check_added_monitors!(nodes[0], 2);
9565
9566         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9567         assert_eq!(events.len(), 2);
9568         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9569         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9570
9571         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9572         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9573         nodes[3].node.claim_funds(payment_preimage);
9574         check_added_monitors!(nodes[3], 0);
9575         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9576 }
9577
9578 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9579 #[derive(Clone, Copy, PartialEq)]
9580 enum ExposureEvent {
9581         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9582         AtHTLCForward,
9583         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9584         AtHTLCReception,
9585         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9586         AtUpdateFeeOutbound,
9587 }
9588
9589 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9590         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9591         // policy.
9592         //
9593         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9594         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9595         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9596         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9597         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9598         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9599         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9600         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9601
9602         let chanmon_cfgs = create_chanmon_cfgs(2);
9603         let mut config = test_default_channel_config();
9604         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9605                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9606                 // to get roughly the same initial value as the default setting when this test was
9607                 // originally written.
9608                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9609         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9612         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9613
9614         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9615         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9616         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9617         open_channel.max_accepted_htlcs = 60;
9618         if on_holder_tx {
9619                 open_channel.dust_limit_satoshis = 546;
9620         }
9621         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9622         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9623         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9624
9625         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9626
9627         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9628
9629         if on_holder_tx {
9630                 let mut node_0_per_peer_lock;
9631                 let mut node_0_peer_state_lock;
9632                 let mut chan = get_outbound_v1_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9633                 chan.context.holder_dust_limit_satoshis = 546;
9634         }
9635
9636         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9637         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()));
9638         check_added_monitors!(nodes[1], 1);
9639         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9640
9641         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()));
9642         check_added_monitors!(nodes[0], 1);
9643         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9644
9645         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9646         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9647         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9648
9649         // Fetch a route in advance as we will be unable to once we're unable to send.
9650         let (mut route, payment_hash, _, payment_secret) =
9651                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9652
9653         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9654                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9655                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9656                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9657                 (chan.context().get_dust_buffer_feerate(None) as u64,
9658                 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9659         };
9660         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;
9661         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9662
9663         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;
9664         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9665
9666         let dust_htlc_on_counterparty_tx: u64 = 4;
9667         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9668
9669         if on_holder_tx {
9670                 if dust_outbound_balance {
9671                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9672                         // Outbound dust balance: 4372 sats
9673                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9674                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9675                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9676                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9677                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9678                         }
9679                 } else {
9680                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9681                         // Inbound dust balance: 4372 sats
9682                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9683                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9684                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9685                         }
9686                 }
9687         } else {
9688                 if dust_outbound_balance {
9689                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9690                         // Outbound dust balance: 5000 sats
9691                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9692                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9693                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9694                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9695                         }
9696                 } else {
9697                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9698                         // Inbound dust balance: 5000 sats
9699                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9700                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9701                         }
9702                 }
9703         }
9704
9705         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9706                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9707                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9708                 // With default dust exposure: 5000 sats
9709                 if on_holder_tx {
9710                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9711                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9712                                 ), true, APIError::ChannelUnavailable { .. }, {});
9713                 } else {
9714                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9715                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9716                                 ), true, APIError::ChannelUnavailable { .. }, {});
9717                 }
9718         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9719                 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 });
9720                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9721                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9722                 check_added_monitors!(nodes[1], 1);
9723                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9724                 assert_eq!(events.len(), 1);
9725                 let payment_event = SendEvent::from_event(events.remove(0));
9726                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9727                 // With default dust exposure: 5000 sats
9728                 if on_holder_tx {
9729                         // Outbound dust balance: 6399 sats
9730                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9731                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9732                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
9733                 } else {
9734                         // Outbound dust balance: 5200 sats
9735                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9736                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9737                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9738                                         max_dust_htlc_exposure_msat), 1);
9739                 }
9740         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9741                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9742                 // For the multiplier dust exposure limit, since it scales with feerate,
9743                 // we need to add a lot of HTLCs that will become dust at the new feerate
9744                 // to cross the threshold.
9745                 for _ in 0..20 {
9746                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9747                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9748                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9749                 }
9750                 {
9751                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9752                         *feerate_lock = *feerate_lock * 10;
9753                 }
9754                 nodes[0].node.timer_tick_occurred();
9755                 check_added_monitors!(nodes[0], 1);
9756                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9757         }
9758
9759         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9760         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9761         added_monitors.clear();
9762 }
9763
9764 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9765         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9766         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9767         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9768         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9769         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9770         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9771         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9772         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9773         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9774         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9775         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9776         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9777 }
9778
9779 #[test]
9780 fn test_max_dust_htlc_exposure() {
9781         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9782         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9783 }
9784
9785 #[test]
9786 fn test_non_final_funding_tx() {
9787         let chanmon_cfgs = create_chanmon_cfgs(2);
9788         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9789         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9790         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9791
9792         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9793         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9794         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9795         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9796         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9797
9798         let best_height = nodes[0].node.best_block.read().unwrap().height();
9799
9800         let chan_id = *nodes[0].network_chan_count.borrow();
9801         let events = nodes[0].node.get_and_clear_pending_events();
9802         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9803         assert_eq!(events.len(), 1);
9804         let mut tx = match events[0] {
9805                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9806                         // Timelock the transaction _beyond_ the best client height + 1.
9807                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9808                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9809                         }]}
9810                 },
9811                 _ => panic!("Unexpected event"),
9812         };
9813         // Transaction should fail as it's evaluated as non-final for propagation.
9814         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9815                 Err(APIError::APIMisuseError { err }) => {
9816                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9817                 },
9818                 _ => panic!()
9819         }
9820
9821         // However, transaction should be accepted if it's in a +1 headroom from best block.
9822         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9823         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9824         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9825 }
9826
9827 #[test]
9828 fn accept_busted_but_better_fee() {
9829         // If a peer sends us a fee update that is too low, but higher than our previous channel
9830         // feerate, we should accept it. In the future we may want to consider closing the channel
9831         // later, but for now we only accept the update.
9832         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9833         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9834         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9835         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9836
9837         create_chan_between_nodes(&nodes[0], &nodes[1]);
9838
9839         // Set nodes[1] to expect 5,000 sat/kW.
9840         {
9841                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9842                 *feerate_lock = 5000;
9843         }
9844
9845         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9846         {
9847                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9848                 *feerate_lock = 1000;
9849         }
9850         nodes[0].node.timer_tick_occurred();
9851         check_added_monitors!(nodes[0], 1);
9852
9853         let events = nodes[0].node.get_and_clear_pending_msg_events();
9854         assert_eq!(events.len(), 1);
9855         match events[0] {
9856                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9857                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9858                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9859                 },
9860                 _ => panic!("Unexpected event"),
9861         };
9862
9863         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9864         // it.
9865         {
9866                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9867                 *feerate_lock = 2000;
9868         }
9869         nodes[0].node.timer_tick_occurred();
9870         check_added_monitors!(nodes[0], 1);
9871
9872         let events = nodes[0].node.get_and_clear_pending_msg_events();
9873         assert_eq!(events.len(), 1);
9874         match events[0] {
9875                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9876                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9877                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9878                 },
9879                 _ => panic!("Unexpected event"),
9880         };
9881
9882         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9883         // channel.
9884         {
9885                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9886                 *feerate_lock = 1000;
9887         }
9888         nodes[0].node.timer_tick_occurred();
9889         check_added_monitors!(nodes[0], 1);
9890
9891         let events = nodes[0].node.get_and_clear_pending_msg_events();
9892         assert_eq!(events.len(), 1);
9893         match events[0] {
9894                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9895                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9896                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9897                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9898                                 [nodes[0].node.get_our_node_id()], 100000);
9899                         check_closed_broadcast!(nodes[1], true);
9900                         check_added_monitors!(nodes[1], 1);
9901                 },
9902                 _ => panic!("Unexpected event"),
9903         };
9904 }
9905
9906 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9907         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9910         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9911         let min_final_cltv_expiry_delta = 120;
9912         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9913                 min_final_cltv_expiry_delta - 2 };
9914         let recv_value = 100_000;
9915
9916         create_chan_between_nodes(&nodes[0], &nodes[1]);
9917
9918         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9919         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9920                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9921                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9922                 (payment_hash, payment_preimage, payment_secret)
9923         } else {
9924                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9925                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9926         };
9927         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9928         nodes[0].node.send_payment_with_route(&route, payment_hash,
9929                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9930         check_added_monitors!(nodes[0], 1);
9931         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9932         assert_eq!(events.len(), 1);
9933         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9934         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9935         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9936         expect_pending_htlcs_forwardable!(nodes[1]);
9937
9938         if valid_delta {
9939                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9940                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9941
9942                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9943         } else {
9944                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9945
9946                 check_added_monitors!(nodes[1], 1);
9947
9948                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9949                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9950                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9951
9952                 expect_payment_failed!(nodes[0], payment_hash, true);
9953         }
9954 }
9955
9956 #[test]
9957 fn test_payment_with_custom_min_cltv_expiry_delta() {
9958         do_payment_with_custom_min_final_cltv_expiry(false, false);
9959         do_payment_with_custom_min_final_cltv_expiry(false, true);
9960         do_payment_with_custom_min_final_cltv_expiry(true, false);
9961         do_payment_with_custom_min_final_cltv_expiry(true, true);
9962 }
9963
9964 #[test]
9965 fn test_disconnects_peer_awaiting_response_ticks() {
9966         // Tests that nodes which are awaiting on a response critical for channel responsiveness
9967         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9968         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9969         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9970         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9971         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9972
9973         // Asserts a disconnect event is queued to the user.
9974         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9975                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9976                         if let MessageSendEvent::HandleError { action, .. } = event {
9977                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9978                                         Some(())
9979                                 } else {
9980                                         None
9981                                 }
9982                         } else {
9983                                 None
9984                         }
9985                 );
9986                 assert_eq!(disconnect_event.is_some(), should_disconnect);
9987         };
9988
9989         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9990         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9991         let check_disconnect = |node: &Node| {
9992                 // No disconnect without any timer ticks.
9993                 check_disconnect_event(node, false);
9994
9995                 // No disconnect with 1 timer tick less than required.
9996                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9997                         node.node.timer_tick_occurred();
9998                         check_disconnect_event(node, false);
9999                 }
10000
10001                 // Disconnect after reaching the required ticks.
10002                 node.node.timer_tick_occurred();
10003                 check_disconnect_event(node, true);
10004
10005                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10006                 node.node.timer_tick_occurred();
10007                 check_disconnect_event(node, true);
10008         };
10009
10010         create_chan_between_nodes(&nodes[0], &nodes[1]);
10011
10012         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10013         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10014         nodes[0].node.timer_tick_occurred();
10015         check_added_monitors!(&nodes[0], 1);
10016         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10017         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10018         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10019         check_added_monitors!(&nodes[1], 1);
10020
10021         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10022         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10023         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10024         check_added_monitors!(&nodes[0], 1);
10025         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10026         check_added_monitors(&nodes[0], 1);
10027
10028         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10029         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10030         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10031         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10032         check_disconnect(&nodes[1]);
10033
10034         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10035         //
10036         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10037         // final `RevokeAndACK` to Bob to complete it.
10038         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10039         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10040         let bob_init = msgs::Init {
10041                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10042         };
10043         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10044         let alice_init = msgs::Init {
10045                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10046         };
10047         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10048
10049         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10050         // received Bob's yet, so she should disconnect him after reaching
10051         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10052         let alice_channel_reestablish = get_event_msg!(
10053                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10054         );
10055         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10056         check_disconnect(&nodes[0]);
10057
10058         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10059         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10060                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10061                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10062                         Some(msg.clone())
10063                 } else {
10064                         None
10065                 }
10066         ).unwrap();
10067         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10068
10069         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10070         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10071                 nodes[0].node.timer_tick_occurred();
10072                 check_disconnect_event(&nodes[0], false);
10073         }
10074
10075         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10076         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10077         check_disconnect(&nodes[1]);
10078
10079         // Finally, have Bob process the last message.
10080         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10081         check_added_monitors(&nodes[1], 1);
10082
10083         // At this point, neither node should attempt to disconnect each other, since they aren't
10084         // waiting on any messages.
10085         for node in &nodes {
10086                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10087                         node.node.timer_tick_occurred();
10088                         check_disconnect_event(node, false);
10089                 }
10090         }
10091 }
10092
10093 #[test]
10094 fn test_remove_expired_outbound_unfunded_channels() {
10095         let chanmon_cfgs = create_chanmon_cfgs(2);
10096         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10097         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10098         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10099
10100         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10101         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10102         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10103         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10104         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10105
10106         let events = nodes[0].node.get_and_clear_pending_events();
10107         assert_eq!(events.len(), 1);
10108         match events[0] {
10109                 Event::FundingGenerationReady { .. } => (),
10110                 _ => panic!("Unexpected event"),
10111         };
10112
10113         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10114         let check_outbound_channel_existence = |should_exist: bool| {
10115                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10116                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10117                 assert_eq!(chan_lock.outbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10118         };
10119
10120         // Channel should exist without any timer ticks.
10121         check_outbound_channel_existence(true);
10122
10123         // Channel should exist with 1 timer tick less than required.
10124         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10125                 nodes[0].node.timer_tick_occurred();
10126                 check_outbound_channel_existence(true)
10127         }
10128
10129         // Remove channel after reaching the required ticks.
10130         nodes[0].node.timer_tick_occurred();
10131         check_outbound_channel_existence(false);
10132
10133         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10134         assert_eq!(msg_events.len(), 1);
10135         match msg_events[0] {
10136                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10137                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10138                 },
10139                 _ => panic!("Unexpected event"),
10140         }
10141         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10142 }
10143
10144 #[test]
10145 fn test_remove_expired_inbound_unfunded_channels() {
10146         let chanmon_cfgs = create_chanmon_cfgs(2);
10147         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10148         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10149         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10150
10151         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10152         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10153         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10154         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10155         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10156
10157         let events = nodes[0].node.get_and_clear_pending_events();
10158         assert_eq!(events.len(), 1);
10159         match events[0] {
10160                 Event::FundingGenerationReady { .. } => (),
10161                 _ => panic!("Unexpected event"),
10162         };
10163
10164         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10165         let check_inbound_channel_existence = |should_exist: bool| {
10166                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10167                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10168                 assert_eq!(chan_lock.inbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10169         };
10170
10171         // Channel should exist without any timer ticks.
10172         check_inbound_channel_existence(true);
10173
10174         // Channel should exist with 1 timer tick less than required.
10175         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10176                 nodes[1].node.timer_tick_occurred();
10177                 check_inbound_channel_existence(true)
10178         }
10179
10180         // Remove channel after reaching the required ticks.
10181         nodes[1].node.timer_tick_occurred();
10182         check_inbound_channel_existence(false);
10183
10184         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10185         assert_eq!(msg_events.len(), 1);
10186         match msg_events[0] {
10187                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10188                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10189                 },
10190                 _ => panic!("Unexpected event"),
10191         }
10192         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10193 }
10194
10195 fn do_test_multi_post_event_actions(do_reload: bool) {
10196         // Tests handling multiple post-Event actions at once.
10197         // There is specific code in ChannelManager to handle channels where multiple post-Event
10198         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10199         //
10200         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10201         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10202         // - one from an RAA and one from an inbound commitment_signed.
10203         let chanmon_cfgs = create_chanmon_cfgs(3);
10204         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10205         let (persister, chain_monitor);
10206         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10207         let nodes_0_deserialized;
10208         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10209
10210         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10211         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10212
10213         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10214         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10215
10216         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10217         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10218
10219         nodes[1].node.claim_funds(our_payment_preimage);
10220         check_added_monitors!(nodes[1], 1);
10221         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10222
10223         nodes[2].node.claim_funds(payment_preimage_2);
10224         check_added_monitors!(nodes[2], 1);
10225         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10226
10227         for dest in &[1, 2] {
10228                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10229                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10230                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10231                 check_added_monitors(&nodes[0], 0);
10232         }
10233
10234         let (route, payment_hash_3, _, payment_secret_3) =
10235                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10236         let payment_id = PaymentId(payment_hash_3.0);
10237         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10238                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10239         check_added_monitors(&nodes[1], 1);
10240
10241         let send_event = SendEvent::from_node(&nodes[1]);
10242         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10243         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10244         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10245
10246         if do_reload {
10247                 let nodes_0_serialized = nodes[0].node.encode();
10248                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10249                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10250                 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);
10251
10252                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10253                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10254
10255                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10256                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10257         }
10258
10259         let events = nodes[0].node.get_and_clear_pending_events();
10260         assert_eq!(events.len(), 4);
10261         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10262                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10263         } else { panic!(); }
10264         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10265                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10266         } else { panic!(); }
10267         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10268         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10269
10270         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10271         // completion, we'll respond to nodes[1] with an RAA + CS.
10272         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10273         check_added_monitors(&nodes[0], 3);
10274 }
10275
10276 #[test]
10277 fn test_multi_post_event_actions() {
10278         do_test_multi_post_event_actions(true);
10279         do_test_multi_post_event_actions(false);
10280 }