Close and remove unfunded inbound/outbound channels that are older than an hour
[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};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{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};
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, RouteParameters, find_route, get_route};
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::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
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};
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 EnforcingSigner 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).unwrap();
705                 let chan_signer = local_chan.get_signer();
706                 let pubkeys = chan_signer.pubkeys();
707                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
708                  pubkeys.funding_pubkey)
709         };
710         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
711                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
712                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
713                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
714                 let chan_signer = remote_chan.get_signer();
715                 let pubkeys = chan_signer.pubkeys();
716                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
717                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
718                  pubkeys.funding_pubkey)
719         };
720
721         // Assemble the set of keys we can use for signatures for our commitment_signed message.
722         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
723                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
724
725         let res = {
726                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
727                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
728                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
729                 let local_chan_signer = local_chan.get_signer();
730                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
731                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
732                         INITIAL_COMMITMENT_NUMBER - 1,
733                         push_sats,
734                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
735                         local_funding, remote_funding,
736                         commit_tx_keys.clone(),
737                         non_buffer_feerate + 4,
738                         &mut htlcs,
739                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
740                 );
741                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
742         };
743
744         let commit_signed_msg = msgs::CommitmentSigned {
745                 channel_id: chan.2,
746                 signature: res.0,
747                 htlc_signatures: res.1,
748                 #[cfg(taproot)]
749                 partial_signature_with_nonce: None,
750         };
751
752         let update_fee = msgs::UpdateFee {
753                 channel_id: chan.2,
754                 feerate_per_kw: non_buffer_feerate + 4,
755         };
756
757         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
758
759         //While producing the commitment_signed response after handling a received update_fee request the
760         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
761         //Should produce and error.
762         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
763         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
764         check_added_monitors!(nodes[1], 1);
765         check_closed_broadcast!(nodes[1], true);
766         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
767 }
768
769 #[test]
770 fn test_update_fee_with_fundee_update_add_htlc() {
771         let chanmon_cfgs = create_chanmon_cfgs(2);
772         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
773         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
774         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
775         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
776
777         // balancing
778         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
779
780         {
781                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
782                 *feerate_lock += 20;
783         }
784         nodes[0].node.timer_tick_occurred();
785         check_added_monitors!(nodes[0], 1);
786
787         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
788         assert_eq!(events_0.len(), 1);
789         let (update_msg, commitment_signed) = match events_0[0] {
790                         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 } } => {
791                         (update_fee.as_ref(), commitment_signed)
792                 },
793                 _ => panic!("Unexpected event"),
794         };
795         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
796         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
797         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
798         check_added_monitors!(nodes[1], 1);
799
800         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
801
802         // nothing happens since node[1] is in AwaitingRemoteRevoke
803         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
804                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
805         {
806                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
807                 assert_eq!(added_monitors.len(), 0);
808                 added_monitors.clear();
809         }
810         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
811         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
812         // node[1] has nothing to do
813
814         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
815         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
816         check_added_monitors!(nodes[0], 1);
817
818         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
819         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
820         // No commitment_signed so get_event_msg's assert(len == 1) passes
821         check_added_monitors!(nodes[0], 1);
822         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
823         check_added_monitors!(nodes[1], 1);
824         // AwaitingRemoteRevoke ends here
825
826         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
827         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
828         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
829         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
830         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
831         assert_eq!(commitment_update.update_fee.is_none(), true);
832
833         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
834         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
835         check_added_monitors!(nodes[0], 1);
836         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
837
838         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
839         check_added_monitors!(nodes[1], 1);
840         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
841
842         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
843         check_added_monitors!(nodes[1], 1);
844         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
845         // No commitment_signed so get_event_msg's assert(len == 1) passes
846
847         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
848         check_added_monitors!(nodes[0], 1);
849         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
850
851         expect_pending_htlcs_forwardable!(nodes[0]);
852
853         let events = nodes[0].node.get_and_clear_pending_events();
854         assert_eq!(events.len(), 1);
855         match events[0] {
856                 Event::PaymentClaimable { .. } => { },
857                 _ => panic!("Unexpected event"),
858         };
859
860         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
861
862         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
863         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
864         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
865         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
866         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
867 }
868
869 #[test]
870 fn test_update_fee() {
871         let chanmon_cfgs = create_chanmon_cfgs(2);
872         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
873         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
874         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
875         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
876         let channel_id = chan.2;
877
878         // A                                        B
879         // (1) update_fee/commitment_signed      ->
880         //                                       <- (2) revoke_and_ack
881         //                                       .- send (3) commitment_signed
882         // (4) update_fee/commitment_signed      ->
883         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
884         //                                       <- (3) commitment_signed delivered
885         // send (6) revoke_and_ack               -.
886         //                                       <- (5) deliver revoke_and_ack
887         // (6) deliver revoke_and_ack            ->
888         //                                       .- send (7) commitment_signed in response to (4)
889         //                                       <- (7) deliver commitment_signed
890         // revoke_and_ack                        ->
891
892         // Create and deliver (1)...
893         let feerate;
894         {
895                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
896                 feerate = *feerate_lock;
897                 *feerate_lock = feerate + 20;
898         }
899         nodes[0].node.timer_tick_occurred();
900         check_added_monitors!(nodes[0], 1);
901
902         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
903         assert_eq!(events_0.len(), 1);
904         let (update_msg, commitment_signed) = match events_0[0] {
905                         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 } } => {
906                         (update_fee.as_ref(), commitment_signed)
907                 },
908                 _ => panic!("Unexpected event"),
909         };
910         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
911
912         // Generate (2) and (3):
913         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
914         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
915         check_added_monitors!(nodes[1], 1);
916
917         // Deliver (2):
918         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
919         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
920         check_added_monitors!(nodes[0], 1);
921
922         // Create and deliver (4)...
923         {
924                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
925                 *feerate_lock = feerate + 30;
926         }
927         nodes[0].node.timer_tick_occurred();
928         check_added_monitors!(nodes[0], 1);
929         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
930         assert_eq!(events_0.len(), 1);
931         let (update_msg, commitment_signed) = match events_0[0] {
932                         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 } } => {
933                         (update_fee.as_ref(), commitment_signed)
934                 },
935                 _ => panic!("Unexpected event"),
936         };
937
938         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
939         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
940         check_added_monitors!(nodes[1], 1);
941         // ... creating (5)
942         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
943         // No commitment_signed so get_event_msg's assert(len == 1) passes
944
945         // Handle (3), creating (6):
946         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
947         check_added_monitors!(nodes[0], 1);
948         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
949         // No commitment_signed so get_event_msg's assert(len == 1) passes
950
951         // Deliver (5):
952         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
953         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
954         check_added_monitors!(nodes[0], 1);
955
956         // Deliver (6), creating (7):
957         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
958         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
959         assert!(commitment_update.update_add_htlcs.is_empty());
960         assert!(commitment_update.update_fulfill_htlcs.is_empty());
961         assert!(commitment_update.update_fail_htlcs.is_empty());
962         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
963         assert!(commitment_update.update_fee.is_none());
964         check_added_monitors!(nodes[1], 1);
965
966         // Deliver (7)
967         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
968         check_added_monitors!(nodes[0], 1);
969         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
970         // No commitment_signed so get_event_msg's assert(len == 1) passes
971
972         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
973         check_added_monitors!(nodes[1], 1);
974         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
975
976         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
977         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
978         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
979         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
980         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
981 }
982
983 #[test]
984 fn fake_network_test() {
985         // Simple test which builds a network of ChannelManagers, connects them to each other, and
986         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
987         let chanmon_cfgs = create_chanmon_cfgs(4);
988         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
989         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
990         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
991
992         // Create some initial channels
993         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
994         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
995         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
996
997         // Rebalance the network a bit by relaying one payment through all the channels...
998         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
999         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1000         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1001         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1002
1003         // Send some more payments
1004         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1005         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1006         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1007
1008         // Test failure packets
1009         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1010         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1011
1012         // Add a new channel that skips 3
1013         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1014
1015         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1016         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1017         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1018         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1020         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1021         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1022
1023         // Do some rebalance loop payments, simultaneously
1024         let mut hops = Vec::with_capacity(3);
1025         hops.push(RouteHop {
1026                 pubkey: nodes[2].node.get_our_node_id(),
1027                 node_features: NodeFeatures::empty(),
1028                 short_channel_id: chan_2.0.contents.short_channel_id,
1029                 channel_features: ChannelFeatures::empty(),
1030                 fee_msat: 0,
1031                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1032         });
1033         hops.push(RouteHop {
1034                 pubkey: nodes[3].node.get_our_node_id(),
1035                 node_features: NodeFeatures::empty(),
1036                 short_channel_id: chan_3.0.contents.short_channel_id,
1037                 channel_features: ChannelFeatures::empty(),
1038                 fee_msat: 0,
1039                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1040         });
1041         hops.push(RouteHop {
1042                 pubkey: nodes[1].node.get_our_node_id(),
1043                 node_features: nodes[1].node.node_features(),
1044                 short_channel_id: chan_4.0.contents.short_channel_id,
1045                 channel_features: nodes[1].node.channel_features(),
1046                 fee_msat: 1000000,
1047                 cltv_expiry_delta: TEST_FINAL_CLTV,
1048         });
1049         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;
1050         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;
1051         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1052
1053         let mut hops = Vec::with_capacity(3);
1054         hops.push(RouteHop {
1055                 pubkey: nodes[3].node.get_our_node_id(),
1056                 node_features: NodeFeatures::empty(),
1057                 short_channel_id: chan_4.0.contents.short_channel_id,
1058                 channel_features: ChannelFeatures::empty(),
1059                 fee_msat: 0,
1060                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1061         });
1062         hops.push(RouteHop {
1063                 pubkey: nodes[2].node.get_our_node_id(),
1064                 node_features: NodeFeatures::empty(),
1065                 short_channel_id: chan_3.0.contents.short_channel_id,
1066                 channel_features: ChannelFeatures::empty(),
1067                 fee_msat: 0,
1068                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1069         });
1070         hops.push(RouteHop {
1071                 pubkey: nodes[1].node.get_our_node_id(),
1072                 node_features: nodes[1].node.node_features(),
1073                 short_channel_id: chan_2.0.contents.short_channel_id,
1074                 channel_features: nodes[1].node.channel_features(),
1075                 fee_msat: 1000000,
1076                 cltv_expiry_delta: TEST_FINAL_CLTV,
1077         });
1078         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;
1079         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;
1080         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1081
1082         // Claim the rebalances...
1083         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1084         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1085
1086         // Close down the channels...
1087         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1088         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1091         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1092         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1093         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1094         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1095         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1096         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1097         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1098         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1099 }
1100
1101 #[test]
1102 fn holding_cell_htlc_counting() {
1103         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1104         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1105         // commitment dance rounds.
1106         let chanmon_cfgs = create_chanmon_cfgs(3);
1107         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1108         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1109         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1110         create_announced_chan_between_nodes(&nodes, 0, 1);
1111         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1112
1113         // Fetch a route in advance as we will be unable to once we're unable to send.
1114         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1115
1116         let mut payments = Vec::new();
1117         for _ in 0..50 {
1118                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1119                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1120                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1121                 payments.push((payment_preimage, payment_hash));
1122         }
1123         check_added_monitors!(nodes[1], 1);
1124
1125         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1126         assert_eq!(events.len(), 1);
1127         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1128         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1129
1130         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1131         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1132         // another HTLC.
1133         {
1134                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1135                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1136                         ), true, APIError::ChannelUnavailable { .. }, {});
1137                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1138         }
1139
1140         // This should also be true if we try to forward a payment.
1141         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1142         {
1143                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1144                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1145                 check_added_monitors!(nodes[0], 1);
1146         }
1147
1148         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1149         assert_eq!(events.len(), 1);
1150         let payment_event = SendEvent::from_event(events.pop().unwrap());
1151         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1152
1153         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1154         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1155         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1156         // fails), the second will process the resulting failure and fail the HTLC backward.
1157         expect_pending_htlcs_forwardable!(nodes[1]);
1158         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 }]);
1159         check_added_monitors!(nodes[1], 1);
1160
1161         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1162         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1163         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1164
1165         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1166
1167         // Now forward all the pending HTLCs and claim them back
1168         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1169         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1170         check_added_monitors!(nodes[2], 1);
1171
1172         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1173         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1174         check_added_monitors!(nodes[1], 1);
1175         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1176
1177         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1178         check_added_monitors!(nodes[1], 1);
1179         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1180
1181         for ref update in as_updates.update_add_htlcs.iter() {
1182                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1183         }
1184         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1185         check_added_monitors!(nodes[2], 1);
1186         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1187         check_added_monitors!(nodes[2], 1);
1188         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1189
1190         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1191         check_added_monitors!(nodes[1], 1);
1192         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1193         check_added_monitors!(nodes[1], 1);
1194         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1195
1196         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1197         check_added_monitors!(nodes[2], 1);
1198
1199         expect_pending_htlcs_forwardable!(nodes[2]);
1200
1201         let events = nodes[2].node.get_and_clear_pending_events();
1202         assert_eq!(events.len(), payments.len());
1203         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1204                 match event {
1205                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1206                                 assert_eq!(*payment_hash, *hash);
1207                         },
1208                         _ => panic!("Unexpected event"),
1209                 };
1210         }
1211
1212         for (preimage, _) in payments.drain(..) {
1213                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1214         }
1215
1216         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1217 }
1218
1219 #[test]
1220 fn duplicate_htlc_test() {
1221         // Test that we accept duplicate payment_hash HTLCs across the network and that
1222         // claiming/failing them are all separate and don't affect each other
1223         let chanmon_cfgs = create_chanmon_cfgs(6);
1224         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1225         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1226         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1227
1228         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1229         create_announced_chan_between_nodes(&nodes, 0, 3);
1230         create_announced_chan_between_nodes(&nodes, 1, 3);
1231         create_announced_chan_between_nodes(&nodes, 2, 3);
1232         create_announced_chan_between_nodes(&nodes, 3, 4);
1233         create_announced_chan_between_nodes(&nodes, 3, 5);
1234
1235         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1236
1237         *nodes[0].network_payment_count.borrow_mut() -= 1;
1238         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1239
1240         *nodes[0].network_payment_count.borrow_mut() -= 1;
1241         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1242
1243         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1244         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1245         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1246 }
1247
1248 #[test]
1249 fn test_duplicate_htlc_different_direction_onchain() {
1250         // Test that ChannelMonitor doesn't generate 2 preimage txn
1251         // when we have 2 HTLCs with same preimage that go across a node
1252         // in opposite directions, even with the same payment secret.
1253         let chanmon_cfgs = create_chanmon_cfgs(2);
1254         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1256         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1257
1258         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1259
1260         // balancing
1261         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1262
1263         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1264
1265         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1266         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1267         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1268
1269         // Provide preimage to node 0 by claiming payment
1270         nodes[0].node.claim_funds(payment_preimage);
1271         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1272         check_added_monitors!(nodes[0], 1);
1273
1274         // Broadcast node 1 commitment txn
1275         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1276
1277         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1278         let mut has_both_htlcs = 0; // check htlcs match ones committed
1279         for outp in remote_txn[0].output.iter() {
1280                 if outp.value == 800_000 / 1000 {
1281                         has_both_htlcs += 1;
1282                 } else if outp.value == 900_000 / 1000 {
1283                         has_both_htlcs += 1;
1284                 }
1285         }
1286         assert_eq!(has_both_htlcs, 2);
1287
1288         mine_transaction(&nodes[0], &remote_txn[0]);
1289         check_added_monitors!(nodes[0], 1);
1290         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1291         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1292
1293         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1294         assert_eq!(claim_txn.len(), 3);
1295
1296         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1297         check_spends!(claim_txn[1], remote_txn[0]);
1298         check_spends!(claim_txn[2], remote_txn[0]);
1299         let preimage_tx = &claim_txn[0];
1300         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1301                 (&claim_txn[1], &claim_txn[2])
1302         } else {
1303                 (&claim_txn[2], &claim_txn[1])
1304         };
1305
1306         assert_eq!(preimage_tx.input.len(), 1);
1307         assert_eq!(preimage_bump_tx.input.len(), 1);
1308
1309         assert_eq!(preimage_tx.input.len(), 1);
1310         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1311         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1312
1313         assert_eq!(timeout_tx.input.len(), 1);
1314         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1315         check_spends!(timeout_tx, remote_txn[0]);
1316         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1317
1318         let events = nodes[0].node.get_and_clear_pending_msg_events();
1319         assert_eq!(events.len(), 3);
1320         for e in events {
1321                 match e {
1322                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1323                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1324                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1325                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1326                         },
1327                         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, .. } } => {
1328                                 assert!(update_add_htlcs.is_empty());
1329                                 assert!(update_fail_htlcs.is_empty());
1330                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1331                                 assert!(update_fail_malformed_htlcs.is_empty());
1332                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1333                         },
1334                         _ => panic!("Unexpected event"),
1335                 }
1336         }
1337 }
1338
1339 #[test]
1340 fn test_basic_channel_reserve() {
1341         let chanmon_cfgs = create_chanmon_cfgs(2);
1342         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1343         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1344         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1345         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1346
1347         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1348         let channel_reserve = chan_stat.channel_reserve_msat;
1349
1350         // The 2* and +1 are for the fee spike reserve.
1351         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));
1352         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1353         let (mut route, our_payment_hash, _, our_payment_secret) =
1354                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1355         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1356         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1357                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1358         match err {
1359                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1360                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1361                         else { panic!("Unexpected error variant"); }
1362                 },
1363                 _ => panic!("Unexpected error variant"),
1364         }
1365         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1366
1367         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1368 }
1369
1370 #[test]
1371 fn test_fee_spike_violation_fails_htlc() {
1372         let chanmon_cfgs = create_chanmon_cfgs(2);
1373         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1374         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1375         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1376         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1377
1378         let (mut route, payment_hash, _, payment_secret) =
1379                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1380         route.paths[0].hops[0].fee_msat += 1;
1381         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1382         let secp_ctx = Secp256k1::new();
1383         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1384
1385         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1386
1387         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1388         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1389                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1390         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1391         let msg = msgs::UpdateAddHTLC {
1392                 channel_id: chan.2,
1393                 htlc_id: 0,
1394                 amount_msat: htlc_msat,
1395                 payment_hash: payment_hash,
1396                 cltv_expiry: htlc_cltv,
1397                 onion_routing_packet: onion_packet,
1398                 skimmed_fee_msat: None,
1399         };
1400
1401         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1402
1403         // Now manually create the commitment_signed message corresponding to the update_add
1404         // nodes[0] just sent. In the code for construction of this message, "local" refers
1405         // to the sender of the message, and "remote" refers to the receiver.
1406
1407         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1408
1409         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1410
1411         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1412         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1413         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1414                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1415                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1416                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1417                 let chan_signer = local_chan.get_signer();
1418                 // Make the signer believe we validated another commitment, so we can release the secret
1419                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1420
1421                 let pubkeys = chan_signer.pubkeys();
1422                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1423                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1424                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1425                  chan_signer.pubkeys().funding_pubkey)
1426         };
1427         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1428                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1429                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1430                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1431                 let chan_signer = remote_chan.get_signer();
1432                 let pubkeys = chan_signer.pubkeys();
1433                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1434                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1435                  chan_signer.pubkeys().funding_pubkey)
1436         };
1437
1438         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1439         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1440                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1441
1442         // Build the remote commitment transaction so we can sign it, and then later use the
1443         // signature for the commitment_signed message.
1444         let local_chan_balance = 1313;
1445
1446         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1447                 offered: false,
1448                 amount_msat: 3460001,
1449                 cltv_expiry: htlc_cltv,
1450                 payment_hash,
1451                 transaction_output_index: Some(1),
1452         };
1453
1454         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1455
1456         let res = {
1457                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1458                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1459                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1460                 let local_chan_signer = local_chan.get_signer();
1461                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1462                         commitment_number,
1463                         95000,
1464                         local_chan_balance,
1465                         local_funding, remote_funding,
1466                         commit_tx_keys.clone(),
1467                         feerate_per_kw,
1468                         &mut vec![(accepted_htlc_info, ())],
1469                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1470                 );
1471                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1472         };
1473
1474         let commit_signed_msg = msgs::CommitmentSigned {
1475                 channel_id: chan.2,
1476                 signature: res.0,
1477                 htlc_signatures: res.1,
1478                 #[cfg(taproot)]
1479                 partial_signature_with_nonce: None,
1480         };
1481
1482         // Send the commitment_signed message to the nodes[1].
1483         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1484         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1485
1486         // Send the RAA to nodes[1].
1487         let raa_msg = msgs::RevokeAndACK {
1488                 channel_id: chan.2,
1489                 per_commitment_secret: local_secret,
1490                 next_per_commitment_point: next_local_point,
1491                 #[cfg(taproot)]
1492                 next_local_nonce: None,
1493         };
1494         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1495
1496         let events = nodes[1].node.get_and_clear_pending_msg_events();
1497         assert_eq!(events.len(), 1);
1498         // Make sure the HTLC failed in the way we expect.
1499         match events[0] {
1500                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1501                         assert_eq!(update_fail_htlcs.len(), 1);
1502                         update_fail_htlcs[0].clone()
1503                 },
1504                 _ => panic!("Unexpected event"),
1505         };
1506         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1507                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1508
1509         check_added_monitors!(nodes[1], 2);
1510 }
1511
1512 #[test]
1513 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1514         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1515         // Set the fee rate for the channel very high, to the point where the fundee
1516         // sending any above-dust amount would result in a channel reserve violation.
1517         // In this test we check that we would be prevented from sending an HTLC in
1518         // this situation.
1519         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1520         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1522         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523         let default_config = UserConfig::default();
1524         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1525
1526         let mut push_amt = 100_000_000;
1527         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1528
1529         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1530
1531         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1532
1533         // Fetch a route in advance as we will be unable to once we're unable to send.
1534         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1535         // Sending exactly enough to hit the reserve amount should be accepted
1536         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1537                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1538         }
1539
1540         // However one more HTLC should be significantly over the reserve amount and fail.
1541         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1542                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1543                 ), true, APIError::ChannelUnavailable { .. }, {});
1544         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1545 }
1546
1547 #[test]
1548 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1549         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1550         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1551         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1552         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1553         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1554         let default_config = UserConfig::default();
1555         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1556
1557         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1558         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1559         // transaction fee with 0 HTLCs (183 sats)).
1560         let mut push_amt = 100_000_000;
1561         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1562         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1563         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1564
1565         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1566         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1567                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1568         }
1569
1570         let (mut route, payment_hash, _, payment_secret) =
1571                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1572         route.paths[0].hops[0].fee_msat = 700_000;
1573         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1574         let secp_ctx = Secp256k1::new();
1575         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1576         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1577         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1578         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1579                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1580         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1581         let msg = msgs::UpdateAddHTLC {
1582                 channel_id: chan.2,
1583                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1584                 amount_msat: htlc_msat,
1585                 payment_hash: payment_hash,
1586                 cltv_expiry: htlc_cltv,
1587                 onion_routing_packet: onion_packet,
1588                 skimmed_fee_msat: None,
1589         };
1590
1591         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1592         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1593         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);
1594         assert_eq!(nodes[0].node.list_channels().len(), 0);
1595         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1596         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1597         check_added_monitors!(nodes[0], 1);
1598         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() });
1599 }
1600
1601 #[test]
1602 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1603         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1604         // calculating our commitment transaction fee (this was previously broken).
1605         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1606         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1607
1608         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1609         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1610         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1611         let default_config = UserConfig::default();
1612         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1613
1614         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1615         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1616         // transaction fee with 0 HTLCs (183 sats)).
1617         let mut push_amt = 100_000_000;
1618         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1619         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1620         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1621
1622         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1623                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1624         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1625         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1626         // commitment transaction fee.
1627         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1628
1629         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1630         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1631                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1632         }
1633
1634         // One more than the dust amt should fail, however.
1635         let (mut route, our_payment_hash, _, our_payment_secret) =
1636                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1637         route.paths[0].hops[0].fee_msat += 1;
1638         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1639                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1640                 ), true, APIError::ChannelUnavailable { .. }, {});
1641 }
1642
1643 #[test]
1644 fn test_chan_init_feerate_unaffordability() {
1645         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1646         // channel reserve and feerate requirements.
1647         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1648         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1649         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1650         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1651         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1652         let default_config = UserConfig::default();
1653         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1654
1655         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1656         // HTLC.
1657         let mut push_amt = 100_000_000;
1658         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1659         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1660                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1661
1662         // During open, we don't have a "counterparty channel reserve" to check against, so that
1663         // requirement only comes into play on the open_channel handling side.
1664         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1665         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1666         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1667         open_channel_msg.push_msat += 1;
1668         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1669
1670         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1671         assert_eq!(msg_events.len(), 1);
1672         match msg_events[0] {
1673                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1674                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1675                 },
1676                 _ => panic!("Unexpected event"),
1677         }
1678 }
1679
1680 #[test]
1681 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1682         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1683         // calculating our counterparty's commitment transaction fee (this was previously broken).
1684         let chanmon_cfgs = create_chanmon_cfgs(2);
1685         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1686         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1687         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1688         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1689
1690         let payment_amt = 46000; // Dust amount
1691         // In the previous code, these first four payments would succeed.
1692         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696
1697         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1698         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1702         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1703
1704         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1705         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1706         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1707         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1708 }
1709
1710 #[test]
1711 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1712         let chanmon_cfgs = create_chanmon_cfgs(3);
1713         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1714         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1715         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1716         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1717         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1718
1719         let feemsat = 239;
1720         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1721         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1722         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1723         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1724
1725         // Add a 2* and +1 for the fee spike reserve.
1726         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1727         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;
1728         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1729
1730         // Add a pending HTLC.
1731         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1732         let payment_event_1 = {
1733                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1734                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1735                 check_added_monitors!(nodes[0], 1);
1736
1737                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1738                 assert_eq!(events.len(), 1);
1739                 SendEvent::from_event(events.remove(0))
1740         };
1741         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1742
1743         // Attempt to trigger a channel reserve violation --> payment failure.
1744         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1745         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;
1746         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1747         let mut route_2 = route_1.clone();
1748         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1749
1750         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1751         let secp_ctx = Secp256k1::new();
1752         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1753         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1754         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1755         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1756                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1757         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1758         let msg = msgs::UpdateAddHTLC {
1759                 channel_id: chan.2,
1760                 htlc_id: 1,
1761                 amount_msat: htlc_msat + 1,
1762                 payment_hash: our_payment_hash_1,
1763                 cltv_expiry: htlc_cltv,
1764                 onion_routing_packet: onion_packet,
1765                 skimmed_fee_msat: None,
1766         };
1767
1768         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1769         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1770         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1771         assert_eq!(nodes[1].node.list_channels().len(), 1);
1772         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1773         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1774         check_added_monitors!(nodes[1], 1);
1775         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1776 }
1777
1778 #[test]
1779 fn test_inbound_outbound_capacity_is_not_zero() {
1780         let chanmon_cfgs = create_chanmon_cfgs(2);
1781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1783         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1784         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1785         let channels0 = node_chanmgrs[0].list_channels();
1786         let channels1 = node_chanmgrs[1].list_channels();
1787         let default_config = UserConfig::default();
1788         assert_eq!(channels0.len(), 1);
1789         assert_eq!(channels1.len(), 1);
1790
1791         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1792         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1793         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1794
1795         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1796         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1797 }
1798
1799 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1800         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1801 }
1802
1803 #[test]
1804 fn test_channel_reserve_holding_cell_htlcs() {
1805         let chanmon_cfgs = create_chanmon_cfgs(3);
1806         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1807         // When this test was written, the default base fee floated based on the HTLC count.
1808         // It is now fixed, so we simply set the fee to the expected value here.
1809         let mut config = test_default_channel_config();
1810         config.channel_config.forwarding_fee_base_msat = 239;
1811         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1812         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1813         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1814         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1815
1816         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1817         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1818
1819         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1820         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1821
1822         macro_rules! expect_forward {
1823                 ($node: expr) => {{
1824                         let mut events = $node.node.get_and_clear_pending_msg_events();
1825                         assert_eq!(events.len(), 1);
1826                         check_added_monitors!($node, 1);
1827                         let payment_event = SendEvent::from_event(events.remove(0));
1828                         payment_event
1829                 }}
1830         }
1831
1832         let feemsat = 239; // set above
1833         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1834         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1835         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1836
1837         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1838
1839         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1840         {
1841                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1842                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1843                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1844                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1845                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1846
1847                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1848                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1849                         ), true, APIError::ChannelUnavailable { .. }, {});
1850                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1851         }
1852
1853         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1854         // nodes[0]'s wealth
1855         loop {
1856                 let amt_msat = recv_value_0 + total_fee_msat;
1857                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1858                 // Also, ensure that each payment has enough to be over the dust limit to
1859                 // ensure it'll be included in each commit tx fee calculation.
1860                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1861                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1862                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1863                         break;
1864                 }
1865
1866                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1867                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1868                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1869                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1870                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1871
1872                 let (stat01_, stat11_, stat12_, stat22_) = (
1873                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1874                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1875                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1876                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1877                 );
1878
1879                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1880                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1881                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1882                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1883                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1884         }
1885
1886         // adding pending output.
1887         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1888         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1889         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1890         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1891         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1892         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1893         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1894         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1895         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1896         // policy.
1897         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1898         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1899         let amt_msat_1 = recv_value_1 + total_fee_msat;
1900
1901         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);
1902         let payment_event_1 = {
1903                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1904                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1905                 check_added_monitors!(nodes[0], 1);
1906
1907                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1908                 assert_eq!(events.len(), 1);
1909                 SendEvent::from_event(events.remove(0))
1910         };
1911         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1912
1913         // channel reserve test with htlc pending output > 0
1914         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1915         {
1916                 let mut route = route_1.clone();
1917                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1918                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1919                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1920                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1921                         ), true, APIError::ChannelUnavailable { .. }, {});
1922                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1923         }
1924
1925         // split the rest to test holding cell
1926         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1927         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1928         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1929         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1930         {
1931                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1932                 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);
1933         }
1934
1935         // now see if they go through on both sides
1936         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);
1937         // but this will stuck in the holding cell
1938         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1939                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1940         check_added_monitors!(nodes[0], 0);
1941         let events = nodes[0].node.get_and_clear_pending_events();
1942         assert_eq!(events.len(), 0);
1943
1944         // test with outbound holding cell amount > 0
1945         {
1946                 let (mut route, our_payment_hash, _, our_payment_secret) =
1947                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1948                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1949                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1950                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1951                         ), true, APIError::ChannelUnavailable { .. }, {});
1952                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1953         }
1954
1955         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);
1956         // this will also stuck in the holding cell
1957         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1958                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1959         check_added_monitors!(nodes[0], 0);
1960         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1961         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1962
1963         // flush the pending htlc
1964         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1965         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1966         check_added_monitors!(nodes[1], 1);
1967
1968         // the pending htlc should be promoted to committed
1969         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1970         check_added_monitors!(nodes[0], 1);
1971         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1972
1973         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1974         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1975         // No commitment_signed so get_event_msg's assert(len == 1) passes
1976         check_added_monitors!(nodes[0], 1);
1977
1978         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1979         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1980         check_added_monitors!(nodes[1], 1);
1981
1982         expect_pending_htlcs_forwardable!(nodes[1]);
1983
1984         let ref payment_event_11 = expect_forward!(nodes[1]);
1985         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1986         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1987
1988         expect_pending_htlcs_forwardable!(nodes[2]);
1989         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1990
1991         // flush the htlcs in the holding cell
1992         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1993         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1994         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1995         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1996         expect_pending_htlcs_forwardable!(nodes[1]);
1997
1998         let ref payment_event_3 = expect_forward!(nodes[1]);
1999         assert_eq!(payment_event_3.msgs.len(), 2);
2000         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2001         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2002
2003         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2004         expect_pending_htlcs_forwardable!(nodes[2]);
2005
2006         let events = nodes[2].node.get_and_clear_pending_events();
2007         assert_eq!(events.len(), 2);
2008         match events[0] {
2009                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2010                         assert_eq!(our_payment_hash_21, *payment_hash);
2011                         assert_eq!(recv_value_21, amount_msat);
2012                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2013                         assert_eq!(via_channel_id, Some(chan_2.2));
2014                         match &purpose {
2015                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2016                                         assert!(payment_preimage.is_none());
2017                                         assert_eq!(our_payment_secret_21, *payment_secret);
2018                                 },
2019                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2020                         }
2021                 },
2022                 _ => panic!("Unexpected event"),
2023         }
2024         match events[1] {
2025                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2026                         assert_eq!(our_payment_hash_22, *payment_hash);
2027                         assert_eq!(recv_value_22, amount_msat);
2028                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2029                         assert_eq!(via_channel_id, Some(chan_2.2));
2030                         match &purpose {
2031                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2032                                         assert!(payment_preimage.is_none());
2033                                         assert_eq!(our_payment_secret_22, *payment_secret);
2034                                 },
2035                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2036                         }
2037                 },
2038                 _ => panic!("Unexpected event"),
2039         }
2040
2041         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2042         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2043         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2044
2045         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2046         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2047         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2048
2049         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2050         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);
2051         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2052         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2053         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2054
2055         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2056         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2057 }
2058
2059 #[test]
2060 fn channel_reserve_in_flight_removes() {
2061         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2062         // can send to its counterparty, but due to update ordering, the other side may not yet have
2063         // considered those HTLCs fully removed.
2064         // This tests that we don't count HTLCs which will not be included in the next remote
2065         // commitment transaction towards the reserve value (as it implies no commitment transaction
2066         // will be generated which violates the remote reserve value).
2067         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2068         // To test this we:
2069         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2070         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2071         //    you only consider the value of the first HTLC, it may not),
2072         //  * start routing a third HTLC from A to B,
2073         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2074         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2075         //  * deliver the first fulfill from B
2076         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2077         //    claim,
2078         //  * deliver A's response CS and RAA.
2079         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2080         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2081         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2082         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2083         let chanmon_cfgs = create_chanmon_cfgs(2);
2084         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2085         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2086         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2087         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2088
2089         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2090         // Route the first two HTLCs.
2091         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2092         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2093         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2094
2095         // Start routing the third HTLC (this is just used to get everyone in the right state).
2096         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2097         let send_1 = {
2098                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2099                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2100                 check_added_monitors!(nodes[0], 1);
2101                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2102                 assert_eq!(events.len(), 1);
2103                 SendEvent::from_event(events.remove(0))
2104         };
2105
2106         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2107         // initial fulfill/CS.
2108         nodes[1].node.claim_funds(payment_preimage_1);
2109         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2110         check_added_monitors!(nodes[1], 1);
2111         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2112
2113         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2114         // remove the second HTLC when we send the HTLC back from B to A.
2115         nodes[1].node.claim_funds(payment_preimage_2);
2116         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2117         check_added_monitors!(nodes[1], 1);
2118         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2119
2120         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2121         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2122         check_added_monitors!(nodes[0], 1);
2123         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2124         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2125
2126         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2127         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2128         check_added_monitors!(nodes[1], 1);
2129         // B is already AwaitingRAA, so cant generate a CS here
2130         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2131
2132         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2133         check_added_monitors!(nodes[1], 1);
2134         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2135
2136         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2137         check_added_monitors!(nodes[0], 1);
2138         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2139
2140         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2141         check_added_monitors!(nodes[1], 1);
2142         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2143
2144         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2145         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2146         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2147         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2148         // on-chain as necessary).
2149         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2150         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2151         check_added_monitors!(nodes[0], 1);
2152         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2153         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2154
2155         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2156         check_added_monitors!(nodes[1], 1);
2157         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2158
2159         expect_pending_htlcs_forwardable!(nodes[1]);
2160         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2161
2162         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2163         // resolve the second HTLC from A's point of view.
2164         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2165         check_added_monitors!(nodes[0], 1);
2166         expect_payment_path_successful!(nodes[0]);
2167         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2168
2169         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2170         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2171         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2172         let send_2 = {
2173                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2174                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2175                 check_added_monitors!(nodes[1], 1);
2176                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2177                 assert_eq!(events.len(), 1);
2178                 SendEvent::from_event(events.remove(0))
2179         };
2180
2181         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2182         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2183         check_added_monitors!(nodes[0], 1);
2184         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2185
2186         // Now just resolve all the outstanding messages/HTLCs for completeness...
2187
2188         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2189         check_added_monitors!(nodes[1], 1);
2190         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2191
2192         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2193         check_added_monitors!(nodes[1], 1);
2194
2195         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2196         check_added_monitors!(nodes[0], 1);
2197         expect_payment_path_successful!(nodes[0]);
2198         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2199
2200         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2201         check_added_monitors!(nodes[1], 1);
2202         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2203
2204         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2205         check_added_monitors!(nodes[0], 1);
2206
2207         expect_pending_htlcs_forwardable!(nodes[0]);
2208         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2209
2210         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2211         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2212 }
2213
2214 #[test]
2215 fn channel_monitor_network_test() {
2216         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2217         // tests that ChannelMonitor is able to recover from various states.
2218         let chanmon_cfgs = create_chanmon_cfgs(5);
2219         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2220         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2221         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2222
2223         // Create some initial channels
2224         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2225         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2226         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2227         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2228
2229         // Make sure all nodes are at the same starting height
2230         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2231         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2232         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2233         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2234         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2235
2236         // Rebalance the network a bit by relaying one payment through all the channels...
2237         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2238         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2239         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2240         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2241
2242         // Simple case with no pending HTLCs:
2243         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2244         check_added_monitors!(nodes[1], 1);
2245         check_closed_broadcast!(nodes[1], true);
2246         {
2247                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2248                 assert_eq!(node_txn.len(), 1);
2249                 mine_transaction(&nodes[0], &node_txn[0]);
2250                 check_added_monitors!(nodes[0], 1);
2251                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2252         }
2253         check_closed_broadcast!(nodes[0], true);
2254         assert_eq!(nodes[0].node.list_channels().len(), 0);
2255         assert_eq!(nodes[1].node.list_channels().len(), 1);
2256         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2257         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2258
2259         // One pending HTLC is discarded by the force-close:
2260         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2261
2262         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2263         // broadcasted until we reach the timelock time).
2264         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2265         check_closed_broadcast!(nodes[1], true);
2266         check_added_monitors!(nodes[1], 1);
2267         {
2268                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2269                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2270                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2271                 mine_transaction(&nodes[2], &node_txn[0]);
2272                 check_added_monitors!(nodes[2], 1);
2273                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2274         }
2275         check_closed_broadcast!(nodes[2], true);
2276         assert_eq!(nodes[1].node.list_channels().len(), 0);
2277         assert_eq!(nodes[2].node.list_channels().len(), 1);
2278         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2279         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2280
2281         macro_rules! claim_funds {
2282                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2283                         {
2284                                 $node.node.claim_funds($preimage);
2285                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2286                                 check_added_monitors!($node, 1);
2287
2288                                 let events = $node.node.get_and_clear_pending_msg_events();
2289                                 assert_eq!(events.len(), 1);
2290                                 match events[0] {
2291                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2292                                                 assert!(update_add_htlcs.is_empty());
2293                                                 assert!(update_fail_htlcs.is_empty());
2294                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2295                                         },
2296                                         _ => panic!("Unexpected event"),
2297                                 };
2298                         }
2299                 }
2300         }
2301
2302         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2303         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2304         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2305         check_added_monitors!(nodes[2], 1);
2306         check_closed_broadcast!(nodes[2], true);
2307         let node2_commitment_txid;
2308         {
2309                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2310                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2311                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2312                 node2_commitment_txid = node_txn[0].txid();
2313
2314                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2315                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2316                 mine_transaction(&nodes[3], &node_txn[0]);
2317                 check_added_monitors!(nodes[3], 1);
2318                 check_preimage_claim(&nodes[3], &node_txn);
2319         }
2320         check_closed_broadcast!(nodes[3], true);
2321         assert_eq!(nodes[2].node.list_channels().len(), 0);
2322         assert_eq!(nodes[3].node.list_channels().len(), 1);
2323         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2324         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2325
2326         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2327         // confusing us in the following tests.
2328         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2329
2330         // One pending HTLC to time out:
2331         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2332         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2333         // buffer space).
2334
2335         let (close_chan_update_1, close_chan_update_2) = {
2336                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2337                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2338                 assert_eq!(events.len(), 2);
2339                 let close_chan_update_1 = match events[0] {
2340                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2341                                 msg.clone()
2342                         },
2343                         _ => panic!("Unexpected event"),
2344                 };
2345                 match events[1] {
2346                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2347                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2348                         },
2349                         _ => panic!("Unexpected event"),
2350                 }
2351                 check_added_monitors!(nodes[3], 1);
2352
2353                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2354                 {
2355                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2356                         node_txn.retain(|tx| {
2357                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2358                                         false
2359                                 } else { true }
2360                         });
2361                 }
2362
2363                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2364
2365                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2366                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2367
2368                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2369                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2370                 assert_eq!(events.len(), 2);
2371                 let close_chan_update_2 = match events[0] {
2372                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2373                                 msg.clone()
2374                         },
2375                         _ => panic!("Unexpected event"),
2376                 };
2377                 match events[1] {
2378                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2379                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2380                         },
2381                         _ => panic!("Unexpected event"),
2382                 }
2383                 check_added_monitors!(nodes[4], 1);
2384                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2385
2386                 mine_transaction(&nodes[4], &node_txn[0]);
2387                 check_preimage_claim(&nodes[4], &node_txn);
2388                 (close_chan_update_1, close_chan_update_2)
2389         };
2390         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2391         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2392         assert_eq!(nodes[3].node.list_channels().len(), 0);
2393         assert_eq!(nodes[4].node.list_channels().len(), 0);
2394
2395         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2396                 ChannelMonitorUpdateStatus::Completed);
2397         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2398         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2399 }
2400
2401 #[test]
2402 fn test_justice_tx_htlc_timeout() {
2403         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2404         let mut alice_config = UserConfig::default();
2405         alice_config.channel_handshake_config.announced_channel = true;
2406         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2407         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2408         let mut bob_config = UserConfig::default();
2409         bob_config.channel_handshake_config.announced_channel = true;
2410         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2411         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2412         let user_cfgs = [Some(alice_config), Some(bob_config)];
2413         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2414         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2415         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2418         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2419         // Create some new channels:
2420         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2421
2422         // A pending HTLC which will be revoked:
2423         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2424         // Get the will-be-revoked local txn from nodes[0]
2425         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2426         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2427         assert_eq!(revoked_local_txn[0].input.len(), 1);
2428         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2429         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2430         assert_eq!(revoked_local_txn[1].input.len(), 1);
2431         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2432         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2433         // Revoke the old state
2434         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2435
2436         {
2437                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2438                 {
2439                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2440                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2441                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2442                         check_spends!(node_txn[0], revoked_local_txn[0]);
2443                         node_txn.swap_remove(0);
2444                 }
2445                 check_added_monitors!(nodes[1], 1);
2446                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2447                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2448
2449                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2450                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2451                 // Verify broadcast of revoked HTLC-timeout
2452                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2453                 check_added_monitors!(nodes[0], 1);
2454                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2455                 // Broadcast revoked HTLC-timeout on node 1
2456                 mine_transaction(&nodes[1], &node_txn[1]);
2457                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2458         }
2459         get_announce_close_broadcast_events(&nodes, 0, 1);
2460         assert_eq!(nodes[0].node.list_channels().len(), 0);
2461         assert_eq!(nodes[1].node.list_channels().len(), 0);
2462 }
2463
2464 #[test]
2465 fn test_justice_tx_htlc_success() {
2466         // Test justice txn built on revoked HTLC-Success tx, against both sides
2467         let mut alice_config = UserConfig::default();
2468         alice_config.channel_handshake_config.announced_channel = true;
2469         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2470         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2471         let mut bob_config = UserConfig::default();
2472         bob_config.channel_handshake_config.announced_channel = true;
2473         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2474         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2475         let user_cfgs = [Some(alice_config), Some(bob_config)];
2476         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2477         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2478         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2481         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2482         // Create some new channels:
2483         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2484
2485         // A pending HTLC which will be revoked:
2486         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2487         // Get the will-be-revoked local txn from B
2488         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2489         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2490         assert_eq!(revoked_local_txn[0].input.len(), 1);
2491         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2492         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2493         // Revoke the old state
2494         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2495         {
2496                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2497                 {
2498                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2499                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2500                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2501
2502                         check_spends!(node_txn[0], revoked_local_txn[0]);
2503                         node_txn.swap_remove(0);
2504                 }
2505                 check_added_monitors!(nodes[0], 1);
2506                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2507
2508                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2509                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2510                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2511                 check_added_monitors!(nodes[1], 1);
2512                 mine_transaction(&nodes[0], &node_txn[1]);
2513                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2514                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2515         }
2516         get_announce_close_broadcast_events(&nodes, 0, 1);
2517         assert_eq!(nodes[0].node.list_channels().len(), 0);
2518         assert_eq!(nodes[1].node.list_channels().len(), 0);
2519 }
2520
2521 #[test]
2522 fn revoked_output_claim() {
2523         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2524         // transaction is broadcast by its counterparty
2525         let chanmon_cfgs = create_chanmon_cfgs(2);
2526         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2527         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2528         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2529         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2530         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2531         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2532         assert_eq!(revoked_local_txn.len(), 1);
2533         // Only output is the full channel value back to nodes[0]:
2534         assert_eq!(revoked_local_txn[0].output.len(), 1);
2535         // Send a payment through, updating everyone's latest commitment txn
2536         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2537
2538         // Inform nodes[1] that nodes[0] broadcast a stale tx
2539         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2540         check_added_monitors!(nodes[1], 1);
2541         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2542         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2543         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2544
2545         check_spends!(node_txn[0], revoked_local_txn[0]);
2546
2547         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2548         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2549         get_announce_close_broadcast_events(&nodes, 0, 1);
2550         check_added_monitors!(nodes[0], 1);
2551         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2552 }
2553
2554 #[test]
2555 fn claim_htlc_outputs_shared_tx() {
2556         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2557         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2558         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2561         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2562
2563         // Create some new channel:
2564         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2565
2566         // Rebalance the network to generate htlc in the two directions
2567         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2568         // 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
2569         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2570         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2571
2572         // Get the will-be-revoked local txn from node[0]
2573         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2574         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2575         assert_eq!(revoked_local_txn[0].input.len(), 1);
2576         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2577         assert_eq!(revoked_local_txn[1].input.len(), 1);
2578         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2579         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2580         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2581
2582         //Revoke the old state
2583         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2584
2585         {
2586                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2587                 check_added_monitors!(nodes[0], 1);
2588                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2589                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2590                 check_added_monitors!(nodes[1], 1);
2591                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2592                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2593                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2594
2595                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2596                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2597
2598                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2599                 check_spends!(node_txn[0], revoked_local_txn[0]);
2600
2601                 let mut witness_lens = BTreeSet::new();
2602                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2603                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2604                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2605                 assert_eq!(witness_lens.len(), 3);
2606                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2607                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2608                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2609
2610                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2611                 // ANTI_REORG_DELAY confirmations.
2612                 mine_transaction(&nodes[1], &node_txn[0]);
2613                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2614                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2615         }
2616         get_announce_close_broadcast_events(&nodes, 0, 1);
2617         assert_eq!(nodes[0].node.list_channels().len(), 0);
2618         assert_eq!(nodes[1].node.list_channels().len(), 0);
2619 }
2620
2621 #[test]
2622 fn claim_htlc_outputs_single_tx() {
2623         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2624         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2625         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2626         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2627         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2628         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2629
2630         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2631
2632         // Rebalance the network to generate htlc in the two directions
2633         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2634         // 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
2635         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2636         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2637         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2638
2639         // Get the will-be-revoked local txn from node[0]
2640         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2641
2642         //Revoke the old state
2643         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2644
2645         {
2646                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2647                 check_added_monitors!(nodes[0], 1);
2648                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2649                 check_added_monitors!(nodes[1], 1);
2650                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2651                 let mut events = nodes[0].node.get_and_clear_pending_events();
2652                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2653                 match events.last().unwrap() {
2654                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2655                         _ => panic!("Unexpected event"),
2656                 }
2657
2658                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2659                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2660
2661                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2662
2663                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2664                 assert_eq!(node_txn[0].input.len(), 1);
2665                 check_spends!(node_txn[0], chan_1.3);
2666                 assert_eq!(node_txn[1].input.len(), 1);
2667                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2668                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2669                 check_spends!(node_txn[1], node_txn[0]);
2670
2671                 // Filter out any non justice transactions.
2672                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2673                 assert!(node_txn.len() > 3);
2674
2675                 assert_eq!(node_txn[0].input.len(), 1);
2676                 assert_eq!(node_txn[1].input.len(), 1);
2677                 assert_eq!(node_txn[2].input.len(), 1);
2678
2679                 check_spends!(node_txn[0], revoked_local_txn[0]);
2680                 check_spends!(node_txn[1], revoked_local_txn[0]);
2681                 check_spends!(node_txn[2], revoked_local_txn[0]);
2682
2683                 let mut witness_lens = BTreeSet::new();
2684                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2685                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2686                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2687                 assert_eq!(witness_lens.len(), 3);
2688                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2689                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2690                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2691
2692                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2693                 // ANTI_REORG_DELAY confirmations.
2694                 mine_transaction(&nodes[1], &node_txn[0]);
2695                 mine_transaction(&nodes[1], &node_txn[1]);
2696                 mine_transaction(&nodes[1], &node_txn[2]);
2697                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2698                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2699         }
2700         get_announce_close_broadcast_events(&nodes, 0, 1);
2701         assert_eq!(nodes[0].node.list_channels().len(), 0);
2702         assert_eq!(nodes[1].node.list_channels().len(), 0);
2703 }
2704
2705 #[test]
2706 fn test_htlc_on_chain_success() {
2707         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2708         // the preimage backward accordingly. So here we test that ChannelManager is
2709         // broadcasting the right event to other nodes in payment path.
2710         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2711         // A --------------------> B ----------------------> C (preimage)
2712         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2713         // commitment transaction was broadcast.
2714         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2715         // towards B.
2716         // B should be able to claim via preimage if A then broadcasts its local tx.
2717         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2718         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2719         // PaymentSent event).
2720
2721         let chanmon_cfgs = create_chanmon_cfgs(3);
2722         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2723         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2724         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2725
2726         // Create some initial channels
2727         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2728         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2729
2730         // Ensure all nodes are at the same height
2731         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2732         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2733         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2734         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2735
2736         // Rebalance the network a bit by relaying one payment through all the channels...
2737         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2738         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2739
2740         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2741         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2742
2743         // Broadcast legit commitment tx from C on B's chain
2744         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2745         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2746         assert_eq!(commitment_tx.len(), 1);
2747         check_spends!(commitment_tx[0], chan_2.3);
2748         nodes[2].node.claim_funds(our_payment_preimage);
2749         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2750         nodes[2].node.claim_funds(our_payment_preimage_2);
2751         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2752         check_added_monitors!(nodes[2], 2);
2753         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2754         assert!(updates.update_add_htlcs.is_empty());
2755         assert!(updates.update_fail_htlcs.is_empty());
2756         assert!(updates.update_fail_malformed_htlcs.is_empty());
2757         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2758
2759         mine_transaction(&nodes[2], &commitment_tx[0]);
2760         check_closed_broadcast!(nodes[2], true);
2761         check_added_monitors!(nodes[2], 1);
2762         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2763         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2764         assert_eq!(node_txn.len(), 2);
2765         check_spends!(node_txn[0], commitment_tx[0]);
2766         check_spends!(node_txn[1], commitment_tx[0]);
2767         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2768         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2769         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2770         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2771         assert_eq!(node_txn[0].lock_time.0, 0);
2772         assert_eq!(node_txn[1].lock_time.0, 0);
2773
2774         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2775         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()]));
2776         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2777         {
2778                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2779                 assert_eq!(added_monitors.len(), 1);
2780                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2781                 added_monitors.clear();
2782         }
2783         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2784         assert_eq!(forwarded_events.len(), 3);
2785         match forwarded_events[0] {
2786                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2787                 _ => panic!("Unexpected event"),
2788         }
2789         let chan_id = Some(chan_1.2);
2790         match forwarded_events[1] {
2791                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2792                         assert_eq!(fee_earned_msat, Some(1000));
2793                         assert_eq!(prev_channel_id, chan_id);
2794                         assert_eq!(claim_from_onchain_tx, true);
2795                         assert_eq!(next_channel_id, Some(chan_2.2));
2796                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2797                 },
2798                 _ => panic!()
2799         }
2800         match forwarded_events[2] {
2801                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2802                         assert_eq!(fee_earned_msat, Some(1000));
2803                         assert_eq!(prev_channel_id, chan_id);
2804                         assert_eq!(claim_from_onchain_tx, true);
2805                         assert_eq!(next_channel_id, Some(chan_2.2));
2806                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2807                 },
2808                 _ => panic!()
2809         }
2810         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2811         {
2812                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2813                 assert_eq!(added_monitors.len(), 2);
2814                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2815                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2816                 added_monitors.clear();
2817         }
2818         assert_eq!(events.len(), 3);
2819
2820         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2821         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2822
2823         match nodes_2_event {
2824                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2825                 _ => panic!("Unexpected event"),
2826         }
2827
2828         match nodes_0_event {
2829                 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, .. } } => {
2830                         assert!(update_add_htlcs.is_empty());
2831                         assert!(update_fail_htlcs.is_empty());
2832                         assert_eq!(update_fulfill_htlcs.len(), 1);
2833                         assert!(update_fail_malformed_htlcs.is_empty());
2834                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2835                 },
2836                 _ => panic!("Unexpected event"),
2837         };
2838
2839         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2840         match events[0] {
2841                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2842                 _ => panic!("Unexpected event"),
2843         }
2844
2845         macro_rules! check_tx_local_broadcast {
2846                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2847                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2848                         assert_eq!(node_txn.len(), 2);
2849                         // Node[1]: 2 * HTLC-timeout tx
2850                         // Node[0]: 2 * HTLC-timeout tx
2851                         check_spends!(node_txn[0], $commitment_tx);
2852                         check_spends!(node_txn[1], $commitment_tx);
2853                         assert_ne!(node_txn[0].lock_time.0, 0);
2854                         assert_ne!(node_txn[1].lock_time.0, 0);
2855                         if $htlc_offered {
2856                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2857                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2858                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2859                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2860                         } else {
2861                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2862                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2863                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2864                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2865                         }
2866                         node_txn.clear();
2867                 } }
2868         }
2869         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2870         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2871
2872         // Broadcast legit commitment tx from A on B's chain
2873         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2874         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2875         check_spends!(node_a_commitment_tx[0], chan_1.3);
2876         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2877         check_closed_broadcast!(nodes[1], true);
2878         check_added_monitors!(nodes[1], 1);
2879         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2880         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2881         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2882         let commitment_spend =
2883                 if node_txn.len() == 1 {
2884                         &node_txn[0]
2885                 } else {
2886                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2887                         // FullBlockViaListen
2888                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2889                                 check_spends!(node_txn[1], commitment_tx[0]);
2890                                 check_spends!(node_txn[2], commitment_tx[0]);
2891                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2892                                 &node_txn[0]
2893                         } else {
2894                                 check_spends!(node_txn[0], commitment_tx[0]);
2895                                 check_spends!(node_txn[1], commitment_tx[0]);
2896                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2897                                 &node_txn[2]
2898                         }
2899                 };
2900
2901         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2902         assert_eq!(commitment_spend.input.len(), 2);
2903         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2904         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2905         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2906         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2907         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2908         // we already checked the same situation with A.
2909
2910         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2911         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2912         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2913         check_closed_broadcast!(nodes[0], true);
2914         check_added_monitors!(nodes[0], 1);
2915         let events = nodes[0].node.get_and_clear_pending_events();
2916         assert_eq!(events.len(), 5);
2917         let mut first_claimed = false;
2918         for event in events {
2919                 match event {
2920                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2921                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2922                                         assert!(!first_claimed);
2923                                         first_claimed = true;
2924                                 } else {
2925                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2926                                         assert_eq!(payment_hash, payment_hash_2);
2927                                 }
2928                         },
2929                         Event::PaymentPathSuccessful { .. } => {},
2930                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2931                         _ => panic!("Unexpected event"),
2932                 }
2933         }
2934         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2935 }
2936
2937 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2938         // Test that in case of a unilateral close onchain, we detect the state of output and
2939         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2940         // broadcasting the right event to other nodes in payment path.
2941         // A ------------------> B ----------------------> C (timeout)
2942         //    B's commitment tx                 C's commitment tx
2943         //            \                                  \
2944         //         B's HTLC timeout tx               B's timeout tx
2945
2946         let chanmon_cfgs = create_chanmon_cfgs(3);
2947         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2948         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2949         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2950         *nodes[0].connect_style.borrow_mut() = connect_style;
2951         *nodes[1].connect_style.borrow_mut() = connect_style;
2952         *nodes[2].connect_style.borrow_mut() = connect_style;
2953
2954         // Create some intial channels
2955         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2956         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2957
2958         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2959         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2960         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2961
2962         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2963
2964         // Broadcast legit commitment tx from C on B's chain
2965         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2966         check_spends!(commitment_tx[0], chan_2.3);
2967         nodes[2].node.fail_htlc_backwards(&payment_hash);
2968         check_added_monitors!(nodes[2], 0);
2969         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2970         check_added_monitors!(nodes[2], 1);
2971
2972         let events = nodes[2].node.get_and_clear_pending_msg_events();
2973         assert_eq!(events.len(), 1);
2974         match events[0] {
2975                 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, .. } } => {
2976                         assert!(update_add_htlcs.is_empty());
2977                         assert!(!update_fail_htlcs.is_empty());
2978                         assert!(update_fulfill_htlcs.is_empty());
2979                         assert!(update_fail_malformed_htlcs.is_empty());
2980                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2981                 },
2982                 _ => panic!("Unexpected event"),
2983         };
2984         mine_transaction(&nodes[2], &commitment_tx[0]);
2985         check_closed_broadcast!(nodes[2], true);
2986         check_added_monitors!(nodes[2], 1);
2987         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2988         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2989         assert_eq!(node_txn.len(), 0);
2990
2991         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2992         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2993         mine_transaction(&nodes[1], &commitment_tx[0]);
2994         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2995         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2996         let timeout_tx = {
2997                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2998                 if nodes[1].connect_style.borrow().skips_blocks() {
2999                         assert_eq!(txn.len(), 1);
3000                 } else {
3001                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3002                 }
3003                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3004                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3005                 txn.remove(0)
3006         };
3007
3008         mine_transaction(&nodes[1], &timeout_tx);
3009         check_added_monitors!(nodes[1], 1);
3010         check_closed_broadcast!(nodes[1], true);
3011
3012         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3013
3014         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 }]);
3015         check_added_monitors!(nodes[1], 1);
3016         let events = nodes[1].node.get_and_clear_pending_msg_events();
3017         assert_eq!(events.len(), 1);
3018         match events[0] {
3019                 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, .. } } => {
3020                         assert!(update_add_htlcs.is_empty());
3021                         assert!(!update_fail_htlcs.is_empty());
3022                         assert!(update_fulfill_htlcs.is_empty());
3023                         assert!(update_fail_malformed_htlcs.is_empty());
3024                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3025                 },
3026                 _ => panic!("Unexpected event"),
3027         };
3028
3029         // Broadcast legit commitment tx from B on A's chain
3030         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3031         check_spends!(commitment_tx[0], chan_1.3);
3032
3033         mine_transaction(&nodes[0], &commitment_tx[0]);
3034         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3035
3036         check_closed_broadcast!(nodes[0], true);
3037         check_added_monitors!(nodes[0], 1);
3038         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3039         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3040         assert_eq!(node_txn.len(), 1);
3041         check_spends!(node_txn[0], commitment_tx[0]);
3042         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3043 }
3044
3045 #[test]
3046 fn test_htlc_on_chain_timeout() {
3047         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3048         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3049         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3050 }
3051
3052 #[test]
3053 fn test_simple_commitment_revoked_fail_backward() {
3054         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3055         // and fail backward accordingly.
3056
3057         let chanmon_cfgs = create_chanmon_cfgs(3);
3058         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3059         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3060         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3061
3062         // Create some initial channels
3063         create_announced_chan_between_nodes(&nodes, 0, 1);
3064         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3065
3066         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3067         // Get the will-be-revoked local txn from nodes[2]
3068         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3069         // Revoke the old state
3070         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3071
3072         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3073
3074         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3075         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3076         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3077         check_added_monitors!(nodes[1], 1);
3078         check_closed_broadcast!(nodes[1], true);
3079
3080         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 }]);
3081         check_added_monitors!(nodes[1], 1);
3082         let events = nodes[1].node.get_and_clear_pending_msg_events();
3083         assert_eq!(events.len(), 1);
3084         match events[0] {
3085                 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, .. } } => {
3086                         assert!(update_add_htlcs.is_empty());
3087                         assert_eq!(update_fail_htlcs.len(), 1);
3088                         assert!(update_fulfill_htlcs.is_empty());
3089                         assert!(update_fail_malformed_htlcs.is_empty());
3090                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3091
3092                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3093                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3094                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3095                 },
3096                 _ => panic!("Unexpected event"),
3097         }
3098 }
3099
3100 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3101         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3102         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3103         // commitment transaction anymore.
3104         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3105         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3106         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3107         // technically disallowed and we should probably handle it reasonably.
3108         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3109         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3110         // transactions:
3111         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3112         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3113         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3114         //   and once they revoke the previous commitment transaction (allowing us to send a new
3115         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3116         let chanmon_cfgs = create_chanmon_cfgs(3);
3117         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3118         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3119         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3120
3121         // Create some initial channels
3122         create_announced_chan_between_nodes(&nodes, 0, 1);
3123         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3124
3125         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 });
3126         // Get the will-be-revoked local txn from nodes[2]
3127         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3128         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3129         // Revoke the old state
3130         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3131
3132         let value = if use_dust {
3133                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3134                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3135                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3136                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3137         } else { 3000000 };
3138
3139         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3140         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3141         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3142
3143         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3144         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3145         check_added_monitors!(nodes[2], 1);
3146         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3147         assert!(updates.update_add_htlcs.is_empty());
3148         assert!(updates.update_fulfill_htlcs.is_empty());
3149         assert!(updates.update_fail_malformed_htlcs.is_empty());
3150         assert_eq!(updates.update_fail_htlcs.len(), 1);
3151         assert!(updates.update_fee.is_none());
3152         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3153         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3154         // Drop the last RAA from 3 -> 2
3155
3156         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3157         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3158         check_added_monitors!(nodes[2], 1);
3159         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3160         assert!(updates.update_add_htlcs.is_empty());
3161         assert!(updates.update_fulfill_htlcs.is_empty());
3162         assert!(updates.update_fail_malformed_htlcs.is_empty());
3163         assert_eq!(updates.update_fail_htlcs.len(), 1);
3164         assert!(updates.update_fee.is_none());
3165         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3166         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3167         check_added_monitors!(nodes[1], 1);
3168         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3169         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3170         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3171         check_added_monitors!(nodes[2], 1);
3172
3173         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3174         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3175         check_added_monitors!(nodes[2], 1);
3176         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3177         assert!(updates.update_add_htlcs.is_empty());
3178         assert!(updates.update_fulfill_htlcs.is_empty());
3179         assert!(updates.update_fail_malformed_htlcs.is_empty());
3180         assert_eq!(updates.update_fail_htlcs.len(), 1);
3181         assert!(updates.update_fee.is_none());
3182         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3183         // At this point first_payment_hash has dropped out of the latest two commitment
3184         // transactions that nodes[1] is tracking...
3185         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3186         check_added_monitors!(nodes[1], 1);
3187         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3188         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3189         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3190         check_added_monitors!(nodes[2], 1);
3191
3192         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3193         // on nodes[2]'s RAA.
3194         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3195         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3196                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3197         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3198         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3199         check_added_monitors!(nodes[1], 0);
3200
3201         if deliver_bs_raa {
3202                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3203                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3204                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3205                 check_added_monitors!(nodes[1], 1);
3206                 let events = nodes[1].node.get_and_clear_pending_events();
3207                 assert_eq!(events.len(), 2);
3208                 match events[0] {
3209                         Event::PendingHTLCsForwardable { .. } => { },
3210                         _ => panic!("Unexpected event"),
3211                 };
3212                 match events[1] {
3213                         Event::HTLCHandlingFailed { .. } => { },
3214                         _ => panic!("Unexpected event"),
3215                 }
3216                 // Deliberately don't process the pending fail-back so they all fail back at once after
3217                 // block connection just like the !deliver_bs_raa case
3218         }
3219
3220         let mut failed_htlcs = HashSet::new();
3221         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3222
3223         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3224         check_added_monitors!(nodes[1], 1);
3225         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3226
3227         let events = nodes[1].node.get_and_clear_pending_events();
3228         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3229         match events[0] {
3230                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3231                 _ => panic!("Unexepected event"),
3232         }
3233         match events[1] {
3234                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3235                         assert_eq!(*payment_hash, fourth_payment_hash);
3236                 },
3237                 _ => panic!("Unexpected event"),
3238         }
3239         match events[2] {
3240                 Event::PaymentFailed { ref payment_hash, .. } => {
3241                         assert_eq!(*payment_hash, fourth_payment_hash);
3242                 },
3243                 _ => panic!("Unexpected event"),
3244         }
3245
3246         nodes[1].node.process_pending_htlc_forwards();
3247         check_added_monitors!(nodes[1], 1);
3248
3249         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3250         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3251
3252         if deliver_bs_raa {
3253                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3254                 match nodes_2_event {
3255                         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, .. } } => {
3256                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3257                                 assert_eq!(update_add_htlcs.len(), 1);
3258                                 assert!(update_fulfill_htlcs.is_empty());
3259                                 assert!(update_fail_htlcs.is_empty());
3260                                 assert!(update_fail_malformed_htlcs.is_empty());
3261                         },
3262                         _ => panic!("Unexpected event"),
3263                 }
3264         }
3265
3266         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3267         match nodes_2_event {
3268                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3269                         assert_eq!(channel_id, chan_2.2);
3270                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3271                 },
3272                 _ => panic!("Unexpected event"),
3273         }
3274
3275         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3276         match nodes_0_event {
3277                 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, .. } } => {
3278                         assert!(update_add_htlcs.is_empty());
3279                         assert_eq!(update_fail_htlcs.len(), 3);
3280                         assert!(update_fulfill_htlcs.is_empty());
3281                         assert!(update_fail_malformed_htlcs.is_empty());
3282                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3283
3284                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3285                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3286                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3287
3288                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3289
3290                         let events = nodes[0].node.get_and_clear_pending_events();
3291                         assert_eq!(events.len(), 6);
3292                         match events[0] {
3293                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3294                                         assert!(failed_htlcs.insert(payment_hash.0));
3295                                         // If we delivered B's RAA we got an unknown preimage error, not something
3296                                         // that we should update our routing table for.
3297                                         if !deliver_bs_raa {
3298                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3299                                         }
3300                                 },
3301                                 _ => panic!("Unexpected event"),
3302                         }
3303                         match events[1] {
3304                                 Event::PaymentFailed { ref payment_hash, .. } => {
3305                                         assert_eq!(*payment_hash, first_payment_hash);
3306                                 },
3307                                 _ => panic!("Unexpected event"),
3308                         }
3309                         match events[2] {
3310                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3311                                         assert!(failed_htlcs.insert(payment_hash.0));
3312                                 },
3313                                 _ => panic!("Unexpected event"),
3314                         }
3315                         match events[3] {
3316                                 Event::PaymentFailed { ref payment_hash, .. } => {
3317                                         assert_eq!(*payment_hash, second_payment_hash);
3318                                 },
3319                                 _ => panic!("Unexpected event"),
3320                         }
3321                         match events[4] {
3322                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3323                                         assert!(failed_htlcs.insert(payment_hash.0));
3324                                 },
3325                                 _ => panic!("Unexpected event"),
3326                         }
3327                         match events[5] {
3328                                 Event::PaymentFailed { ref payment_hash, .. } => {
3329                                         assert_eq!(*payment_hash, third_payment_hash);
3330                                 },
3331                                 _ => panic!("Unexpected event"),
3332                         }
3333                 },
3334                 _ => panic!("Unexpected event"),
3335         }
3336
3337         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3338         match events[0] {
3339                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3340                 _ => panic!("Unexpected event"),
3341         }
3342
3343         assert!(failed_htlcs.contains(&first_payment_hash.0));
3344         assert!(failed_htlcs.contains(&second_payment_hash.0));
3345         assert!(failed_htlcs.contains(&third_payment_hash.0));
3346 }
3347
3348 #[test]
3349 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3350         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3351         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3352         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3353         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3354 }
3355
3356 #[test]
3357 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3358         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3359         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3360         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3361         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3362 }
3363
3364 #[test]
3365 fn fail_backward_pending_htlc_upon_channel_failure() {
3366         let chanmon_cfgs = create_chanmon_cfgs(2);
3367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3369         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3370         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3371
3372         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3373         {
3374                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3375                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3376                         PaymentId(payment_hash.0)).unwrap();
3377                 check_added_monitors!(nodes[0], 1);
3378
3379                 let payment_event = {
3380                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3381                         assert_eq!(events.len(), 1);
3382                         SendEvent::from_event(events.remove(0))
3383                 };
3384                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3385                 assert_eq!(payment_event.msgs.len(), 1);
3386         }
3387
3388         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3389         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3390         {
3391                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3392                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3393                 check_added_monitors!(nodes[0], 0);
3394
3395                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3396         }
3397
3398         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3399         {
3400                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3401
3402                 let secp_ctx = Secp256k1::new();
3403                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3404                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3405                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3406                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3407                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3408                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3409
3410                 // Send a 0-msat update_add_htlc to fail the channel.
3411                 let update_add_htlc = msgs::UpdateAddHTLC {
3412                         channel_id: chan.2,
3413                         htlc_id: 0,
3414                         amount_msat: 0,
3415                         payment_hash,
3416                         cltv_expiry,
3417                         onion_routing_packet,
3418                         skimmed_fee_msat: None,
3419                 };
3420                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3421         }
3422         let events = nodes[0].node.get_and_clear_pending_events();
3423         assert_eq!(events.len(), 3);
3424         // Check that Alice fails backward the pending HTLC from the second payment.
3425         match events[0] {
3426                 Event::PaymentPathFailed { payment_hash, .. } => {
3427                         assert_eq!(payment_hash, failed_payment_hash);
3428                 },
3429                 _ => panic!("Unexpected event"),
3430         }
3431         match events[1] {
3432                 Event::PaymentFailed { payment_hash, .. } => {
3433                         assert_eq!(payment_hash, failed_payment_hash);
3434                 },
3435                 _ => panic!("Unexpected event"),
3436         }
3437         match events[2] {
3438                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3439                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3440                 },
3441                 _ => panic!("Unexpected event {:?}", events[1]),
3442         }
3443         check_closed_broadcast!(nodes[0], true);
3444         check_added_monitors!(nodes[0], 1);
3445 }
3446
3447 #[test]
3448 fn test_htlc_ignore_latest_remote_commitment() {
3449         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3450         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3451         let chanmon_cfgs = create_chanmon_cfgs(2);
3452         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3453         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3454         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3455         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3456                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3457                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3458                 // connect_style.
3459                 return;
3460         }
3461         create_announced_chan_between_nodes(&nodes, 0, 1);
3462
3463         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3464         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3465         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3466         check_closed_broadcast!(nodes[0], true);
3467         check_added_monitors!(nodes[0], 1);
3468         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3469
3470         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3471         assert_eq!(node_txn.len(), 3);
3472         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3473
3474         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3475         connect_block(&nodes[1], &block);
3476         check_closed_broadcast!(nodes[1], true);
3477         check_added_monitors!(nodes[1], 1);
3478         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3479
3480         // Duplicate the connect_block call since this may happen due to other listeners
3481         // registering new transactions
3482         connect_block(&nodes[1], &block);
3483 }
3484
3485 #[test]
3486 fn test_force_close_fail_back() {
3487         // Check which HTLCs are failed-backwards on channel force-closure
3488         let chanmon_cfgs = create_chanmon_cfgs(3);
3489         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3490         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3491         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3492         create_announced_chan_between_nodes(&nodes, 0, 1);
3493         create_announced_chan_between_nodes(&nodes, 1, 2);
3494
3495         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3496
3497         let mut payment_event = {
3498                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3499                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3500                 check_added_monitors!(nodes[0], 1);
3501
3502                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3503                 assert_eq!(events.len(), 1);
3504                 SendEvent::from_event(events.remove(0))
3505         };
3506
3507         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3508         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3509
3510         expect_pending_htlcs_forwardable!(nodes[1]);
3511
3512         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3513         assert_eq!(events_2.len(), 1);
3514         payment_event = SendEvent::from_event(events_2.remove(0));
3515         assert_eq!(payment_event.msgs.len(), 1);
3516
3517         check_added_monitors!(nodes[1], 1);
3518         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3519         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3520         check_added_monitors!(nodes[2], 1);
3521         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3522
3523         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3524         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3525         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3526
3527         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3528         check_closed_broadcast!(nodes[2], true);
3529         check_added_monitors!(nodes[2], 1);
3530         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3531         let tx = {
3532                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3533                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3534                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3535                 // back to nodes[1] upon timeout otherwise.
3536                 assert_eq!(node_txn.len(), 1);
3537                 node_txn.remove(0)
3538         };
3539
3540         mine_transaction(&nodes[1], &tx);
3541
3542         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3543         check_closed_broadcast!(nodes[1], true);
3544         check_added_monitors!(nodes[1], 1);
3545         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3546
3547         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3548         {
3549                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3550                         .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);
3551         }
3552         mine_transaction(&nodes[2], &tx);
3553         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3554         assert_eq!(node_txn.len(), 1);
3555         assert_eq!(node_txn[0].input.len(), 1);
3556         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3557         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3558         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3559
3560         check_spends!(node_txn[0], tx);
3561 }
3562
3563 #[test]
3564 fn test_dup_events_on_peer_disconnect() {
3565         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3566         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3567         // as we used to generate the event immediately upon receipt of the payment preimage in the
3568         // update_fulfill_htlc message.
3569
3570         let chanmon_cfgs = create_chanmon_cfgs(2);
3571         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3572         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3573         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3574         create_announced_chan_between_nodes(&nodes, 0, 1);
3575
3576         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3577
3578         nodes[1].node.claim_funds(payment_preimage);
3579         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3580         check_added_monitors!(nodes[1], 1);
3581         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3582         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3583         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3584
3585         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3586         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3587
3588         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3589         expect_payment_path_successful!(nodes[0]);
3590 }
3591
3592 #[test]
3593 fn test_peer_disconnected_before_funding_broadcasted() {
3594         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3595         // before the funding transaction has been broadcasted.
3596         let chanmon_cfgs = create_chanmon_cfgs(2);
3597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3599         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3600
3601         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3602         // broadcasted, even though it's created by `nodes[0]`.
3603         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();
3604         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3605         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3606         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3607         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3608
3609         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3610         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3611
3612         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3613
3614         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3615         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3616
3617         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3618         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3619         // broadcasted.
3620         {
3621                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3622         }
3623
3624         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3625         // disconnected before the funding transaction was broadcasted.
3626         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3627         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3628
3629         check_closed_event(&nodes[0], 1, ClosureReason::DisconnectedPeer, false);
3630         check_closed_event(&nodes[1], 1, ClosureReason::DisconnectedPeer, false);
3631 }
3632
3633 #[test]
3634 fn test_simple_peer_disconnect() {
3635         // Test that we can reconnect when there are no lost messages
3636         let chanmon_cfgs = create_chanmon_cfgs(3);
3637         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3638         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3639         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3640         create_announced_chan_between_nodes(&nodes, 0, 1);
3641         create_announced_chan_between_nodes(&nodes, 1, 2);
3642
3643         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3644         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3645         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3646
3647         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3648         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3649         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3650         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3651
3652         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3653         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3654         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3655
3656         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3657         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3658         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3659         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3660
3661         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3662         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3663
3664         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3665         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3666
3667         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3668         {
3669                 let events = nodes[0].node.get_and_clear_pending_events();
3670                 assert_eq!(events.len(), 4);
3671                 match events[0] {
3672                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3673                                 assert_eq!(payment_preimage, payment_preimage_3);
3674                                 assert_eq!(payment_hash, payment_hash_3);
3675                         },
3676                         _ => panic!("Unexpected event"),
3677                 }
3678                 match events[1] {
3679                         Event::PaymentPathSuccessful { .. } => {},
3680                         _ => panic!("Unexpected event"),
3681                 }
3682                 match events[2] {
3683                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3684                                 assert_eq!(payment_hash, payment_hash_5);
3685                                 assert!(payment_failed_permanently);
3686                         },
3687                         _ => panic!("Unexpected event"),
3688                 }
3689                 match events[3] {
3690                         Event::PaymentFailed { payment_hash, .. } => {
3691                                 assert_eq!(payment_hash, payment_hash_5);
3692                         },
3693                         _ => panic!("Unexpected event"),
3694                 }
3695         }
3696
3697         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3698         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3699 }
3700
3701 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3702         // Test that we can reconnect when in-flight HTLC updates get dropped
3703         let chanmon_cfgs = create_chanmon_cfgs(2);
3704         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3705         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3706         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3707
3708         let mut as_channel_ready = None;
3709         let channel_id = if messages_delivered == 0 {
3710                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3711                 as_channel_ready = Some(channel_ready);
3712                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3713                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3714                 // it before the channel_reestablish message.
3715                 chan_id
3716         } else {
3717                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3718         };
3719
3720         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3721
3722         let payment_event = {
3723                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3724                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3725                 check_added_monitors!(nodes[0], 1);
3726
3727                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3728                 assert_eq!(events.len(), 1);
3729                 SendEvent::from_event(events.remove(0))
3730         };
3731         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3732
3733         if messages_delivered < 2 {
3734                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3735         } else {
3736                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3737                 if messages_delivered >= 3 {
3738                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3739                         check_added_monitors!(nodes[1], 1);
3740                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3741
3742                         if messages_delivered >= 4 {
3743                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3744                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3745                                 check_added_monitors!(nodes[0], 1);
3746
3747                                 if messages_delivered >= 5 {
3748                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3749                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3750                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3751                                         check_added_monitors!(nodes[0], 1);
3752
3753                                         if messages_delivered >= 6 {
3754                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3755                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3756                                                 check_added_monitors!(nodes[1], 1);
3757                                         }
3758                                 }
3759                         }
3760                 }
3761         }
3762
3763         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3764         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3765         if messages_delivered < 3 {
3766                 if simulate_broken_lnd {
3767                         // lnd has a long-standing bug where they send a channel_ready prior to a
3768                         // channel_reestablish if you reconnect prior to channel_ready time.
3769                         //
3770                         // Here we simulate that behavior, delivering a channel_ready immediately on
3771                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3772                         // in `reconnect_nodes` but we currently don't fail based on that.
3773                         //
3774                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3775                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3776                 }
3777                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3778                 // received on either side, both sides will need to resend them.
3779                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3780         } else if messages_delivered == 3 {
3781                 // nodes[0] still wants its RAA + commitment_signed
3782                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3783         } else if messages_delivered == 4 {
3784                 // nodes[0] still wants its commitment_signed
3785                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3786         } else if messages_delivered == 5 {
3787                 // nodes[1] still wants its final RAA
3788                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3789         } else if messages_delivered == 6 {
3790                 // Everything was delivered...
3791                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3792         }
3793
3794         let events_1 = nodes[1].node.get_and_clear_pending_events();
3795         if messages_delivered == 0 {
3796                 assert_eq!(events_1.len(), 2);
3797                 match events_1[0] {
3798                         Event::ChannelReady { .. } => { },
3799                         _ => panic!("Unexpected event"),
3800                 };
3801                 match events_1[1] {
3802                         Event::PendingHTLCsForwardable { .. } => { },
3803                         _ => panic!("Unexpected event"),
3804                 };
3805         } else {
3806                 assert_eq!(events_1.len(), 1);
3807                 match events_1[0] {
3808                         Event::PendingHTLCsForwardable { .. } => { },
3809                         _ => panic!("Unexpected event"),
3810                 };
3811         }
3812
3813         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3814         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3815         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816
3817         nodes[1].node.process_pending_htlc_forwards();
3818
3819         let events_2 = nodes[1].node.get_and_clear_pending_events();
3820         assert_eq!(events_2.len(), 1);
3821         match events_2[0] {
3822                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3823                         assert_eq!(payment_hash_1, *payment_hash);
3824                         assert_eq!(amount_msat, 1_000_000);
3825                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3826                         assert_eq!(via_channel_id, Some(channel_id));
3827                         match &purpose {
3828                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3829                                         assert!(payment_preimage.is_none());
3830                                         assert_eq!(payment_secret_1, *payment_secret);
3831                                 },
3832                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3833                         }
3834                 },
3835                 _ => panic!("Unexpected event"),
3836         }
3837
3838         nodes[1].node.claim_funds(payment_preimage_1);
3839         check_added_monitors!(nodes[1], 1);
3840         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3841
3842         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3843         assert_eq!(events_3.len(), 1);
3844         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3845                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3846                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3847                         assert!(updates.update_add_htlcs.is_empty());
3848                         assert!(updates.update_fail_htlcs.is_empty());
3849                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3850                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3851                         assert!(updates.update_fee.is_none());
3852                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3853                 },
3854                 _ => panic!("Unexpected event"),
3855         };
3856
3857         if messages_delivered >= 1 {
3858                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3859
3860                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3861                 assert_eq!(events_4.len(), 1);
3862                 match events_4[0] {
3863                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3864                                 assert_eq!(payment_preimage_1, *payment_preimage);
3865                                 assert_eq!(payment_hash_1, *payment_hash);
3866                         },
3867                         _ => panic!("Unexpected event"),
3868                 }
3869
3870                 if messages_delivered >= 2 {
3871                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3872                         check_added_monitors!(nodes[0], 1);
3873                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3874
3875                         if messages_delivered >= 3 {
3876                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3877                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3878                                 check_added_monitors!(nodes[1], 1);
3879
3880                                 if messages_delivered >= 4 {
3881                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3882                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3883                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3884                                         check_added_monitors!(nodes[1], 1);
3885
3886                                         if messages_delivered >= 5 {
3887                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3888                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3889                                                 check_added_monitors!(nodes[0], 1);
3890                                         }
3891                                 }
3892                         }
3893                 }
3894         }
3895
3896         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3897         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3898         if messages_delivered < 2 {
3899                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3900                 if messages_delivered < 1 {
3901                         expect_payment_sent!(nodes[0], payment_preimage_1);
3902                 } else {
3903                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3904                 }
3905         } else if messages_delivered == 2 {
3906                 // nodes[0] still wants its RAA + commitment_signed
3907                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3908         } else if messages_delivered == 3 {
3909                 // nodes[0] still wants its commitment_signed
3910                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3911         } else if messages_delivered == 4 {
3912                 // nodes[1] still wants its final RAA
3913                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3914         } else if messages_delivered == 5 {
3915                 // Everything was delivered...
3916                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3917         }
3918
3919         if messages_delivered == 1 || messages_delivered == 2 {
3920                 expect_payment_path_successful!(nodes[0]);
3921         }
3922         if messages_delivered <= 5 {
3923                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3924                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3925         }
3926         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3927
3928         if messages_delivered > 2 {
3929                 expect_payment_path_successful!(nodes[0]);
3930         }
3931
3932         // Channel should still work fine...
3933         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3934         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3935         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3936 }
3937
3938 #[test]
3939 fn test_drop_messages_peer_disconnect_a() {
3940         do_test_drop_messages_peer_disconnect(0, true);
3941         do_test_drop_messages_peer_disconnect(0, false);
3942         do_test_drop_messages_peer_disconnect(1, false);
3943         do_test_drop_messages_peer_disconnect(2, false);
3944 }
3945
3946 #[test]
3947 fn test_drop_messages_peer_disconnect_b() {
3948         do_test_drop_messages_peer_disconnect(3, false);
3949         do_test_drop_messages_peer_disconnect(4, false);
3950         do_test_drop_messages_peer_disconnect(5, false);
3951         do_test_drop_messages_peer_disconnect(6, false);
3952 }
3953
3954 #[test]
3955 fn test_channel_ready_without_best_block_updated() {
3956         // Previously, if we were offline when a funding transaction was locked in, and then we came
3957         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3958         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3959         // channel_ready immediately instead.
3960         let chanmon_cfgs = create_chanmon_cfgs(2);
3961         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3962         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3963         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3964         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3965
3966         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3967
3968         let conf_height = nodes[0].best_block_info().1 + 1;
3969         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3970         let block_txn = [funding_tx];
3971         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3972         let conf_block_header = nodes[0].get_block_header(conf_height);
3973         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3974
3975         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3976         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3977         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3978 }
3979
3980 #[test]
3981 fn test_drop_messages_peer_disconnect_dual_htlc() {
3982         // Test that we can handle reconnecting when both sides of a channel have pending
3983         // commitment_updates when we disconnect.
3984         let chanmon_cfgs = create_chanmon_cfgs(2);
3985         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3986         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3987         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3988         create_announced_chan_between_nodes(&nodes, 0, 1);
3989
3990         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3991
3992         // Now try to send a second payment which will fail to send
3993         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3994         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3995                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3996         check_added_monitors!(nodes[0], 1);
3997
3998         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3999         assert_eq!(events_1.len(), 1);
4000         match events_1[0] {
4001                 MessageSendEvent::UpdateHTLCs { .. } => {},
4002                 _ => panic!("Unexpected event"),
4003         }
4004
4005         nodes[1].node.claim_funds(payment_preimage_1);
4006         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4007         check_added_monitors!(nodes[1], 1);
4008
4009         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4010         assert_eq!(events_2.len(), 1);
4011         match events_2[0] {
4012                 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 } } => {
4013                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4014                         assert!(update_add_htlcs.is_empty());
4015                         assert_eq!(update_fulfill_htlcs.len(), 1);
4016                         assert!(update_fail_htlcs.is_empty());
4017                         assert!(update_fail_malformed_htlcs.is_empty());
4018                         assert!(update_fee.is_none());
4019
4020                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4021                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4022                         assert_eq!(events_3.len(), 1);
4023                         match events_3[0] {
4024                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4025                                         assert_eq!(*payment_preimage, payment_preimage_1);
4026                                         assert_eq!(*payment_hash, payment_hash_1);
4027                                 },
4028                                 _ => panic!("Unexpected event"),
4029                         }
4030
4031                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4032                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4033                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4034                         check_added_monitors!(nodes[0], 1);
4035                 },
4036                 _ => panic!("Unexpected event"),
4037         }
4038
4039         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4040         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4041
4042         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4043                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4044         }, true).unwrap();
4045         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4046         assert_eq!(reestablish_1.len(), 1);
4047         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4048                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4049         }, false).unwrap();
4050         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4051         assert_eq!(reestablish_2.len(), 1);
4052
4053         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4054         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4055         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4056         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4057
4058         assert!(as_resp.0.is_none());
4059         assert!(bs_resp.0.is_none());
4060
4061         assert!(bs_resp.1.is_none());
4062         assert!(bs_resp.2.is_none());
4063
4064         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4065
4066         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4067         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4068         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4069         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4070         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4071         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4072         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4073         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4074         // No commitment_signed so get_event_msg's assert(len == 1) passes
4075         check_added_monitors!(nodes[1], 1);
4076
4077         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4078         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4079         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4080         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4081         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4082         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4083         assert!(bs_second_commitment_signed.update_fee.is_none());
4084         check_added_monitors!(nodes[1], 1);
4085
4086         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4087         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4088         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4089         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4090         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4091         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4092         assert!(as_commitment_signed.update_fee.is_none());
4093         check_added_monitors!(nodes[0], 1);
4094
4095         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4096         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4097         // No commitment_signed so get_event_msg's assert(len == 1) passes
4098         check_added_monitors!(nodes[0], 1);
4099
4100         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4101         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4102         // No commitment_signed so get_event_msg's assert(len == 1) passes
4103         check_added_monitors!(nodes[1], 1);
4104
4105         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4106         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4107         check_added_monitors!(nodes[1], 1);
4108
4109         expect_pending_htlcs_forwardable!(nodes[1]);
4110
4111         let events_5 = nodes[1].node.get_and_clear_pending_events();
4112         assert_eq!(events_5.len(), 1);
4113         match events_5[0] {
4114                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4115                         assert_eq!(payment_hash_2, *payment_hash);
4116                         match &purpose {
4117                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4118                                         assert!(payment_preimage.is_none());
4119                                         assert_eq!(payment_secret_2, *payment_secret);
4120                                 },
4121                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4122                         }
4123                 },
4124                 _ => panic!("Unexpected event"),
4125         }
4126
4127         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4128         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4129         check_added_monitors!(nodes[0], 1);
4130
4131         expect_payment_path_successful!(nodes[0]);
4132         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4133 }
4134
4135 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4136         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4137         // to avoid our counterparty failing the channel.
4138         let chanmon_cfgs = create_chanmon_cfgs(2);
4139         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4140         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4141         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4142
4143         create_announced_chan_between_nodes(&nodes, 0, 1);
4144
4145         let our_payment_hash = if send_partial_mpp {
4146                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4147                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4148                 // indicates there are more HTLCs coming.
4149                 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.
4150                 let payment_id = PaymentId([42; 32]);
4151                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4152                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4153                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4154                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4155                         &None, session_privs[0]).unwrap();
4156                 check_added_monitors!(nodes[0], 1);
4157                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4158                 assert_eq!(events.len(), 1);
4159                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4160                 // hop should *not* yet generate any PaymentClaimable event(s).
4161                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4162                 our_payment_hash
4163         } else {
4164                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4165         };
4166
4167         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4168         connect_block(&nodes[0], &block);
4169         connect_block(&nodes[1], &block);
4170         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4171         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4172                 block.header.prev_blockhash = block.block_hash();
4173                 connect_block(&nodes[0], &block);
4174                 connect_block(&nodes[1], &block);
4175         }
4176
4177         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4178
4179         check_added_monitors!(nodes[1], 1);
4180         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4181         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4182         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4183         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4184         assert!(htlc_timeout_updates.update_fee.is_none());
4185
4186         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4187         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4188         // 100_000 msat as u64, followed by the height at which we failed back above
4189         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4190         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4191         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4192 }
4193
4194 #[test]
4195 fn test_htlc_timeout() {
4196         do_test_htlc_timeout(true);
4197         do_test_htlc_timeout(false);
4198 }
4199
4200 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4201         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4202         let chanmon_cfgs = create_chanmon_cfgs(3);
4203         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4204         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4205         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4206         create_announced_chan_between_nodes(&nodes, 0, 1);
4207         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4208
4209         // Make sure all nodes are at the same starting height
4210         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4211         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4212         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4213
4214         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4215         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4216         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4217                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4218         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4219         check_added_monitors!(nodes[1], 1);
4220
4221         // Now attempt to route a second payment, which should be placed in the holding cell
4222         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4223         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4224         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4225                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4226         if forwarded_htlc {
4227                 check_added_monitors!(nodes[0], 1);
4228                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4229                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4230                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4231                 expect_pending_htlcs_forwardable!(nodes[1]);
4232         }
4233         check_added_monitors!(nodes[1], 0);
4234
4235         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4236         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4237         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4238         connect_blocks(&nodes[1], 1);
4239
4240         if forwarded_htlc {
4241                 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 }]);
4242                 check_added_monitors!(nodes[1], 1);
4243                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4244                 assert_eq!(fail_commit.len(), 1);
4245                 match fail_commit[0] {
4246                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4247                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4248                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4249                         },
4250                         _ => unreachable!(),
4251                 }
4252                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4253         } else {
4254                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4255         }
4256 }
4257
4258 #[test]
4259 fn test_holding_cell_htlc_add_timeouts() {
4260         do_test_holding_cell_htlc_add_timeouts(false);
4261         do_test_holding_cell_htlc_add_timeouts(true);
4262 }
4263
4264 macro_rules! check_spendable_outputs {
4265         ($node: expr, $keysinterface: expr) => {
4266                 {
4267                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4268                         let mut txn = Vec::new();
4269                         let mut all_outputs = Vec::new();
4270                         let secp_ctx = Secp256k1::new();
4271                         for event in events.drain(..) {
4272                                 match event {
4273                                         Event::SpendableOutputs { mut outputs } => {
4274                                                 for outp in outputs.drain(..) {
4275                                                         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());
4276                                                         all_outputs.push(outp);
4277                                                 }
4278                                         },
4279                                         _ => panic!("Unexpected event"),
4280                                 };
4281                         }
4282                         if all_outputs.len() > 1 {
4283                                 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) {
4284                                         txn.push(tx);
4285                                 }
4286                         }
4287                         txn
4288                 }
4289         }
4290 }
4291
4292 #[test]
4293 fn test_claim_sizeable_push_msat() {
4294         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4295         let chanmon_cfgs = create_chanmon_cfgs(2);
4296         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4297         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4298         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4299
4300         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4301         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4302         check_closed_broadcast!(nodes[1], true);
4303         check_added_monitors!(nodes[1], 1);
4304         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4305         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4306         assert_eq!(node_txn.len(), 1);
4307         check_spends!(node_txn[0], chan.3);
4308         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
4309
4310         mine_transaction(&nodes[1], &node_txn[0]);
4311         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4312
4313         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4314         assert_eq!(spend_txn.len(), 1);
4315         assert_eq!(spend_txn[0].input.len(), 1);
4316         check_spends!(spend_txn[0], node_txn[0]);
4317         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4318 }
4319
4320 #[test]
4321 fn test_claim_on_remote_sizeable_push_msat() {
4322         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4323         // to_remote output is encumbered by a P2WPKH
4324         let chanmon_cfgs = create_chanmon_cfgs(2);
4325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4327         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4328
4329         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4330         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4331         check_closed_broadcast!(nodes[0], true);
4332         check_added_monitors!(nodes[0], 1);
4333         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4334
4335         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4336         assert_eq!(node_txn.len(), 1);
4337         check_spends!(node_txn[0], chan.3);
4338         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
4339
4340         mine_transaction(&nodes[1], &node_txn[0]);
4341         check_closed_broadcast!(nodes[1], true);
4342         check_added_monitors!(nodes[1], 1);
4343         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4344         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4345
4346         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4347         assert_eq!(spend_txn.len(), 1);
4348         check_spends!(spend_txn[0], node_txn[0]);
4349 }
4350
4351 #[test]
4352 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4353         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4354         // to_remote output is encumbered by a P2WPKH
4355
4356         let chanmon_cfgs = create_chanmon_cfgs(2);
4357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4359         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4360
4361         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4362         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4363         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4364         assert_eq!(revoked_local_txn[0].input.len(), 1);
4365         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4366
4367         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4368         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4369         check_closed_broadcast!(nodes[1], true);
4370         check_added_monitors!(nodes[1], 1);
4371         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4372
4373         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4374         mine_transaction(&nodes[1], &node_txn[0]);
4375         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4376
4377         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4378         assert_eq!(spend_txn.len(), 3);
4379         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4380         check_spends!(spend_txn[1], node_txn[0]);
4381         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4382 }
4383
4384 #[test]
4385 fn test_static_spendable_outputs_preimage_tx() {
4386         let chanmon_cfgs = create_chanmon_cfgs(2);
4387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4389         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4390
4391         // Create some initial channels
4392         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4393
4394         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4395
4396         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4397         assert_eq!(commitment_tx[0].input.len(), 1);
4398         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4399
4400         // Settle A's commitment tx on B's chain
4401         nodes[1].node.claim_funds(payment_preimage);
4402         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4403         check_added_monitors!(nodes[1], 1);
4404         mine_transaction(&nodes[1], &commitment_tx[0]);
4405         check_added_monitors!(nodes[1], 1);
4406         let events = nodes[1].node.get_and_clear_pending_msg_events();
4407         match events[0] {
4408                 MessageSendEvent::UpdateHTLCs { .. } => {},
4409                 _ => panic!("Unexpected event"),
4410         }
4411         match events[1] {
4412                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4413                 _ => panic!("Unexepected event"),
4414         }
4415
4416         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4417         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4418         assert_eq!(node_txn.len(), 1);
4419         check_spends!(node_txn[0], commitment_tx[0]);
4420         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4421
4422         mine_transaction(&nodes[1], &node_txn[0]);
4423         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4424         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4425
4426         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4427         assert_eq!(spend_txn.len(), 1);
4428         check_spends!(spend_txn[0], node_txn[0]);
4429 }
4430
4431 #[test]
4432 fn test_static_spendable_outputs_timeout_tx() {
4433         let chanmon_cfgs = create_chanmon_cfgs(2);
4434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4437
4438         // Create some initial channels
4439         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4440
4441         // Rebalance the network a bit by relaying one payment through all the channels ...
4442         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4443
4444         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4445
4446         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4447         assert_eq!(commitment_tx[0].input.len(), 1);
4448         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4449
4450         // Settle A's commitment tx on B' chain
4451         mine_transaction(&nodes[1], &commitment_tx[0]);
4452         check_added_monitors!(nodes[1], 1);
4453         let events = nodes[1].node.get_and_clear_pending_msg_events();
4454         match events[0] {
4455                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4456                 _ => panic!("Unexpected event"),
4457         }
4458         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4459
4460         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4461         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4462         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4463         check_spends!(node_txn[0],  commitment_tx[0].clone());
4464         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4465
4466         mine_transaction(&nodes[1], &node_txn[0]);
4467         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4468         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4469         expect_payment_failed!(nodes[1], our_payment_hash, false);
4470
4471         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4472         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4473         check_spends!(spend_txn[0], commitment_tx[0]);
4474         check_spends!(spend_txn[1], node_txn[0]);
4475         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4476 }
4477
4478 #[test]
4479 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4480         let chanmon_cfgs = create_chanmon_cfgs(2);
4481         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4482         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4483         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4484
4485         // Create some initial channels
4486         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4487
4488         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4489         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4490         assert_eq!(revoked_local_txn[0].input.len(), 1);
4491         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4492
4493         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4494
4495         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4496         check_closed_broadcast!(nodes[1], true);
4497         check_added_monitors!(nodes[1], 1);
4498         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4499
4500         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4501         assert_eq!(node_txn.len(), 1);
4502         assert_eq!(node_txn[0].input.len(), 2);
4503         check_spends!(node_txn[0], revoked_local_txn[0]);
4504
4505         mine_transaction(&nodes[1], &node_txn[0]);
4506         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4507
4508         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4509         assert_eq!(spend_txn.len(), 1);
4510         check_spends!(spend_txn[0], node_txn[0]);
4511 }
4512
4513 #[test]
4514 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4515         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4516         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4517         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4518         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4519         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4520
4521         // Create some initial channels
4522         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4523
4524         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4525         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4526         assert_eq!(revoked_local_txn[0].input.len(), 1);
4527         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4528
4529         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4530
4531         // A will generate HTLC-Timeout from revoked commitment tx
4532         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4533         check_closed_broadcast!(nodes[0], true);
4534         check_added_monitors!(nodes[0], 1);
4535         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4536         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4537
4538         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4539         assert_eq!(revoked_htlc_txn.len(), 1);
4540         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4541         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4542         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4543         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4544
4545         // B will generate justice tx from A's revoked commitment/HTLC tx
4546         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4547         check_closed_broadcast!(nodes[1], true);
4548         check_added_monitors!(nodes[1], 1);
4549         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4550
4551         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4552         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4553         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4554         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4555         // transactions next...
4556         assert_eq!(node_txn[0].input.len(), 3);
4557         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4558
4559         assert_eq!(node_txn[1].input.len(), 2);
4560         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4561         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4562                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4563         } else {
4564                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4565                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4566         }
4567
4568         mine_transaction(&nodes[1], &node_txn[1]);
4569         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4570
4571         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4572         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4573         assert_eq!(spend_txn.len(), 1);
4574         assert_eq!(spend_txn[0].input.len(), 1);
4575         check_spends!(spend_txn[0], node_txn[1]);
4576 }
4577
4578 #[test]
4579 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4580         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4581         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4582         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4583         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4584         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4585
4586         // Create some initial channels
4587         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4588
4589         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4590         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4591         assert_eq!(revoked_local_txn[0].input.len(), 1);
4592         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4593
4594         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4595         assert_eq!(revoked_local_txn[0].output.len(), 2);
4596
4597         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4598
4599         // B will generate HTLC-Success from revoked commitment tx
4600         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4601         check_closed_broadcast!(nodes[1], true);
4602         check_added_monitors!(nodes[1], 1);
4603         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4604         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4605
4606         assert_eq!(revoked_htlc_txn.len(), 1);
4607         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4608         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4609         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4610
4611         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4612         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4613         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4614
4615         // A will generate justice tx from B's revoked commitment/HTLC tx
4616         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4617         check_closed_broadcast!(nodes[0], true);
4618         check_added_monitors!(nodes[0], 1);
4619         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4620
4621         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4622         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4623
4624         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4625         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4626         // transactions next...
4627         assert_eq!(node_txn[0].input.len(), 2);
4628         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4629         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4630                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4631         } else {
4632                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4633                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4634         }
4635
4636         assert_eq!(node_txn[1].input.len(), 1);
4637         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4638
4639         mine_transaction(&nodes[0], &node_txn[1]);
4640         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4641
4642         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4643         // didn't try to generate any new transactions.
4644
4645         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4646         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4647         assert_eq!(spend_txn.len(), 3);
4648         assert_eq!(spend_txn[0].input.len(), 1);
4649         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4650         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4651         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4652         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4653 }
4654
4655 #[test]
4656 fn test_onchain_to_onchain_claim() {
4657         // Test that in case of channel closure, we detect the state of output and claim HTLC
4658         // on downstream peer's remote commitment tx.
4659         // First, have C claim an HTLC against its own latest commitment transaction.
4660         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4661         // channel.
4662         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4663         // gets broadcast.
4664
4665         let chanmon_cfgs = create_chanmon_cfgs(3);
4666         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4667         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4668         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4669
4670         // Create some initial channels
4671         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4672         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4673
4674         // Ensure all nodes are at the same height
4675         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4676         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4677         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4678         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4679
4680         // Rebalance the network a bit by relaying one payment through all the channels ...
4681         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4682         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4683
4684         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4685         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4686         check_spends!(commitment_tx[0], chan_2.3);
4687         nodes[2].node.claim_funds(payment_preimage);
4688         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4689         check_added_monitors!(nodes[2], 1);
4690         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4691         assert!(updates.update_add_htlcs.is_empty());
4692         assert!(updates.update_fail_htlcs.is_empty());
4693         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4694         assert!(updates.update_fail_malformed_htlcs.is_empty());
4695
4696         mine_transaction(&nodes[2], &commitment_tx[0]);
4697         check_closed_broadcast!(nodes[2], true);
4698         check_added_monitors!(nodes[2], 1);
4699         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4700
4701         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4702         assert_eq!(c_txn.len(), 1);
4703         check_spends!(c_txn[0], commitment_tx[0]);
4704         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4705         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4706         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4707
4708         // 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
4709         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4710         check_added_monitors!(nodes[1], 1);
4711         let events = nodes[1].node.get_and_clear_pending_events();
4712         assert_eq!(events.len(), 2);
4713         match events[0] {
4714                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4715                 _ => panic!("Unexpected event"),
4716         }
4717         match events[1] {
4718                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4719                         assert_eq!(fee_earned_msat, Some(1000));
4720                         assert_eq!(prev_channel_id, Some(chan_1.2));
4721                         assert_eq!(claim_from_onchain_tx, true);
4722                         assert_eq!(next_channel_id, Some(chan_2.2));
4723                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4724                 },
4725                 _ => panic!("Unexpected event"),
4726         }
4727         check_added_monitors!(nodes[1], 1);
4728         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4729         assert_eq!(msg_events.len(), 3);
4730         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4731         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4732
4733         match nodes_2_event {
4734                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4735                 _ => panic!("Unexpected event"),
4736         }
4737
4738         match nodes_0_event {
4739                 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, .. } } => {
4740                         assert!(update_add_htlcs.is_empty());
4741                         assert!(update_fail_htlcs.is_empty());
4742                         assert_eq!(update_fulfill_htlcs.len(), 1);
4743                         assert!(update_fail_malformed_htlcs.is_empty());
4744                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4745                 },
4746                 _ => panic!("Unexpected event"),
4747         };
4748
4749         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4750         match msg_events[0] {
4751                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4752                 _ => panic!("Unexpected event"),
4753         }
4754
4755         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4756         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4757         mine_transaction(&nodes[1], &commitment_tx[0]);
4758         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4759         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4760         // ChannelMonitor: HTLC-Success tx
4761         assert_eq!(b_txn.len(), 1);
4762         check_spends!(b_txn[0], commitment_tx[0]);
4763         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4764         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4765         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4766
4767         check_closed_broadcast!(nodes[1], true);
4768         check_added_monitors!(nodes[1], 1);
4769 }
4770
4771 #[test]
4772 fn test_duplicate_payment_hash_one_failure_one_success() {
4773         // Topology : A --> B --> C --> D
4774         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4775         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4776         // we forward one of the payments onwards to D.
4777         let chanmon_cfgs = create_chanmon_cfgs(4);
4778         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4779         // When this test was written, the default base fee floated based on the HTLC count.
4780         // It is now fixed, so we simply set the fee to the expected value here.
4781         let mut config = test_default_channel_config();
4782         config.channel_config.forwarding_fee_base_msat = 196;
4783         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4784                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4785         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4786
4787         create_announced_chan_between_nodes(&nodes, 0, 1);
4788         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4789         create_announced_chan_between_nodes(&nodes, 2, 3);
4790
4791         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4792         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4793         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4794         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4795         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4796
4797         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4798
4799         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4800         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4801         // script push size limit so that the below script length checks match
4802         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4803         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4804                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4805         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4806         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4807
4808         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4809         assert_eq!(commitment_txn[0].input.len(), 1);
4810         check_spends!(commitment_txn[0], chan_2.3);
4811
4812         mine_transaction(&nodes[1], &commitment_txn[0]);
4813         check_closed_broadcast!(nodes[1], true);
4814         check_added_monitors!(nodes[1], 1);
4815         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4816         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4817
4818         let htlc_timeout_tx;
4819         { // Extract one of the two HTLC-Timeout transaction
4820                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4821                 // ChannelMonitor: timeout tx * 2-or-3
4822                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4823
4824                 check_spends!(node_txn[0], commitment_txn[0]);
4825                 assert_eq!(node_txn[0].input.len(), 1);
4826                 assert_eq!(node_txn[0].output.len(), 1);
4827
4828                 if node_txn.len() > 2 {
4829                         check_spends!(node_txn[1], commitment_txn[0]);
4830                         assert_eq!(node_txn[1].input.len(), 1);
4831                         assert_eq!(node_txn[1].output.len(), 1);
4832                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4833
4834                         check_spends!(node_txn[2], commitment_txn[0]);
4835                         assert_eq!(node_txn[2].input.len(), 1);
4836                         assert_eq!(node_txn[2].output.len(), 1);
4837                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4838                 } else {
4839                         check_spends!(node_txn[1], commitment_txn[0]);
4840                         assert_eq!(node_txn[1].input.len(), 1);
4841                         assert_eq!(node_txn[1].output.len(), 1);
4842                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4843                 }
4844
4845                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4846                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4847                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4848                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4849                 if node_txn.len() > 2 {
4850                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4851                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4852                 } else {
4853                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4854                 }
4855         }
4856
4857         nodes[2].node.claim_funds(our_payment_preimage);
4858         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4859
4860         mine_transaction(&nodes[2], &commitment_txn[0]);
4861         check_added_monitors!(nodes[2], 2);
4862         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4863         let events = nodes[2].node.get_and_clear_pending_msg_events();
4864         match events[0] {
4865                 MessageSendEvent::UpdateHTLCs { .. } => {},
4866                 _ => panic!("Unexpected event"),
4867         }
4868         match events[1] {
4869                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4870                 _ => panic!("Unexepected event"),
4871         }
4872         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4873         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4874         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4875         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4876         assert_eq!(htlc_success_txn[0].input.len(), 1);
4877         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4878         assert_eq!(htlc_success_txn[1].input.len(), 1);
4879         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4880         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4881         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4882
4883         mine_transaction(&nodes[1], &htlc_timeout_tx);
4884         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4885         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 }]);
4886         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4887         assert!(htlc_updates.update_add_htlcs.is_empty());
4888         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4889         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4890         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4891         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4892         check_added_monitors!(nodes[1], 1);
4893
4894         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4895         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4896         {
4897                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4898         }
4899         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4900
4901         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4902         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4903         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4904         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4905         assert!(updates.update_add_htlcs.is_empty());
4906         assert!(updates.update_fail_htlcs.is_empty());
4907         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4908         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4909         assert!(updates.update_fail_malformed_htlcs.is_empty());
4910         check_added_monitors!(nodes[1], 1);
4911
4912         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4913         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4914         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4915 }
4916
4917 #[test]
4918 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4919         let chanmon_cfgs = create_chanmon_cfgs(2);
4920         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4921         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4922         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4923
4924         // Create some initial channels
4925         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4926
4927         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4928         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4929         assert_eq!(local_txn.len(), 1);
4930         assert_eq!(local_txn[0].input.len(), 1);
4931         check_spends!(local_txn[0], chan_1.3);
4932
4933         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4934         nodes[1].node.claim_funds(payment_preimage);
4935         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4936         check_added_monitors!(nodes[1], 1);
4937
4938         mine_transaction(&nodes[1], &local_txn[0]);
4939         check_added_monitors!(nodes[1], 1);
4940         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4941         let events = nodes[1].node.get_and_clear_pending_msg_events();
4942         match events[0] {
4943                 MessageSendEvent::UpdateHTLCs { .. } => {},
4944                 _ => panic!("Unexpected event"),
4945         }
4946         match events[1] {
4947                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4948                 _ => panic!("Unexepected event"),
4949         }
4950         let node_tx = {
4951                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4952                 assert_eq!(node_txn.len(), 1);
4953                 assert_eq!(node_txn[0].input.len(), 1);
4954                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4955                 check_spends!(node_txn[0], local_txn[0]);
4956                 node_txn[0].clone()
4957         };
4958
4959         mine_transaction(&nodes[1], &node_tx);
4960         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4961
4962         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4963         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4964         assert_eq!(spend_txn.len(), 1);
4965         assert_eq!(spend_txn[0].input.len(), 1);
4966         check_spends!(spend_txn[0], node_tx);
4967         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4968 }
4969
4970 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4971         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4972         // unrevoked commitment transaction.
4973         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4974         // a remote RAA before they could be failed backwards (and combinations thereof).
4975         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4976         // use the same payment hashes.
4977         // Thus, we use a six-node network:
4978         //
4979         // A \         / E
4980         //    - C - D -
4981         // B /         \ F
4982         // And test where C fails back to A/B when D announces its latest commitment transaction
4983         let chanmon_cfgs = create_chanmon_cfgs(6);
4984         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4985         // When this test was written, the default base fee floated based on the HTLC count.
4986         // It is now fixed, so we simply set the fee to the expected value here.
4987         let mut config = test_default_channel_config();
4988         config.channel_config.forwarding_fee_base_msat = 196;
4989         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4990                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4991         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4992
4993         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4994         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4995         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4996         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4997         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4998
4999         // Rebalance and check output sanity...
5000         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5001         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5002         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5003
5004         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5005                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5006         // 0th HTLC:
5007         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
5008         // 1st HTLC:
5009         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
5010         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5011         // 2nd HTLC:
5012         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
5013         // 3rd HTLC:
5014         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
5015         // 4th HTLC:
5016         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5017         // 5th HTLC:
5018         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5019         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5020         // 6th HTLC:
5021         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());
5022         // 7th HTLC:
5023         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());
5024
5025         // 8th HTLC:
5026         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5027         // 9th HTLC:
5028         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5029         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
5030
5031         // 10th HTLC:
5032         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
5033         // 11th HTLC:
5034         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5035         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());
5036
5037         // Double-check that six of the new HTLC were added
5038         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5039         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5040         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5041         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5042
5043         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5044         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5045         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5046         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5047         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5048         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5049         check_added_monitors!(nodes[4], 0);
5050
5051         let failed_destinations = vec![
5052                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5053                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5054                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5055                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5056         ];
5057         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5058         check_added_monitors!(nodes[4], 1);
5059
5060         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5061         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5062         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5063         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5064         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5065         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5066
5067         // Fail 3rd below-dust and 7th above-dust HTLCs
5068         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5069         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5070         check_added_monitors!(nodes[5], 0);
5071
5072         let failed_destinations_2 = vec![
5073                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5074                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5075         ];
5076         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5077         check_added_monitors!(nodes[5], 1);
5078
5079         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5080         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5081         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5082         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5083
5084         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5085
5086         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5087         let failed_destinations_3 = vec![
5088                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5089                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5090                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5091                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5092                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5093                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5094         ];
5095         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5096         check_added_monitors!(nodes[3], 1);
5097         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5098         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5099         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5100         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5101         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5102         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5103         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5104         if deliver_last_raa {
5105                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5106         } else {
5107                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5108         }
5109
5110         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5111         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5112         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5113         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5114         //
5115         // We now broadcast the latest commitment transaction, which *should* result in failures for
5116         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5117         // the non-broadcast above-dust HTLCs.
5118         //
5119         // Alternatively, we may broadcast the previous commitment transaction, which should only
5120         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5121         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5122
5123         if announce_latest {
5124                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5125         } else {
5126                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5127         }
5128         let events = nodes[2].node.get_and_clear_pending_events();
5129         let close_event = if deliver_last_raa {
5130                 assert_eq!(events.len(), 2 + 6);
5131                 events.last().clone().unwrap()
5132         } else {
5133                 assert_eq!(events.len(), 1);
5134                 events.last().clone().unwrap()
5135         };
5136         match close_event {
5137                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5138                 _ => panic!("Unexpected event"),
5139         }
5140
5141         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5142         check_closed_broadcast!(nodes[2], true);
5143         if deliver_last_raa {
5144                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5145
5146                 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();
5147                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5148         } else {
5149                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5150                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5151                 } else {
5152                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5153                 };
5154
5155                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5156         }
5157         check_added_monitors!(nodes[2], 3);
5158
5159         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5160         assert_eq!(cs_msgs.len(), 2);
5161         let mut a_done = false;
5162         for msg in cs_msgs {
5163                 match msg {
5164                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5165                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5166                                 // should be failed-backwards here.
5167                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5168                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5169                                         for htlc in &updates.update_fail_htlcs {
5170                                                 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 });
5171                                         }
5172                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5173                                         assert!(!a_done);
5174                                         a_done = true;
5175                                         &nodes[0]
5176                                 } else {
5177                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5178                                         for htlc in &updates.update_fail_htlcs {
5179                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5180                                         }
5181                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5182                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5183                                         &nodes[1]
5184                                 };
5185                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5186                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5187                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5188                                 if announce_latest {
5189                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5190                                         if *node_id == nodes[0].node.get_our_node_id() {
5191                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5192                                         }
5193                                 }
5194                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5195                         },
5196                         _ => panic!("Unexpected event"),
5197                 }
5198         }
5199
5200         let as_events = nodes[0].node.get_and_clear_pending_events();
5201         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5202         let mut as_failds = HashSet::new();
5203         let mut as_updates = 0;
5204         for event in as_events.iter() {
5205                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5206                         assert!(as_failds.insert(*payment_hash));
5207                         if *payment_hash != payment_hash_2 {
5208                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5209                         } else {
5210                                 assert!(!payment_failed_permanently);
5211                         }
5212                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5213                                 as_updates += 1;
5214                         }
5215                 } else if let &Event::PaymentFailed { .. } = event {
5216                 } else { panic!("Unexpected event"); }
5217         }
5218         assert!(as_failds.contains(&payment_hash_1));
5219         assert!(as_failds.contains(&payment_hash_2));
5220         if announce_latest {
5221                 assert!(as_failds.contains(&payment_hash_3));
5222                 assert!(as_failds.contains(&payment_hash_5));
5223         }
5224         assert!(as_failds.contains(&payment_hash_6));
5225
5226         let bs_events = nodes[1].node.get_and_clear_pending_events();
5227         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5228         let mut bs_failds = HashSet::new();
5229         let mut bs_updates = 0;
5230         for event in bs_events.iter() {
5231                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5232                         assert!(bs_failds.insert(*payment_hash));
5233                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5234                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5235                         } else {
5236                                 assert!(!payment_failed_permanently);
5237                         }
5238                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5239                                 bs_updates += 1;
5240                         }
5241                 } else if let &Event::PaymentFailed { .. } = event {
5242                 } else { panic!("Unexpected event"); }
5243         }
5244         assert!(bs_failds.contains(&payment_hash_1));
5245         assert!(bs_failds.contains(&payment_hash_2));
5246         if announce_latest {
5247                 assert!(bs_failds.contains(&payment_hash_4));
5248         }
5249         assert!(bs_failds.contains(&payment_hash_5));
5250
5251         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5252         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5253         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5254         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5255         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5256         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5257 }
5258
5259 #[test]
5260 fn test_fail_backwards_latest_remote_announce_a() {
5261         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5262 }
5263
5264 #[test]
5265 fn test_fail_backwards_latest_remote_announce_b() {
5266         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5267 }
5268
5269 #[test]
5270 fn test_fail_backwards_previous_remote_announce() {
5271         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5272         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5273         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5274 }
5275
5276 #[test]
5277 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5278         let chanmon_cfgs = create_chanmon_cfgs(2);
5279         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5280         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5281         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5282
5283         // Create some initial channels
5284         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5285
5286         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5287         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5288         assert_eq!(local_txn[0].input.len(), 1);
5289         check_spends!(local_txn[0], chan_1.3);
5290
5291         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5292         mine_transaction(&nodes[0], &local_txn[0]);
5293         check_closed_broadcast!(nodes[0], true);
5294         check_added_monitors!(nodes[0], 1);
5295         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5296         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5297
5298         let htlc_timeout = {
5299                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5300                 assert_eq!(node_txn.len(), 1);
5301                 assert_eq!(node_txn[0].input.len(), 1);
5302                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5303                 check_spends!(node_txn[0], local_txn[0]);
5304                 node_txn[0].clone()
5305         };
5306
5307         mine_transaction(&nodes[0], &htlc_timeout);
5308         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5309         expect_payment_failed!(nodes[0], our_payment_hash, false);
5310
5311         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5312         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5313         assert_eq!(spend_txn.len(), 3);
5314         check_spends!(spend_txn[0], local_txn[0]);
5315         assert_eq!(spend_txn[1].input.len(), 1);
5316         check_spends!(spend_txn[1], htlc_timeout);
5317         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5318         assert_eq!(spend_txn[2].input.len(), 2);
5319         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5320         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5321                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5322 }
5323
5324 #[test]
5325 fn test_key_derivation_params() {
5326         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5327         // manager rotation to test that `channel_keys_id` returned in
5328         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5329         // then derive a `delayed_payment_key`.
5330
5331         let chanmon_cfgs = create_chanmon_cfgs(3);
5332
5333         // We manually create the node configuration to backup the seed.
5334         let seed = [42; 32];
5335         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5336         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);
5337         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5338         let scorer = Mutex::new(test_utils::TestScorer::new());
5339         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5340         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)) };
5341         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5342         node_cfgs.remove(0);
5343         node_cfgs.insert(0, node);
5344
5345         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5346         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5347
5348         // Create some initial channels
5349         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5350         // for node 0
5351         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5352         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5353         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5354
5355         // Ensure all nodes are at the same height
5356         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5357         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5358         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5359         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5360
5361         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5362         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5363         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5364         assert_eq!(local_txn_1[0].input.len(), 1);
5365         check_spends!(local_txn_1[0], chan_1.3);
5366
5367         // We check funding pubkey are unique
5368         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]));
5369         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]));
5370         if from_0_funding_key_0 == from_1_funding_key_0
5371             || from_0_funding_key_0 == from_1_funding_key_1
5372             || from_0_funding_key_1 == from_1_funding_key_0
5373             || from_0_funding_key_1 == from_1_funding_key_1 {
5374                 panic!("Funding pubkeys aren't unique");
5375         }
5376
5377         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5378         mine_transaction(&nodes[0], &local_txn_1[0]);
5379         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5380         check_closed_broadcast!(nodes[0], true);
5381         check_added_monitors!(nodes[0], 1);
5382         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5383
5384         let htlc_timeout = {
5385                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5386                 assert_eq!(node_txn.len(), 1);
5387                 assert_eq!(node_txn[0].input.len(), 1);
5388                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5389                 check_spends!(node_txn[0], local_txn_1[0]);
5390                 node_txn[0].clone()
5391         };
5392
5393         mine_transaction(&nodes[0], &htlc_timeout);
5394         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5395         expect_payment_failed!(nodes[0], our_payment_hash, false);
5396
5397         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5398         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5399         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5400         assert_eq!(spend_txn.len(), 3);
5401         check_spends!(spend_txn[0], local_txn_1[0]);
5402         assert_eq!(spend_txn[1].input.len(), 1);
5403         check_spends!(spend_txn[1], htlc_timeout);
5404         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5405         assert_eq!(spend_txn[2].input.len(), 2);
5406         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5407         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5408                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5409 }
5410
5411 #[test]
5412 fn test_static_output_closing_tx() {
5413         let chanmon_cfgs = create_chanmon_cfgs(2);
5414         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5415         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5416         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5417
5418         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5419
5420         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5421         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5422
5423         mine_transaction(&nodes[0], &closing_tx);
5424         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5425         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5426
5427         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5428         assert_eq!(spend_txn.len(), 1);
5429         check_spends!(spend_txn[0], closing_tx);
5430
5431         mine_transaction(&nodes[1], &closing_tx);
5432         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5433         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5434
5435         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5436         assert_eq!(spend_txn.len(), 1);
5437         check_spends!(spend_txn[0], closing_tx);
5438 }
5439
5440 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5441         let chanmon_cfgs = create_chanmon_cfgs(2);
5442         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5443         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5444         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5445         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5446
5447         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5448
5449         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5450         // present in B's local commitment transaction, but none of A's commitment transactions.
5451         nodes[1].node.claim_funds(payment_preimage);
5452         check_added_monitors!(nodes[1], 1);
5453         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5454
5455         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5456         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5457         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5458
5459         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5460         check_added_monitors!(nodes[0], 1);
5461         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5462         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5463         check_added_monitors!(nodes[1], 1);
5464
5465         let starting_block = nodes[1].best_block_info();
5466         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5467         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5468                 connect_block(&nodes[1], &block);
5469                 block.header.prev_blockhash = block.block_hash();
5470         }
5471         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5472         check_closed_broadcast!(nodes[1], true);
5473         check_added_monitors!(nodes[1], 1);
5474         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5475 }
5476
5477 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5478         let chanmon_cfgs = create_chanmon_cfgs(2);
5479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5481         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5482         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5483
5484         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5485         nodes[0].node.send_payment_with_route(&route, payment_hash,
5486                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5487         check_added_monitors!(nodes[0], 1);
5488
5489         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5490
5491         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5492         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5493         // to "time out" the HTLC.
5494
5495         let starting_block = nodes[1].best_block_info();
5496         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5497
5498         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5499                 connect_block(&nodes[0], &block);
5500                 block.header.prev_blockhash = block.block_hash();
5501         }
5502         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5503         check_closed_broadcast!(nodes[0], true);
5504         check_added_monitors!(nodes[0], 1);
5505         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5506 }
5507
5508 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5509         let chanmon_cfgs = create_chanmon_cfgs(3);
5510         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5511         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5512         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5513         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5514
5515         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5516         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5517         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5518         // actually revoked.
5519         let htlc_value = if use_dust { 50000 } else { 3000000 };
5520         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5521         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5522         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5523         check_added_monitors!(nodes[1], 1);
5524
5525         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5526         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5527         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5528         check_added_monitors!(nodes[0], 1);
5529         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5530         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5531         check_added_monitors!(nodes[1], 1);
5532         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5533         check_added_monitors!(nodes[1], 1);
5534         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5535
5536         if check_revoke_no_close {
5537                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5538                 check_added_monitors!(nodes[0], 1);
5539         }
5540
5541         let starting_block = nodes[1].best_block_info();
5542         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5543         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5544                 connect_block(&nodes[0], &block);
5545                 block.header.prev_blockhash = block.block_hash();
5546         }
5547         if !check_revoke_no_close {
5548                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5549                 check_closed_broadcast!(nodes[0], true);
5550                 check_added_monitors!(nodes[0], 1);
5551                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5552         } else {
5553                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5554         }
5555 }
5556
5557 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5558 // There are only a few cases to test here:
5559 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5560 //    broadcastable commitment transactions result in channel closure,
5561 //  * its included in an unrevoked-but-previous remote commitment transaction,
5562 //  * its included in the latest remote or local commitment transactions.
5563 // We test each of the three possible commitment transactions individually and use both dust and
5564 // non-dust HTLCs.
5565 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5566 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5567 // tested for at least one of the cases in other tests.
5568 #[test]
5569 fn htlc_claim_single_commitment_only_a() {
5570         do_htlc_claim_local_commitment_only(true);
5571         do_htlc_claim_local_commitment_only(false);
5572
5573         do_htlc_claim_current_remote_commitment_only(true);
5574         do_htlc_claim_current_remote_commitment_only(false);
5575 }
5576
5577 #[test]
5578 fn htlc_claim_single_commitment_only_b() {
5579         do_htlc_claim_previous_remote_commitment_only(true, false);
5580         do_htlc_claim_previous_remote_commitment_only(false, false);
5581         do_htlc_claim_previous_remote_commitment_only(true, true);
5582         do_htlc_claim_previous_remote_commitment_only(false, true);
5583 }
5584
5585 #[test]
5586 #[should_panic]
5587 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5588         let chanmon_cfgs = create_chanmon_cfgs(2);
5589         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5590         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5591         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5592         // Force duplicate randomness for every get-random call
5593         for node in nodes.iter() {
5594                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5595         }
5596
5597         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5598         let channel_value_satoshis=10000;
5599         let push_msat=10001;
5600         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5601         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5602         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5603         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5604
5605         // Create a second channel with the same random values. This used to panic due to a colliding
5606         // channel_id, but now panics due to a colliding outbound SCID alias.
5607         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5608 }
5609
5610 #[test]
5611 fn bolt2_open_channel_sending_node_checks_part2() {
5612         let chanmon_cfgs = create_chanmon_cfgs(2);
5613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5615         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5616
5617         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5618         let channel_value_satoshis=2^24;
5619         let push_msat=10001;
5620         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5621
5622         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5623         let channel_value_satoshis=10000;
5624         // Test when push_msat is equal to 1000 * funding_satoshis.
5625         let push_msat=1000*channel_value_satoshis+1;
5626         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5627
5628         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5629         let channel_value_satoshis=10000;
5630         let push_msat=10001;
5631         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
5632         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5633         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5634
5635         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5636         // 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
5637         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5638
5639         // 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.
5640         assert!(BREAKDOWN_TIMEOUT>0);
5641         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5642
5643         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5644         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5645         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5646
5647         // 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.
5648         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5649         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5650         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5651         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5652         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5653 }
5654
5655 #[test]
5656 fn bolt2_open_channel_sane_dust_limit() {
5657         let chanmon_cfgs = create_chanmon_cfgs(2);
5658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5661
5662         let channel_value_satoshis=1000000;
5663         let push_msat=10001;
5664         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5665         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5666         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5667         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5668
5669         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5670         let events = nodes[1].node.get_and_clear_pending_msg_events();
5671         let err_msg = match events[0] {
5672                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5673                         msg.clone()
5674                 },
5675                 _ => panic!("Unexpected event"),
5676         };
5677         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5678 }
5679
5680 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5681 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5682 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5683 // is no longer affordable once it's freed.
5684 #[test]
5685 fn test_fail_holding_cell_htlc_upon_free() {
5686         let chanmon_cfgs = create_chanmon_cfgs(2);
5687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5689         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5690         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5691
5692         // First nodes[0] generates an update_fee, setting the channel's
5693         // pending_update_fee.
5694         {
5695                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5696                 *feerate_lock += 20;
5697         }
5698         nodes[0].node.timer_tick_occurred();
5699         check_added_monitors!(nodes[0], 1);
5700
5701         let events = nodes[0].node.get_and_clear_pending_msg_events();
5702         assert_eq!(events.len(), 1);
5703         let (update_msg, commitment_signed) = match events[0] {
5704                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5705                         (update_fee.as_ref(), commitment_signed)
5706                 },
5707                 _ => panic!("Unexpected event"),
5708         };
5709
5710         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5711
5712         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5713         let channel_reserve = chan_stat.channel_reserve_msat;
5714         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5715         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5716
5717         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5718         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5719         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5720
5721         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5722         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5723                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5724         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5725         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5726
5727         // Flush the pending fee update.
5728         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5729         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5730         check_added_monitors!(nodes[1], 1);
5731         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5732         check_added_monitors!(nodes[0], 1);
5733
5734         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5735         // HTLC, but now that the fee has been raised the payment will now fail, causing
5736         // us to surface its failure to the user.
5737         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5738         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5739         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5740
5741         // Check that the payment failed to be sent out.
5742         let events = nodes[0].node.get_and_clear_pending_events();
5743         assert_eq!(events.len(), 2);
5744         match &events[0] {
5745                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5746                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5747                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5748                         assert_eq!(*payment_failed_permanently, false);
5749                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5750                 },
5751                 _ => panic!("Unexpected event"),
5752         }
5753         match &events[1] {
5754                 &Event::PaymentFailed { ref payment_hash, .. } => {
5755                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5756                 },
5757                 _ => panic!("Unexpected event"),
5758         }
5759 }
5760
5761 // Test that if multiple HTLCs are released from the holding cell and one is
5762 // valid but the other is no longer valid upon release, the valid HTLC can be
5763 // successfully completed while the other one fails as expected.
5764 #[test]
5765 fn test_free_and_fail_holding_cell_htlcs() {
5766         let chanmon_cfgs = create_chanmon_cfgs(2);
5767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5769         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5770         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5771
5772         // First nodes[0] generates an update_fee, setting the channel's
5773         // pending_update_fee.
5774         {
5775                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5776                 *feerate_lock += 200;
5777         }
5778         nodes[0].node.timer_tick_occurred();
5779         check_added_monitors!(nodes[0], 1);
5780
5781         let events = nodes[0].node.get_and_clear_pending_msg_events();
5782         assert_eq!(events.len(), 1);
5783         let (update_msg, commitment_signed) = match events[0] {
5784                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5785                         (update_fee.as_ref(), commitment_signed)
5786                 },
5787                 _ => panic!("Unexpected event"),
5788         };
5789
5790         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5791
5792         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5793         let channel_reserve = chan_stat.channel_reserve_msat;
5794         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5795         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5796
5797         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5798         let amt_1 = 20000;
5799         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5800         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5801         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5802
5803         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5804         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5805                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5806         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5807         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5808         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5809         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5810                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5811         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5812         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5813
5814         // Flush the pending fee update.
5815         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5816         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5817         check_added_monitors!(nodes[1], 1);
5818         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5819         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5820         check_added_monitors!(nodes[0], 2);
5821
5822         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5823         // but now that the fee has been raised the second payment will now fail, causing us
5824         // to surface its failure to the user. The first payment should succeed.
5825         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5826         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5827         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5828
5829         // Check that the second payment failed to be sent out.
5830         let events = nodes[0].node.get_and_clear_pending_events();
5831         assert_eq!(events.len(), 2);
5832         match &events[0] {
5833                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5834                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5835                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5836                         assert_eq!(*payment_failed_permanently, false);
5837                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5838                 },
5839                 _ => panic!("Unexpected event"),
5840         }
5841         match &events[1] {
5842                 &Event::PaymentFailed { ref payment_hash, .. } => {
5843                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5844                 },
5845                 _ => panic!("Unexpected event"),
5846         }
5847
5848         // Complete the first payment and the RAA from the fee update.
5849         let (payment_event, send_raa_event) = {
5850                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5851                 assert_eq!(msgs.len(), 2);
5852                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5853         };
5854         let raa = match send_raa_event {
5855                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5856                 _ => panic!("Unexpected event"),
5857         };
5858         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5859         check_added_monitors!(nodes[1], 1);
5860         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5861         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5862         let events = nodes[1].node.get_and_clear_pending_events();
5863         assert_eq!(events.len(), 1);
5864         match events[0] {
5865                 Event::PendingHTLCsForwardable { .. } => {},
5866                 _ => panic!("Unexpected event"),
5867         }
5868         nodes[1].node.process_pending_htlc_forwards();
5869         let events = nodes[1].node.get_and_clear_pending_events();
5870         assert_eq!(events.len(), 1);
5871         match events[0] {
5872                 Event::PaymentClaimable { .. } => {},
5873                 _ => panic!("Unexpected event"),
5874         }
5875         nodes[1].node.claim_funds(payment_preimage_1);
5876         check_added_monitors!(nodes[1], 1);
5877         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5878
5879         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5880         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5881         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5882         expect_payment_sent!(nodes[0], payment_preimage_1);
5883 }
5884
5885 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5886 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5887 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5888 // once it's freed.
5889 #[test]
5890 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5891         let chanmon_cfgs = create_chanmon_cfgs(3);
5892         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5893         // Avoid having to include routing fees in calculations
5894         let mut config = test_default_channel_config();
5895         config.channel_config.forwarding_fee_base_msat = 0;
5896         config.channel_config.forwarding_fee_proportional_millionths = 0;
5897         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5898         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5899         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5900         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5901
5902         // First nodes[1] generates an update_fee, setting the channel's
5903         // pending_update_fee.
5904         {
5905                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5906                 *feerate_lock += 20;
5907         }
5908         nodes[1].node.timer_tick_occurred();
5909         check_added_monitors!(nodes[1], 1);
5910
5911         let events = nodes[1].node.get_and_clear_pending_msg_events();
5912         assert_eq!(events.len(), 1);
5913         let (update_msg, commitment_signed) = match events[0] {
5914                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5915                         (update_fee.as_ref(), commitment_signed)
5916                 },
5917                 _ => panic!("Unexpected event"),
5918         };
5919
5920         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5921
5922         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5923         let channel_reserve = chan_stat.channel_reserve_msat;
5924         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5925         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
5926
5927         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5928         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5929         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5930         let payment_event = {
5931                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5932                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5933                 check_added_monitors!(nodes[0], 1);
5934
5935                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5936                 assert_eq!(events.len(), 1);
5937
5938                 SendEvent::from_event(events.remove(0))
5939         };
5940         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5941         check_added_monitors!(nodes[1], 0);
5942         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5943         expect_pending_htlcs_forwardable!(nodes[1]);
5944
5945         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5946         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5947
5948         // Flush the pending fee update.
5949         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5950         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5951         check_added_monitors!(nodes[2], 1);
5952         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5953         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5954         check_added_monitors!(nodes[1], 2);
5955
5956         // A final RAA message is generated to finalize the fee update.
5957         let events = nodes[1].node.get_and_clear_pending_msg_events();
5958         assert_eq!(events.len(), 1);
5959
5960         let raa_msg = match &events[0] {
5961                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5962                         msg.clone()
5963                 },
5964                 _ => panic!("Unexpected event"),
5965         };
5966
5967         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5968         check_added_monitors!(nodes[2], 1);
5969         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5970
5971         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5972         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5973         assert_eq!(process_htlc_forwards_event.len(), 2);
5974         match &process_htlc_forwards_event[0] {
5975                 &Event::PendingHTLCsForwardable { .. } => {},
5976                 _ => panic!("Unexpected event"),
5977         }
5978
5979         // In response, we call ChannelManager's process_pending_htlc_forwards
5980         nodes[1].node.process_pending_htlc_forwards();
5981         check_added_monitors!(nodes[1], 1);
5982
5983         // This causes the HTLC to be failed backwards.
5984         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5985         assert_eq!(fail_event.len(), 1);
5986         let (fail_msg, commitment_signed) = match &fail_event[0] {
5987                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5988                         assert_eq!(updates.update_add_htlcs.len(), 0);
5989                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5990                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5991                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5992                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5993                 },
5994                 _ => panic!("Unexpected event"),
5995         };
5996
5997         // Pass the failure messages back to nodes[0].
5998         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5999         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6000
6001         // Complete the HTLC failure+removal process.
6002         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6003         check_added_monitors!(nodes[0], 1);
6004         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6005         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6006         check_added_monitors!(nodes[1], 2);
6007         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6008         assert_eq!(final_raa_event.len(), 1);
6009         let raa = match &final_raa_event[0] {
6010                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6011                 _ => panic!("Unexpected event"),
6012         };
6013         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6014         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6015         check_added_monitors!(nodes[0], 1);
6016 }
6017
6018 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6019 // 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.
6020 //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.
6021
6022 #[test]
6023 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6024         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6025         let chanmon_cfgs = create_chanmon_cfgs(2);
6026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6028         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6029         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6030
6031         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6032         route.paths[0].hops[0].fee_msat = 100;
6033
6034         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6035                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6036                 ), true, APIError::ChannelUnavailable { .. }, {});
6037         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6038 }
6039
6040 #[test]
6041 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6042         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6043         let chanmon_cfgs = create_chanmon_cfgs(2);
6044         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6045         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6046         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6047         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6048
6049         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6050         route.paths[0].hops[0].fee_msat = 0;
6051         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6052                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6053                 true, APIError::ChannelUnavailable { ref err },
6054                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6055
6056         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6057         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6058 }
6059
6060 #[test]
6061 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6062         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6063         let chanmon_cfgs = create_chanmon_cfgs(2);
6064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6066         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6067         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6068
6069         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6070         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6071                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6072         check_added_monitors!(nodes[0], 1);
6073         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6074         updates.update_add_htlcs[0].amount_msat = 0;
6075
6076         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6077         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6078         check_closed_broadcast!(nodes[1], true).unwrap();
6079         check_added_monitors!(nodes[1], 1);
6080         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6081 }
6082
6083 #[test]
6084 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6085         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6086         //It is enforced when constructing a route.
6087         let chanmon_cfgs = create_chanmon_cfgs(2);
6088         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6089         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6090         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6091         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6092
6093         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6094                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6095         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6096         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6097         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6098                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6099                 ), true, APIError::InvalidRoute { ref err },
6100                 assert_eq!(err, &"Channel CLTV overflowed?"));
6101 }
6102
6103 #[test]
6104 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6105         //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.
6106         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6107         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6108         let chanmon_cfgs = create_chanmon_cfgs(2);
6109         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6110         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6111         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6112         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6113         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6114                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6115
6116         // Fetch a route in advance as we will be unable to once we're unable to send.
6117         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6118         for i in 0..max_accepted_htlcs {
6119                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6120                 let payment_event = {
6121                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6122                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6123                         check_added_monitors!(nodes[0], 1);
6124
6125                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6126                         assert_eq!(events.len(), 1);
6127                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6128                                 assert_eq!(htlcs[0].htlc_id, i);
6129                         } else {
6130                                 assert!(false);
6131                         }
6132                         SendEvent::from_event(events.remove(0))
6133                 };
6134                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6135                 check_added_monitors!(nodes[1], 0);
6136                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6137
6138                 expect_pending_htlcs_forwardable!(nodes[1]);
6139                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6140         }
6141         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6142                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6143                 ), true, APIError::ChannelUnavailable { .. }, {});
6144
6145         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6146 }
6147
6148 #[test]
6149 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6150         //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.
6151         let chanmon_cfgs = create_chanmon_cfgs(2);
6152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6154         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6155         let channel_value = 100000;
6156         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6157         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6158
6159         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6160
6161         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6162         // Manually create a route over our max in flight (which our router normally automatically
6163         // limits us to.
6164         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6165         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6166                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6167                 ), true, APIError::ChannelUnavailable { .. }, {});
6168         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6169
6170         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6171 }
6172
6173 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6174 #[test]
6175 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6176         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6177         let chanmon_cfgs = create_chanmon_cfgs(2);
6178         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6179         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6180         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6181         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6182         let htlc_minimum_msat: u64;
6183         {
6184                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6185                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6186                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6187                 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6188         }
6189
6190         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6191         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6192                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6193         check_added_monitors!(nodes[0], 1);
6194         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6195         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6196         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6197         assert!(nodes[1].node.list_channels().is_empty());
6198         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6199         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()));
6200         check_added_monitors!(nodes[1], 1);
6201         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6202 }
6203
6204 #[test]
6205 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6206         //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
6207         let chanmon_cfgs = create_chanmon_cfgs(2);
6208         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6209         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6210         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6211         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6212
6213         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6214         let channel_reserve = chan_stat.channel_reserve_msat;
6215         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6216         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6217         // The 2* and +1 are for the fee spike reserve.
6218         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6219
6220         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6221         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6222         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6223                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6224         check_added_monitors!(nodes[0], 1);
6225         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6226
6227         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6228         // at this time channel-initiatee receivers are not required to enforce that senders
6229         // respect the fee_spike_reserve.
6230         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6231         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6232
6233         assert!(nodes[1].node.list_channels().is_empty());
6234         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6235         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6236         check_added_monitors!(nodes[1], 1);
6237         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6238 }
6239
6240 #[test]
6241 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6242         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6243         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6244         let chanmon_cfgs = create_chanmon_cfgs(2);
6245         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6246         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6247         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6248         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6249
6250         let send_amt = 3999999;
6251         let (mut route, our_payment_hash, _, our_payment_secret) =
6252                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6253         route.paths[0].hops[0].fee_msat = send_amt;
6254         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6255         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6256         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6257         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6258                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6259         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6260
6261         let mut msg = msgs::UpdateAddHTLC {
6262                 channel_id: chan.2,
6263                 htlc_id: 0,
6264                 amount_msat: 1000,
6265                 payment_hash: our_payment_hash,
6266                 cltv_expiry: htlc_cltv,
6267                 onion_routing_packet: onion_packet.clone(),
6268                 skimmed_fee_msat: None,
6269         };
6270
6271         for i in 0..50 {
6272                 msg.htlc_id = i as u64;
6273                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6274         }
6275         msg.htlc_id = (50) as u64;
6276         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6277
6278         assert!(nodes[1].node.list_channels().is_empty());
6279         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6280         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6281         check_added_monitors!(nodes[1], 1);
6282         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6283 }
6284
6285 #[test]
6286 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6287         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6288         let chanmon_cfgs = create_chanmon_cfgs(2);
6289         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6290         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6291         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6292         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6293
6294         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6295         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6296                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6297         check_added_monitors!(nodes[0], 1);
6298         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6299         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;
6300         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6301
6302         assert!(nodes[1].node.list_channels().is_empty());
6303         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6304         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6305         check_added_monitors!(nodes[1], 1);
6306         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6307 }
6308
6309 #[test]
6310 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6311         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6312         let chanmon_cfgs = create_chanmon_cfgs(2);
6313         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6314         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6315         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6316
6317         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6318         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6319         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6320                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6321         check_added_monitors!(nodes[0], 1);
6322         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6323         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6324         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6325
6326         assert!(nodes[1].node.list_channels().is_empty());
6327         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6328         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6329         check_added_monitors!(nodes[1], 1);
6330         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6331 }
6332
6333 #[test]
6334 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6335         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6336         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6337         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6338         let chanmon_cfgs = create_chanmon_cfgs(2);
6339         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6340         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6341         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6342
6343         create_announced_chan_between_nodes(&nodes, 0, 1);
6344         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6345         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6346                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6347         check_added_monitors!(nodes[0], 1);
6348         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6349         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6350
6351         //Disconnect and Reconnect
6352         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6353         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6354         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6355                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6356         }, true).unwrap();
6357         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6358         assert_eq!(reestablish_1.len(), 1);
6359         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6360                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6361         }, false).unwrap();
6362         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6363         assert_eq!(reestablish_2.len(), 1);
6364         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6365         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6366         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6367         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6368
6369         //Resend HTLC
6370         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6371         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6372         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6373         check_added_monitors!(nodes[1], 1);
6374         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6375
6376         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6377
6378         assert!(nodes[1].node.list_channels().is_empty());
6379         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6380         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6381         check_added_monitors!(nodes[1], 1);
6382         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6383 }
6384
6385 #[test]
6386 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6387         //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.
6388
6389         let chanmon_cfgs = create_chanmon_cfgs(2);
6390         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6391         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6392         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6393         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6394         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6395         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6396                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6397
6398         check_added_monitors!(nodes[0], 1);
6399         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6400         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6401
6402         let update_msg = msgs::UpdateFulfillHTLC{
6403                 channel_id: chan.2,
6404                 htlc_id: 0,
6405                 payment_preimage: our_payment_preimage,
6406         };
6407
6408         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6409
6410         assert!(nodes[0].node.list_channels().is_empty());
6411         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6412         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()));
6413         check_added_monitors!(nodes[0], 1);
6414         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6415 }
6416
6417 #[test]
6418 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6419         //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.
6420
6421         let chanmon_cfgs = create_chanmon_cfgs(2);
6422         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6423         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6424         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6425         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6426
6427         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6428         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6429                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6430         check_added_monitors!(nodes[0], 1);
6431         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6432         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6433
6434         let update_msg = msgs::UpdateFailHTLC{
6435                 channel_id: chan.2,
6436                 htlc_id: 0,
6437                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6438         };
6439
6440         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6441
6442         assert!(nodes[0].node.list_channels().is_empty());
6443         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6444         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()));
6445         check_added_monitors!(nodes[0], 1);
6446         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6447 }
6448
6449 #[test]
6450 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6451         //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.
6452
6453         let chanmon_cfgs = create_chanmon_cfgs(2);
6454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6456         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6457         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6458
6459         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6460         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6461                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6462         check_added_monitors!(nodes[0], 1);
6463         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6464         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6465         let update_msg = msgs::UpdateFailMalformedHTLC{
6466                 channel_id: chan.2,
6467                 htlc_id: 0,
6468                 sha256_of_onion: [1; 32],
6469                 failure_code: 0x8000,
6470         };
6471
6472         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6473
6474         assert!(nodes[0].node.list_channels().is_empty());
6475         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6476         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()));
6477         check_added_monitors!(nodes[0], 1);
6478         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6479 }
6480
6481 #[test]
6482 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6483         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6484
6485         let chanmon_cfgs = create_chanmon_cfgs(2);
6486         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6487         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6488         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6489         create_announced_chan_between_nodes(&nodes, 0, 1);
6490
6491         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6492
6493         nodes[1].node.claim_funds(our_payment_preimage);
6494         check_added_monitors!(nodes[1], 1);
6495         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6496
6497         let events = nodes[1].node.get_and_clear_pending_msg_events();
6498         assert_eq!(events.len(), 1);
6499         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6500                 match events[0] {
6501                         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, .. } } => {
6502                                 assert!(update_add_htlcs.is_empty());
6503                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6504                                 assert!(update_fail_htlcs.is_empty());
6505                                 assert!(update_fail_malformed_htlcs.is_empty());
6506                                 assert!(update_fee.is_none());
6507                                 update_fulfill_htlcs[0].clone()
6508                         },
6509                         _ => panic!("Unexpected event"),
6510                 }
6511         };
6512
6513         update_fulfill_msg.htlc_id = 1;
6514
6515         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6516
6517         assert!(nodes[0].node.list_channels().is_empty());
6518         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6519         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6520         check_added_monitors!(nodes[0], 1);
6521         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6522 }
6523
6524 #[test]
6525 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6526         //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.
6527
6528         let chanmon_cfgs = create_chanmon_cfgs(2);
6529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6532         create_announced_chan_between_nodes(&nodes, 0, 1);
6533
6534         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6535
6536         nodes[1].node.claim_funds(our_payment_preimage);
6537         check_added_monitors!(nodes[1], 1);
6538         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6539
6540         let events = nodes[1].node.get_and_clear_pending_msg_events();
6541         assert_eq!(events.len(), 1);
6542         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6543                 match events[0] {
6544                         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, .. } } => {
6545                                 assert!(update_add_htlcs.is_empty());
6546                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6547                                 assert!(update_fail_htlcs.is_empty());
6548                                 assert!(update_fail_malformed_htlcs.is_empty());
6549                                 assert!(update_fee.is_none());
6550                                 update_fulfill_htlcs[0].clone()
6551                         },
6552                         _ => panic!("Unexpected event"),
6553                 }
6554         };
6555
6556         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6557
6558         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6559
6560         assert!(nodes[0].node.list_channels().is_empty());
6561         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6562         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6563         check_added_monitors!(nodes[0], 1);
6564         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6565 }
6566
6567 #[test]
6568 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6569         //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.
6570
6571         let chanmon_cfgs = create_chanmon_cfgs(2);
6572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6575         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6576
6577         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6578         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6579                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6580         check_added_monitors!(nodes[0], 1);
6581
6582         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6583         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6584
6585         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6586         check_added_monitors!(nodes[1], 0);
6587         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6588
6589         let events = nodes[1].node.get_and_clear_pending_msg_events();
6590
6591         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6592                 match events[0] {
6593                         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, .. } } => {
6594                                 assert!(update_add_htlcs.is_empty());
6595                                 assert!(update_fulfill_htlcs.is_empty());
6596                                 assert!(update_fail_htlcs.is_empty());
6597                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6598                                 assert!(update_fee.is_none());
6599                                 update_fail_malformed_htlcs[0].clone()
6600                         },
6601                         _ => panic!("Unexpected event"),
6602                 }
6603         };
6604         update_msg.failure_code &= !0x8000;
6605         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6606
6607         assert!(nodes[0].node.list_channels().is_empty());
6608         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6609         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6610         check_added_monitors!(nodes[0], 1);
6611         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6612 }
6613
6614 #[test]
6615 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6616         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6617         //    * 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.
6618
6619         let chanmon_cfgs = create_chanmon_cfgs(3);
6620         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6621         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6622         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6623         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6624         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6625
6626         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6627
6628         //First hop
6629         let mut payment_event = {
6630                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6631                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6632                 check_added_monitors!(nodes[0], 1);
6633                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6634                 assert_eq!(events.len(), 1);
6635                 SendEvent::from_event(events.remove(0))
6636         };
6637         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6638         check_added_monitors!(nodes[1], 0);
6639         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6640         expect_pending_htlcs_forwardable!(nodes[1]);
6641         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6642         assert_eq!(events_2.len(), 1);
6643         check_added_monitors!(nodes[1], 1);
6644         payment_event = SendEvent::from_event(events_2.remove(0));
6645         assert_eq!(payment_event.msgs.len(), 1);
6646
6647         //Second Hop
6648         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6649         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6650         check_added_monitors!(nodes[2], 0);
6651         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6652
6653         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6654         assert_eq!(events_3.len(), 1);
6655         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6656                 match events_3[0] {
6657                         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 } } => {
6658                                 assert!(update_add_htlcs.is_empty());
6659                                 assert!(update_fulfill_htlcs.is_empty());
6660                                 assert!(update_fail_htlcs.is_empty());
6661                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6662                                 assert!(update_fee.is_none());
6663                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6664                         },
6665                         _ => panic!("Unexpected event"),
6666                 }
6667         };
6668
6669         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6670
6671         check_added_monitors!(nodes[1], 0);
6672         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6673         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 }]);
6674         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6675         assert_eq!(events_4.len(), 1);
6676
6677         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6678         match events_4[0] {
6679                 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, .. } } => {
6680                         assert!(update_add_htlcs.is_empty());
6681                         assert!(update_fulfill_htlcs.is_empty());
6682                         assert_eq!(update_fail_htlcs.len(), 1);
6683                         assert!(update_fail_malformed_htlcs.is_empty());
6684                         assert!(update_fee.is_none());
6685                 },
6686                 _ => panic!("Unexpected event"),
6687         };
6688
6689         check_added_monitors!(nodes[1], 1);
6690 }
6691
6692 #[test]
6693 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6694         let chanmon_cfgs = create_chanmon_cfgs(3);
6695         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6696         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6697         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6698         create_announced_chan_between_nodes(&nodes, 0, 1);
6699         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6700
6701         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6702
6703         // First hop
6704         let mut payment_event = {
6705                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6706                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6707                 check_added_monitors!(nodes[0], 1);
6708                 SendEvent::from_node(&nodes[0])
6709         };
6710
6711         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6712         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6713         expect_pending_htlcs_forwardable!(nodes[1]);
6714         check_added_monitors!(nodes[1], 1);
6715         payment_event = SendEvent::from_node(&nodes[1]);
6716         assert_eq!(payment_event.msgs.len(), 1);
6717
6718         // Second Hop
6719         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6720         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6721         check_added_monitors!(nodes[2], 0);
6722         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6723
6724         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6725         assert_eq!(events_3.len(), 1);
6726         match events_3[0] {
6727                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6728                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6729                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6730                         update_msg.failure_code |= 0x2000;
6731
6732                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6733                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6734                 },
6735                 _ => panic!("Unexpected event"),
6736         }
6737
6738         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6739                 vec![HTLCDestination::NextHopChannel {
6740                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6741         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6742         assert_eq!(events_4.len(), 1);
6743         check_added_monitors!(nodes[1], 1);
6744
6745         match events_4[0] {
6746                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6747                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6748                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6749                 },
6750                 _ => panic!("Unexpected event"),
6751         }
6752
6753         let events_5 = nodes[0].node.get_and_clear_pending_events();
6754         assert_eq!(events_5.len(), 2);
6755
6756         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6757         // the node originating the error to its next hop.
6758         match events_5[0] {
6759                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6760                 } => {
6761                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6762                         assert!(is_permanent);
6763                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6764                 },
6765                 _ => panic!("Unexpected event"),
6766         }
6767         match events_5[1] {
6768                 Event::PaymentFailed { payment_hash, .. } => {
6769                         assert_eq!(payment_hash, our_payment_hash);
6770                 },
6771                 _ => panic!("Unexpected event"),
6772         }
6773
6774         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6775 }
6776
6777 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6778         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6779         // 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
6780         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6781
6782         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6783         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6786         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6787         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6788
6789         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6790                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6791
6792         // We route 2 dust-HTLCs between A and B
6793         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6794         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6795         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6796
6797         // Cache one local commitment tx as previous
6798         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6799
6800         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6801         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6802         check_added_monitors!(nodes[1], 0);
6803         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6804         check_added_monitors!(nodes[1], 1);
6805
6806         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6807         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6808         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6809         check_added_monitors!(nodes[0], 1);
6810
6811         // Cache one local commitment tx as lastest
6812         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6813
6814         let events = nodes[0].node.get_and_clear_pending_msg_events();
6815         match events[0] {
6816                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6817                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6818                 },
6819                 _ => panic!("Unexpected event"),
6820         }
6821         match events[1] {
6822                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6823                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6824                 },
6825                 _ => panic!("Unexpected event"),
6826         }
6827
6828         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6829         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6830         if announce_latest {
6831                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6832         } else {
6833                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6834         }
6835
6836         check_closed_broadcast!(nodes[0], true);
6837         check_added_monitors!(nodes[0], 1);
6838         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6839
6840         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6841         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6842         let events = nodes[0].node.get_and_clear_pending_events();
6843         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6844         assert_eq!(events.len(), 4);
6845         let mut first_failed = false;
6846         for event in events {
6847                 match event {
6848                         Event::PaymentPathFailed { payment_hash, .. } => {
6849                                 if payment_hash == payment_hash_1 {
6850                                         assert!(!first_failed);
6851                                         first_failed = true;
6852                                 } else {
6853                                         assert_eq!(payment_hash, payment_hash_2);
6854                                 }
6855                         },
6856                         Event::PaymentFailed { .. } => {}
6857                         _ => panic!("Unexpected event"),
6858                 }
6859         }
6860 }
6861
6862 #[test]
6863 fn test_failure_delay_dust_htlc_local_commitment() {
6864         do_test_failure_delay_dust_htlc_local_commitment(true);
6865         do_test_failure_delay_dust_htlc_local_commitment(false);
6866 }
6867
6868 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6869         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6870         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6871         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6872         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6873         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6874         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6875
6876         let chanmon_cfgs = create_chanmon_cfgs(3);
6877         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6878         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6879         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6880         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6881
6882         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6883                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6884
6885         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6886         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6887
6888         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6889         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6890
6891         // We revoked bs_commitment_tx
6892         if revoked {
6893                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6894                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6895         }
6896
6897         let mut timeout_tx = Vec::new();
6898         if local {
6899                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6900                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6901                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6902                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6903                 expect_payment_failed!(nodes[0], dust_hash, false);
6904
6905                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6906                 check_closed_broadcast!(nodes[0], true);
6907                 check_added_monitors!(nodes[0], 1);
6908                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6909                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6910                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6911                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6912                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6913                 mine_transaction(&nodes[0], &timeout_tx[0]);
6914                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6915                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6916         } else {
6917                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6918                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6919                 check_closed_broadcast!(nodes[0], true);
6920                 check_added_monitors!(nodes[0], 1);
6921                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6922                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6923
6924                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6925                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6926                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6927                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6928                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6929                 // dust HTLC should have been failed.
6930                 expect_payment_failed!(nodes[0], dust_hash, false);
6931
6932                 if !revoked {
6933                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6934                 } else {
6935                         assert_eq!(timeout_tx[0].lock_time.0, 11);
6936                 }
6937                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6938                 mine_transaction(&nodes[0], &timeout_tx[0]);
6939                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6940                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6941                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6942         }
6943 }
6944
6945 #[test]
6946 fn test_sweep_outbound_htlc_failure_update() {
6947         do_test_sweep_outbound_htlc_failure_update(false, true);
6948         do_test_sweep_outbound_htlc_failure_update(false, false);
6949         do_test_sweep_outbound_htlc_failure_update(true, false);
6950 }
6951
6952 #[test]
6953 fn test_user_configurable_csv_delay() {
6954         // We test our channel constructors yield errors when we pass them absurd csv delay
6955
6956         let mut low_our_to_self_config = UserConfig::default();
6957         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6958         let mut high_their_to_self_config = UserConfig::default();
6959         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6960         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6961         let chanmon_cfgs = create_chanmon_cfgs(2);
6962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6964         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6965
6966         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
6967         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6968                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6969                 &low_our_to_self_config, 0, 42)
6970         {
6971                 match error {
6972                         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())); },
6973                         _ => panic!("Unexpected event"),
6974                 }
6975         } else { assert!(false) }
6976
6977         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
6978         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6979         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6980         open_channel.to_self_delay = 200;
6981         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6982                 &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,
6983                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6984         {
6985                 match error {
6986                         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()));  },
6987                         _ => panic!("Unexpected event"),
6988                 }
6989         } else { assert!(false); }
6990
6991         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6992         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6993         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()));
6994         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6995         accept_channel.to_self_delay = 200;
6996         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6997         let reason_msg;
6998         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6999                 match action {
7000                         &ErrorAction::SendErrorMessage { ref msg } => {
7001                                 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()));
7002                                 reason_msg = msg.data.clone();
7003                         },
7004                         _ => { panic!(); }
7005                 }
7006         } else { panic!(); }
7007         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7008
7009         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7010         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7011         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7012         open_channel.to_self_delay = 200;
7013         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7014                 &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,
7015                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7016         {
7017                 match error {
7018                         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())); },
7019                         _ => panic!("Unexpected event"),
7020                 }
7021         } else { assert!(false); }
7022 }
7023
7024 #[test]
7025 fn test_check_htlc_underpaying() {
7026         // Send payment through A -> B but A is maliciously
7027         // sending a probe payment (i.e less than expected value0
7028         // to B, B should refuse payment.
7029
7030         let chanmon_cfgs = create_chanmon_cfgs(2);
7031         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7032         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7033         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7034
7035         // Create some initial channels
7036         create_announced_chan_between_nodes(&nodes, 0, 1);
7037
7038         let scorer = test_utils::TestScorer::new();
7039         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7040         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7041         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7042         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7043         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7044         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7045                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7046         check_added_monitors!(nodes[0], 1);
7047
7048         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7049         assert_eq!(events.len(), 1);
7050         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7051         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7052         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7053
7054         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7055         // and then will wait a second random delay before failing the HTLC back:
7056         expect_pending_htlcs_forwardable!(nodes[1]);
7057         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7058
7059         // Node 3 is expecting payment of 100_000 but received 10_000,
7060         // it should fail htlc like we didn't know the preimage.
7061         nodes[1].node.process_pending_htlc_forwards();
7062
7063         let events = nodes[1].node.get_and_clear_pending_msg_events();
7064         assert_eq!(events.len(), 1);
7065         let (update_fail_htlc, commitment_signed) = match events[0] {
7066                 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 } } => {
7067                         assert!(update_add_htlcs.is_empty());
7068                         assert!(update_fulfill_htlcs.is_empty());
7069                         assert_eq!(update_fail_htlcs.len(), 1);
7070                         assert!(update_fail_malformed_htlcs.is_empty());
7071                         assert!(update_fee.is_none());
7072                         (update_fail_htlcs[0].clone(), commitment_signed)
7073                 },
7074                 _ => panic!("Unexpected event"),
7075         };
7076         check_added_monitors!(nodes[1], 1);
7077
7078         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7079         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7080
7081         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7082         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7083         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7084         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7085 }
7086
7087 #[test]
7088 fn test_announce_disable_channels() {
7089         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7090         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7091
7092         let chanmon_cfgs = create_chanmon_cfgs(2);
7093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7096
7097         create_announced_chan_between_nodes(&nodes, 0, 1);
7098         create_announced_chan_between_nodes(&nodes, 1, 0);
7099         create_announced_chan_between_nodes(&nodes, 0, 1);
7100
7101         // Disconnect peers
7102         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7103         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7104
7105         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7106                 nodes[0].node.timer_tick_occurred();
7107         }
7108         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7109         assert_eq!(msg_events.len(), 3);
7110         let mut chans_disabled = HashMap::new();
7111         for e in msg_events {
7112                 match e {
7113                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7114                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7115                                 // Check that each channel gets updated exactly once
7116                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7117                                         panic!("Generated ChannelUpdate for wrong chan!");
7118                                 }
7119                         },
7120                         _ => panic!("Unexpected event"),
7121                 }
7122         }
7123         // Reconnect peers
7124         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7125                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7126         }, true).unwrap();
7127         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7128         assert_eq!(reestablish_1.len(), 3);
7129         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7130                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7131         }, false).unwrap();
7132         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7133         assert_eq!(reestablish_2.len(), 3);
7134
7135         // Reestablish chan_1
7136         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7137         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7138         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7139         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7140         // Reestablish chan_2
7141         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7142         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7143         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7144         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7145         // Reestablish chan_3
7146         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7147         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7148         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7149         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7150
7151         for _ in 0..ENABLE_GOSSIP_TICKS {
7152                 nodes[0].node.timer_tick_occurred();
7153         }
7154         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7155         nodes[0].node.timer_tick_occurred();
7156         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7157         assert_eq!(msg_events.len(), 3);
7158         for e in msg_events {
7159                 match e {
7160                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7161                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7162                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7163                                         // Each update should have a higher timestamp than the previous one, replacing
7164                                         // the old one.
7165                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7166                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7167                                 }
7168                         },
7169                         _ => panic!("Unexpected event"),
7170                 }
7171         }
7172         // Check that each channel gets updated exactly once
7173         assert!(chans_disabled.is_empty());
7174 }
7175
7176 #[test]
7177 fn test_bump_penalty_txn_on_revoked_commitment() {
7178         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7179         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7180
7181         let chanmon_cfgs = create_chanmon_cfgs(2);
7182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7184         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7185
7186         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7187
7188         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7189         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7190                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7191         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7192         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7193
7194         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7195         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7196         assert_eq!(revoked_txn[0].output.len(), 4);
7197         assert_eq!(revoked_txn[0].input.len(), 1);
7198         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7199         let revoked_txid = revoked_txn[0].txid();
7200
7201         let mut penalty_sum = 0;
7202         for outp in revoked_txn[0].output.iter() {
7203                 if outp.script_pubkey.is_v0_p2wsh() {
7204                         penalty_sum += outp.value;
7205                 }
7206         }
7207
7208         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7209         let header_114 = connect_blocks(&nodes[1], 14);
7210
7211         // Actually revoke tx by claiming a HTLC
7212         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7213         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7214         check_added_monitors!(nodes[1], 1);
7215
7216         // One or more justice tx should have been broadcast, check it
7217         let penalty_1;
7218         let feerate_1;
7219         {
7220                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7221                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7222                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7223                 assert_eq!(node_txn[0].output.len(), 1);
7224                 check_spends!(node_txn[0], revoked_txn[0]);
7225                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7226                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7227                 penalty_1 = node_txn[0].txid();
7228                 node_txn.clear();
7229         };
7230
7231         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7232         connect_blocks(&nodes[1], 15);
7233         let mut penalty_2 = penalty_1;
7234         let mut feerate_2 = 0;
7235         {
7236                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7237                 assert_eq!(node_txn.len(), 1);
7238                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7239                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7240                         assert_eq!(node_txn[0].output.len(), 1);
7241                         check_spends!(node_txn[0], revoked_txn[0]);
7242                         penalty_2 = node_txn[0].txid();
7243                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7244                         assert_ne!(penalty_2, penalty_1);
7245                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7246                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7247                         // Verify 25% bump heuristic
7248                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7249                         node_txn.clear();
7250                 }
7251         }
7252         assert_ne!(feerate_2, 0);
7253
7254         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7255         connect_blocks(&nodes[1], 1);
7256         let penalty_3;
7257         let mut feerate_3 = 0;
7258         {
7259                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7260                 assert_eq!(node_txn.len(), 1);
7261                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7262                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7263                         assert_eq!(node_txn[0].output.len(), 1);
7264                         check_spends!(node_txn[0], revoked_txn[0]);
7265                         penalty_3 = node_txn[0].txid();
7266                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7267                         assert_ne!(penalty_3, penalty_2);
7268                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7269                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7270                         // Verify 25% bump heuristic
7271                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7272                         node_txn.clear();
7273                 }
7274         }
7275         assert_ne!(feerate_3, 0);
7276
7277         nodes[1].node.get_and_clear_pending_events();
7278         nodes[1].node.get_and_clear_pending_msg_events();
7279 }
7280
7281 #[test]
7282 fn test_bump_penalty_txn_on_revoked_htlcs() {
7283         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7284         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7285
7286         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7287         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7288         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7289         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7290         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7291
7292         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7293         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7294         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7295         let scorer = test_utils::TestScorer::new();
7296         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7297         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7298                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7299         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7300         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7301         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7302                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7303         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7304
7305         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7306         assert_eq!(revoked_local_txn[0].input.len(), 1);
7307         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7308
7309         // Revoke local commitment tx
7310         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7311
7312         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7313         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7314         check_closed_broadcast!(nodes[1], true);
7315         check_added_monitors!(nodes[1], 1);
7316         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7317         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7318
7319         let revoked_htlc_txn = {
7320                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7321                 assert_eq!(txn.len(), 2);
7322
7323                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7324                 assert_eq!(txn[0].input.len(), 1);
7325                 check_spends!(txn[0], revoked_local_txn[0]);
7326
7327                 assert_eq!(txn[1].input.len(), 1);
7328                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7329                 assert_eq!(txn[1].output.len(), 1);
7330                 check_spends!(txn[1], revoked_local_txn[0]);
7331
7332                 txn
7333         };
7334
7335         // Broadcast set of revoked txn on A
7336         let hash_128 = connect_blocks(&nodes[0], 40);
7337         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7338         connect_block(&nodes[0], &block_11);
7339         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7340         connect_block(&nodes[0], &block_129);
7341         let events = nodes[0].node.get_and_clear_pending_events();
7342         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7343         match events.last().unwrap() {
7344                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7345                 _ => panic!("Unexpected event"),
7346         }
7347         let first;
7348         let feerate_1;
7349         let penalty_txn;
7350         {
7351                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7352                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7353                 // Verify claim tx are spending revoked HTLC txn
7354
7355                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7356                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7357                 // which are included in the same block (they are broadcasted because we scan the
7358                 // transactions linearly and generate claims as we go, they likely should be removed in the
7359                 // future).
7360                 assert_eq!(node_txn[0].input.len(), 1);
7361                 check_spends!(node_txn[0], revoked_local_txn[0]);
7362                 assert_eq!(node_txn[1].input.len(), 1);
7363                 check_spends!(node_txn[1], revoked_local_txn[0]);
7364                 assert_eq!(node_txn[2].input.len(), 1);
7365                 check_spends!(node_txn[2], revoked_local_txn[0]);
7366
7367                 // Each of the three justice transactions claim a separate (single) output of the three
7368                 // available, which we check here:
7369                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7370                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7371                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7372
7373                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7374                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7375
7376                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7377                 // output, checked above).
7378                 assert_eq!(node_txn[3].input.len(), 2);
7379                 assert_eq!(node_txn[3].output.len(), 1);
7380                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7381
7382                 first = node_txn[3].txid();
7383                 // Store both feerates for later comparison
7384                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7385                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7386                 penalty_txn = vec![node_txn[2].clone()];
7387                 node_txn.clear();
7388         }
7389
7390         // Connect one more block to see if bumped penalty are issued for HTLC txn
7391         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7392         connect_block(&nodes[0], &block_130);
7393         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7394         connect_block(&nodes[0], &block_131);
7395
7396         // Few more blocks to confirm penalty txn
7397         connect_blocks(&nodes[0], 4);
7398         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7399         let header_144 = connect_blocks(&nodes[0], 9);
7400         let node_txn = {
7401                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7402                 assert_eq!(node_txn.len(), 1);
7403
7404                 assert_eq!(node_txn[0].input.len(), 2);
7405                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7406                 // Verify bumped tx is different and 25% bump heuristic
7407                 assert_ne!(first, node_txn[0].txid());
7408                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7409                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7410                 assert!(feerate_2 * 100 > feerate_1 * 125);
7411                 let txn = vec![node_txn[0].clone()];
7412                 node_txn.clear();
7413                 txn
7414         };
7415         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7416         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7417         connect_blocks(&nodes[0], 20);
7418         {
7419                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7420                 // We verify than no new transaction has been broadcast because previously
7421                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7422                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7423                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7424                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7425                 // up bumped justice generation.
7426                 assert_eq!(node_txn.len(), 0);
7427                 node_txn.clear();
7428         }
7429         check_closed_broadcast!(nodes[0], true);
7430         check_added_monitors!(nodes[0], 1);
7431 }
7432
7433 #[test]
7434 fn test_bump_penalty_txn_on_remote_commitment() {
7435         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7436         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7437
7438         // Create 2 HTLCs
7439         // Provide preimage for one
7440         // Check aggregation
7441
7442         let chanmon_cfgs = create_chanmon_cfgs(2);
7443         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7444         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7445         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7446
7447         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7448         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7449         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7450
7451         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7452         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7453         assert_eq!(remote_txn[0].output.len(), 4);
7454         assert_eq!(remote_txn[0].input.len(), 1);
7455         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7456
7457         // Claim a HTLC without revocation (provide B monitor with preimage)
7458         nodes[1].node.claim_funds(payment_preimage);
7459         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7460         mine_transaction(&nodes[1], &remote_txn[0]);
7461         check_added_monitors!(nodes[1], 2);
7462         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7463
7464         // One or more claim tx should have been broadcast, check it
7465         let timeout;
7466         let preimage;
7467         let preimage_bump;
7468         let feerate_timeout;
7469         let feerate_preimage;
7470         {
7471                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7472                 // 3 transactions including:
7473                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7474                 assert_eq!(node_txn.len(), 3);
7475                 assert_eq!(node_txn[0].input.len(), 1);
7476                 assert_eq!(node_txn[1].input.len(), 1);
7477                 assert_eq!(node_txn[2].input.len(), 1);
7478                 check_spends!(node_txn[0], remote_txn[0]);
7479                 check_spends!(node_txn[1], remote_txn[0]);
7480                 check_spends!(node_txn[2], remote_txn[0]);
7481
7482                 preimage = node_txn[0].txid();
7483                 let index = node_txn[0].input[0].previous_output.vout;
7484                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7485                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7486
7487                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7488                         (node_txn[2].clone(), node_txn[1].clone())
7489                 } else {
7490                         (node_txn[1].clone(), node_txn[2].clone())
7491                 };
7492
7493                 preimage_bump = preimage_bump_tx;
7494                 check_spends!(preimage_bump, remote_txn[0]);
7495                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7496
7497                 timeout = timeout_tx.txid();
7498                 let index = timeout_tx.input[0].previous_output.vout;
7499                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7500                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7501
7502                 node_txn.clear();
7503         };
7504         assert_ne!(feerate_timeout, 0);
7505         assert_ne!(feerate_preimage, 0);
7506
7507         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7508         connect_blocks(&nodes[1], 1);
7509         {
7510                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7511                 assert_eq!(node_txn.len(), 1);
7512                 assert_eq!(node_txn[0].input.len(), 1);
7513                 assert_eq!(preimage_bump.input.len(), 1);
7514                 check_spends!(node_txn[0], remote_txn[0]);
7515                 check_spends!(preimage_bump, remote_txn[0]);
7516
7517                 let index = preimage_bump.input[0].previous_output.vout;
7518                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7519                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7520                 assert!(new_feerate * 100 > feerate_timeout * 125);
7521                 assert_ne!(timeout, preimage_bump.txid());
7522
7523                 let index = node_txn[0].input[0].previous_output.vout;
7524                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7525                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7526                 assert!(new_feerate * 100 > feerate_preimage * 125);
7527                 assert_ne!(preimage, node_txn[0].txid());
7528
7529                 node_txn.clear();
7530         }
7531
7532         nodes[1].node.get_and_clear_pending_events();
7533         nodes[1].node.get_and_clear_pending_msg_events();
7534 }
7535
7536 #[test]
7537 fn test_counterparty_raa_skip_no_crash() {
7538         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7539         // commitment transaction, we would have happily carried on and provided them the next
7540         // commitment transaction based on one RAA forward. This would probably eventually have led to
7541         // channel closure, but it would not have resulted in funds loss. Still, our
7542         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7543         // check simply that the channel is closed in response to such an RAA, but don't check whether
7544         // we decide to punish our counterparty for revoking their funds (as we don't currently
7545         // implement that).
7546         let chanmon_cfgs = create_chanmon_cfgs(2);
7547         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7548         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7549         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7550         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7551
7552         let per_commitment_secret;
7553         let next_per_commitment_point;
7554         {
7555                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7556                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7557                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7558
7559                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7560
7561                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7562                 keys.get_enforcement_state().last_holder_commitment -= 1;
7563                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7564
7565                 // Must revoke without gaps
7566                 keys.get_enforcement_state().last_holder_commitment -= 1;
7567                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7568
7569                 keys.get_enforcement_state().last_holder_commitment -= 1;
7570                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7571                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7572         }
7573
7574         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7575                 &msgs::RevokeAndACK {
7576                         channel_id,
7577                         per_commitment_secret,
7578                         next_per_commitment_point,
7579                         #[cfg(taproot)]
7580                         next_local_nonce: None,
7581                 });
7582         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7583         check_added_monitors!(nodes[1], 1);
7584         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7585 }
7586
7587 #[test]
7588 fn test_bump_txn_sanitize_tracking_maps() {
7589         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7590         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7591
7592         let chanmon_cfgs = create_chanmon_cfgs(2);
7593         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7594         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7595         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7596
7597         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7598         // Lock HTLC in both directions
7599         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7600         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7601
7602         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7603         assert_eq!(revoked_local_txn[0].input.len(), 1);
7604         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7605
7606         // Revoke local commitment tx
7607         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7608
7609         // Broadcast set of revoked txn on A
7610         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7611         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7612         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7613
7614         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7615         check_closed_broadcast!(nodes[0], true);
7616         check_added_monitors!(nodes[0], 1);
7617         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7618         let penalty_txn = {
7619                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7620                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7621                 check_spends!(node_txn[0], revoked_local_txn[0]);
7622                 check_spends!(node_txn[1], revoked_local_txn[0]);
7623                 check_spends!(node_txn[2], revoked_local_txn[0]);
7624                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7625                 node_txn.clear();
7626                 penalty_txn
7627         };
7628         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7629         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7630         {
7631                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7632                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7633                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7634         }
7635 }
7636
7637 #[test]
7638 fn test_channel_conf_timeout() {
7639         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7640         // confirm within 2016 blocks, as recommended by BOLT 2.
7641         let chanmon_cfgs = create_chanmon_cfgs(2);
7642         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7643         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7644         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7645
7646         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7647
7648         // The outbound node should wait forever for confirmation:
7649         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7650         // copied here instead of directly referencing the constant.
7651         connect_blocks(&nodes[0], 2016);
7652         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7653
7654         // The inbound node should fail the channel after exactly 2016 blocks
7655         connect_blocks(&nodes[1], 2015);
7656         check_added_monitors!(nodes[1], 0);
7657         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7658
7659         connect_blocks(&nodes[1], 1);
7660         check_added_monitors!(nodes[1], 1);
7661         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7662         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7663         assert_eq!(close_ev.len(), 1);
7664         match close_ev[0] {
7665                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7666                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7667                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7668                 },
7669                 _ => panic!("Unexpected event"),
7670         }
7671 }
7672
7673 #[test]
7674 fn test_override_channel_config() {
7675         let chanmon_cfgs = create_chanmon_cfgs(2);
7676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7678         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7679
7680         // Node0 initiates a channel to node1 using the override config.
7681         let mut override_config = UserConfig::default();
7682         override_config.channel_handshake_config.our_to_self_delay = 200;
7683
7684         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7685
7686         // Assert the channel created by node0 is using the override config.
7687         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7688         assert_eq!(res.channel_flags, 0);
7689         assert_eq!(res.to_self_delay, 200);
7690 }
7691
7692 #[test]
7693 fn test_override_0msat_htlc_minimum() {
7694         let mut zero_config = UserConfig::default();
7695         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7696         let chanmon_cfgs = create_chanmon_cfgs(2);
7697         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7698         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7699         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7700
7701         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7702         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7703         assert_eq!(res.htlc_minimum_msat, 1);
7704
7705         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7706         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7707         assert_eq!(res.htlc_minimum_msat, 1);
7708 }
7709
7710 #[test]
7711 fn test_channel_update_has_correct_htlc_maximum_msat() {
7712         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7713         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7714         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7715         // 90% of the `channel_value`.
7716         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7717
7718         let mut config_30_percent = UserConfig::default();
7719         config_30_percent.channel_handshake_config.announced_channel = true;
7720         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7721         let mut config_50_percent = UserConfig::default();
7722         config_50_percent.channel_handshake_config.announced_channel = true;
7723         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7724         let mut config_95_percent = UserConfig::default();
7725         config_95_percent.channel_handshake_config.announced_channel = true;
7726         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7727         let mut config_100_percent = UserConfig::default();
7728         config_100_percent.channel_handshake_config.announced_channel = true;
7729         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7730
7731         let chanmon_cfgs = create_chanmon_cfgs(4);
7732         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7733         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)]);
7734         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7735
7736         let channel_value_satoshis = 100000;
7737         let channel_value_msat = channel_value_satoshis * 1000;
7738         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7739         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7740         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7741
7742         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7743         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7744
7745         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7746         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7747         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7748         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7749         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7750         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7751
7752         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7753         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7754         // `channel_value`.
7755         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7756         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7757         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7758         // `channel_value`.
7759         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7760 }
7761
7762 #[test]
7763 fn test_manually_accept_inbound_channel_request() {
7764         let mut manually_accept_conf = UserConfig::default();
7765         manually_accept_conf.manually_accept_inbound_channels = true;
7766         let chanmon_cfgs = create_chanmon_cfgs(2);
7767         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7768         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7769         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7770
7771         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7772         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7773
7774         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7775
7776         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7777         // accepting the inbound channel request.
7778         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7779
7780         let events = nodes[1].node.get_and_clear_pending_events();
7781         match events[0] {
7782                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7783                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7784                 }
7785                 _ => panic!("Unexpected event"),
7786         }
7787
7788         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7789         assert_eq!(accept_msg_ev.len(), 1);
7790
7791         match accept_msg_ev[0] {
7792                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7793                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7794                 }
7795                 _ => panic!("Unexpected event"),
7796         }
7797
7798         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7799
7800         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7801         assert_eq!(close_msg_ev.len(), 1);
7802
7803         let events = nodes[1].node.get_and_clear_pending_events();
7804         match events[0] {
7805                 Event::ChannelClosed { user_channel_id, .. } => {
7806                         assert_eq!(user_channel_id, 23);
7807                 }
7808                 _ => panic!("Unexpected event"),
7809         }
7810 }
7811
7812 #[test]
7813 fn test_manually_reject_inbound_channel_request() {
7814         let mut manually_accept_conf = UserConfig::default();
7815         manually_accept_conf.manually_accept_inbound_channels = true;
7816         let chanmon_cfgs = create_chanmon_cfgs(2);
7817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7820
7821         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7822         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7823
7824         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7825
7826         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7827         // rejecting the inbound channel request.
7828         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7829
7830         let events = nodes[1].node.get_and_clear_pending_events();
7831         match events[0] {
7832                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7833                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7834                 }
7835                 _ => panic!("Unexpected event"),
7836         }
7837
7838         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7839         assert_eq!(close_msg_ev.len(), 1);
7840
7841         match close_msg_ev[0] {
7842                 MessageSendEvent::HandleError { ref node_id, .. } => {
7843                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7844                 }
7845                 _ => panic!("Unexpected event"),
7846         }
7847         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7848 }
7849
7850 #[test]
7851 fn test_reject_funding_before_inbound_channel_accepted() {
7852         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7853         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7854         // the node operator before the counterparty sends a `FundingCreated` message. If a
7855         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7856         // and the channel should be closed.
7857         let mut manually_accept_conf = UserConfig::default();
7858         manually_accept_conf.manually_accept_inbound_channels = true;
7859         let chanmon_cfgs = create_chanmon_cfgs(2);
7860         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7861         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7862         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7863
7864         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7865         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7866         let temp_channel_id = res.temporary_channel_id;
7867
7868         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7869
7870         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7871         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7872
7873         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7874         nodes[1].node.get_and_clear_pending_events();
7875
7876         // Get the `AcceptChannel` message of `nodes[1]` without calling
7877         // `ChannelManager::accept_inbound_channel`, which generates a
7878         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7879         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7880         // succeed when `nodes[0]` is passed to it.
7881         let accept_chan_msg = {
7882                 let mut node_1_per_peer_lock;
7883                 let mut node_1_peer_state_lock;
7884                 let channel =  get_inbound_v1_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7885                 channel.get_accept_channel_message()
7886         };
7887         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7888
7889         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7890
7891         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7892         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7893
7894         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7895         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7896
7897         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7898         assert_eq!(close_msg_ev.len(), 1);
7899
7900         let expected_err = "FundingCreated message received before the channel was accepted";
7901         match close_msg_ev[0] {
7902                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7903                         assert_eq!(msg.channel_id, temp_channel_id);
7904                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7905                         assert_eq!(msg.data, expected_err);
7906                 }
7907                 _ => panic!("Unexpected event"),
7908         }
7909
7910         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7911 }
7912
7913 #[test]
7914 fn test_can_not_accept_inbound_channel_twice() {
7915         let mut manually_accept_conf = UserConfig::default();
7916         manually_accept_conf.manually_accept_inbound_channels = true;
7917         let chanmon_cfgs = create_chanmon_cfgs(2);
7918         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7919         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7920         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7921
7922         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7923         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7924
7925         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7926
7927         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7928         // accepting the inbound channel request.
7929         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7930
7931         let events = nodes[1].node.get_and_clear_pending_events();
7932         match events[0] {
7933                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7934                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7935                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7936                         match api_res {
7937                                 Err(APIError::APIMisuseError { err }) => {
7938                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7939                                 },
7940                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7941                                 Err(_) => panic!("Unexpected Error"),
7942                         }
7943                 }
7944                 _ => panic!("Unexpected event"),
7945         }
7946
7947         // Ensure that the channel wasn't closed after attempting to accept it twice.
7948         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7949         assert_eq!(accept_msg_ev.len(), 1);
7950
7951         match accept_msg_ev[0] {
7952                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7953                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7954                 }
7955                 _ => panic!("Unexpected event"),
7956         }
7957 }
7958
7959 #[test]
7960 fn test_can_not_accept_unknown_inbound_channel() {
7961         let chanmon_cfg = create_chanmon_cfgs(2);
7962         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7963         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7964         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7965
7966         let unknown_channel_id = [0; 32];
7967         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7968         match api_res {
7969                 Err(APIError::ChannelUnavailable { err }) => {
7970                         assert_eq!(err, format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(unknown_channel_id), nodes[1].node.get_our_node_id()));
7971                 },
7972                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7973                 Err(_) => panic!("Unexpected Error"),
7974         }
7975 }
7976
7977 #[test]
7978 fn test_onion_value_mpp_set_calculation() {
7979         // Test that we use the onion value `amt_to_forward` when
7980         // calculating whether we've reached the `total_msat` of an MPP
7981         // by having a routing node forward more than `amt_to_forward`
7982         // and checking that the receiving node doesn't generate
7983         // a PaymentClaimable event too early
7984         let node_count = 4;
7985         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7986         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7987         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7988         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7989
7990         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7991         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7992         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7993         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7994
7995         let total_msat = 100_000;
7996         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7997         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7998         let sample_path = route.paths.pop().unwrap();
7999
8000         let mut path_1 = sample_path.clone();
8001         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8002         path_1.hops[0].short_channel_id = chan_1_id;
8003         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8004         path_1.hops[1].short_channel_id = chan_3_id;
8005         path_1.hops[1].fee_msat = 100_000;
8006         route.paths.push(path_1);
8007
8008         let mut path_2 = sample_path.clone();
8009         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8010         path_2.hops[0].short_channel_id = chan_2_id;
8011         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8012         path_2.hops[1].short_channel_id = chan_4_id;
8013         path_2.hops[1].fee_msat = 1_000;
8014         route.paths.push(path_2);
8015
8016         // Send payment
8017         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8018         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8019                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8020         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8021                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8022         check_added_monitors!(nodes[0], expected_paths.len());
8023
8024         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8025         assert_eq!(events.len(), expected_paths.len());
8026
8027         // First path
8028         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8029         let mut payment_event = SendEvent::from_event(ev);
8030         let mut prev_node = &nodes[0];
8031
8032         for (idx, &node) in expected_paths[0].iter().enumerate() {
8033                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8034
8035                 if idx == 0 { // routing node
8036                         let session_priv = [3; 32];
8037                         let height = nodes[0].best_block_info().1;
8038                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8039                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8040                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8041                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8042                         // Edit amt_to_forward to simulate the sender having set
8043                         // the final amount and the routing node taking less fee
8044                         onion_payloads[1].amt_to_forward = 99_000;
8045                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8046                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8047                 }
8048
8049                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8050                 check_added_monitors!(node, 0);
8051                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8052                 expect_pending_htlcs_forwardable!(node);
8053
8054                 if idx == 0 {
8055                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8056                         assert_eq!(events_2.len(), 1);
8057                         check_added_monitors!(node, 1);
8058                         payment_event = SendEvent::from_event(events_2.remove(0));
8059                         assert_eq!(payment_event.msgs.len(), 1);
8060                 } else {
8061                         let events_2 = node.node.get_and_clear_pending_events();
8062                         assert!(events_2.is_empty());
8063                 }
8064
8065                 prev_node = node;
8066         }
8067
8068         // Second path
8069         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8070         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8071
8072         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8073 }
8074
8075 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8076
8077         let routing_node_count = msat_amounts.len();
8078         let node_count = routing_node_count + 2;
8079
8080         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8081         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8082         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8083         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8084
8085         let src_idx = 0;
8086         let dst_idx = 1;
8087
8088         // Create channels for each amount
8089         let mut expected_paths = Vec::with_capacity(routing_node_count);
8090         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8091         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8092         for i in 0..routing_node_count {
8093                 let routing_node = 2 + i;
8094                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8095                 src_chan_ids.push(src_chan_id);
8096                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8097                 dst_chan_ids.push(dst_chan_id);
8098                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8099                 expected_paths.push(path);
8100         }
8101         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8102
8103         // Create a route for each amount
8104         let example_amount = 100000;
8105         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);
8106         let sample_path = route.paths.pop().unwrap();
8107         for i in 0..routing_node_count {
8108                 let routing_node = 2 + i;
8109                 let mut path = sample_path.clone();
8110                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8111                 path.hops[0].short_channel_id = src_chan_ids[i];
8112                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8113                 path.hops[1].short_channel_id = dst_chan_ids[i];
8114                 path.hops[1].fee_msat = msat_amounts[i];
8115                 route.paths.push(path);
8116         }
8117
8118         // Send payment with manually set total_msat
8119         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8120         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8121                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8122         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8123                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8124         check_added_monitors!(nodes[src_idx], expected_paths.len());
8125
8126         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8127         assert_eq!(events.len(), expected_paths.len());
8128         let mut amount_received = 0;
8129         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8130                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8131
8132                 let current_path_amount = msat_amounts[path_idx];
8133                 amount_received += current_path_amount;
8134                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8135                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8136         }
8137
8138         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8139 }
8140
8141 #[test]
8142 fn test_overshoot_mpp() {
8143         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8144         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8145 }
8146
8147 #[test]
8148 fn test_simple_mpp() {
8149         // Simple test of sending a multi-path payment.
8150         let chanmon_cfgs = create_chanmon_cfgs(4);
8151         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8152         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8153         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8154
8155         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8156         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8157         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8158         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8159
8160         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8161         let path = route.paths[0].clone();
8162         route.paths.push(path);
8163         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8164         route.paths[0].hops[0].short_channel_id = chan_1_id;
8165         route.paths[0].hops[1].short_channel_id = chan_3_id;
8166         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8167         route.paths[1].hops[0].short_channel_id = chan_2_id;
8168         route.paths[1].hops[1].short_channel_id = chan_4_id;
8169         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8170         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8171 }
8172
8173 #[test]
8174 fn test_preimage_storage() {
8175         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8176         let chanmon_cfgs = create_chanmon_cfgs(2);
8177         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8178         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8179         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8180
8181         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8182
8183         {
8184                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8185                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8186                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8187                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8188                 check_added_monitors!(nodes[0], 1);
8189                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8190                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8191                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8192                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8193         }
8194         // Note that after leaving the above scope we have no knowledge of any arguments or return
8195         // values from previous calls.
8196         expect_pending_htlcs_forwardable!(nodes[1]);
8197         let events = nodes[1].node.get_and_clear_pending_events();
8198         assert_eq!(events.len(), 1);
8199         match events[0] {
8200                 Event::PaymentClaimable { ref purpose, .. } => {
8201                         match &purpose {
8202                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8203                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8204                                 },
8205                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8206                         }
8207                 },
8208                 _ => panic!("Unexpected event"),
8209         }
8210 }
8211
8212 #[test]
8213 fn test_bad_secret_hash() {
8214         // Simple test of unregistered payment hash/invalid payment secret handling
8215         let chanmon_cfgs = create_chanmon_cfgs(2);
8216         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8217         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8218         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8219
8220         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8221
8222         let random_payment_hash = PaymentHash([42; 32]);
8223         let random_payment_secret = PaymentSecret([43; 32]);
8224         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8225         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8226
8227         // All the below cases should end up being handled exactly identically, so we macro the
8228         // resulting events.
8229         macro_rules! handle_unknown_invalid_payment_data {
8230                 ($payment_hash: expr) => {
8231                         check_added_monitors!(nodes[0], 1);
8232                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8233                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8234                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8235                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8236
8237                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8238                         // again to process the pending backwards-failure of the HTLC
8239                         expect_pending_htlcs_forwardable!(nodes[1]);
8240                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8241                         check_added_monitors!(nodes[1], 1);
8242
8243                         // We should fail the payment back
8244                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8245                         match events.pop().unwrap() {
8246                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8247                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8248                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8249                                 },
8250                                 _ => panic!("Unexpected event"),
8251                         }
8252                 }
8253         }
8254
8255         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8256         // Error data is the HTLC value (100,000) and current block height
8257         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8258
8259         // Send a payment with the right payment hash but the wrong payment secret
8260         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8261                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8262         handle_unknown_invalid_payment_data!(our_payment_hash);
8263         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8264
8265         // Send a payment with a random payment hash, but the right payment secret
8266         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8267                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8268         handle_unknown_invalid_payment_data!(random_payment_hash);
8269         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8270
8271         // Send a payment with a random payment hash and random payment secret
8272         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8273                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8274         handle_unknown_invalid_payment_data!(random_payment_hash);
8275         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8276 }
8277
8278 #[test]
8279 fn test_update_err_monitor_lockdown() {
8280         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8281         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8282         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8283         // error.
8284         //
8285         // This scenario may happen in a watchtower setup, where watchtower process a block height
8286         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8287         // commitment at same time.
8288
8289         let chanmon_cfgs = create_chanmon_cfgs(2);
8290         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8291         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8292         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8293
8294         // Create some initial channel
8295         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8296         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8297
8298         // Rebalance the network to generate htlc in the two directions
8299         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8300
8301         // Route a HTLC from node 0 to node 1 (but don't settle)
8302         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8303
8304         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8305         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8306         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8307         let persister = test_utils::TestPersister::new();
8308         let watchtower = {
8309                 let new_monitor = {
8310                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8311                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8312                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8313                         assert!(new_monitor == *monitor);
8314                         new_monitor
8315                 };
8316                 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);
8317                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8318                 watchtower
8319         };
8320         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8321         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8322         // transaction lock time requirements here.
8323         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8324         watchtower.chain_monitor.block_connected(&block, 200);
8325
8326         // Try to update ChannelMonitor
8327         nodes[1].node.claim_funds(preimage);
8328         check_added_monitors!(nodes[1], 1);
8329         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8330
8331         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8332         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8333         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8334         {
8335                 let mut node_0_per_peer_lock;
8336                 let mut node_0_peer_state_lock;
8337                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8338                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8339                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8340                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8341                 } else { assert!(false); }
8342         }
8343         // Our local monitor is in-sync and hasn't processed yet timeout
8344         check_added_monitors!(nodes[0], 1);
8345         let events = nodes[0].node.get_and_clear_pending_events();
8346         assert_eq!(events.len(), 1);
8347 }
8348
8349 #[test]
8350 fn test_concurrent_monitor_claim() {
8351         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8352         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8353         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8354         // state N+1 confirms. Alice claims output from state N+1.
8355
8356         let chanmon_cfgs = create_chanmon_cfgs(2);
8357         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8358         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8359         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8360
8361         // Create some initial channel
8362         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8363         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8364
8365         // Rebalance the network to generate htlc in the two directions
8366         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8367
8368         // Route a HTLC from node 0 to node 1 (but don't settle)
8369         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8370
8371         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8372         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8373         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8374         let persister = test_utils::TestPersister::new();
8375         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8376                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8377         );
8378         let watchtower_alice = {
8379                 let new_monitor = {
8380                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8381                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8382                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8383                         assert!(new_monitor == *monitor);
8384                         new_monitor
8385                 };
8386                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8387                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8388                 watchtower
8389         };
8390         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8391         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8392         // requirements here.
8393         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8394         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8395         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8396
8397         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8398         let alice_state = {
8399                 let mut txn = alice_broadcaster.txn_broadcast();
8400                 assert_eq!(txn.len(), 2);
8401                 txn.remove(0)
8402         };
8403
8404         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8405         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8406         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8407         let persister = test_utils::TestPersister::new();
8408         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8409         let watchtower_bob = {
8410                 let new_monitor = {
8411                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8412                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8413                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8414                         assert!(new_monitor == *monitor);
8415                         new_monitor
8416                 };
8417                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8418                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8419                 watchtower
8420         };
8421         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8422
8423         // Route another payment to generate another update with still previous HTLC pending
8424         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8425         nodes[1].node.send_payment_with_route(&route, payment_hash,
8426                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8427         check_added_monitors!(nodes[1], 1);
8428
8429         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8430         assert_eq!(updates.update_add_htlcs.len(), 1);
8431         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8432         {
8433                 let mut node_0_per_peer_lock;
8434                 let mut node_0_peer_state_lock;
8435                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8436                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8437                         // Watchtower Alice should already have seen the block and reject the update
8438                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8439                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8440                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8441                 } else { assert!(false); }
8442         }
8443         // Our local monitor is in-sync and hasn't processed yet timeout
8444         check_added_monitors!(nodes[0], 1);
8445
8446         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8447         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8448
8449         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8450         let bob_state_y;
8451         {
8452                 let mut txn = bob_broadcaster.txn_broadcast();
8453                 assert_eq!(txn.len(), 2);
8454                 bob_state_y = txn.remove(0);
8455         };
8456
8457         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8458         let height = HTLC_TIMEOUT_BROADCAST + 1;
8459         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8460         check_closed_broadcast(&nodes[0], 1, true);
8461         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8462         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8463         check_added_monitors(&nodes[0], 1);
8464         {
8465                 let htlc_txn = alice_broadcaster.txn_broadcast();
8466                 assert_eq!(htlc_txn.len(), 2);
8467                 check_spends!(htlc_txn[0], bob_state_y);
8468                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8469                 // it. However, she should, because it now has an invalid parent.
8470                 check_spends!(htlc_txn[1], alice_state);
8471         }
8472 }
8473
8474 #[test]
8475 fn test_pre_lockin_no_chan_closed_update() {
8476         // Test that if a peer closes a channel in response to a funding_created message we don't
8477         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8478         // message).
8479         //
8480         // Doing so would imply a channel monitor update before the initial channel monitor
8481         // registration, violating our API guarantees.
8482         //
8483         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8484         // then opening a second channel with the same funding output as the first (which is not
8485         // rejected because the first channel does not exist in the ChannelManager) and closing it
8486         // before receiving funding_signed.
8487         let chanmon_cfgs = create_chanmon_cfgs(2);
8488         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8489         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8490         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8491
8492         // Create an initial channel
8493         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8494         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8495         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8496         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8497         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8498
8499         // Move the first channel through the funding flow...
8500         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8501
8502         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8503         check_added_monitors!(nodes[0], 0);
8504
8505         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8506         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8507         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8508         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8509         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8510 }
8511
8512 #[test]
8513 fn test_htlc_no_detection() {
8514         // This test is a mutation to underscore the detection logic bug we had
8515         // before #653. HTLC value routed is above the remaining balance, thus
8516         // inverting HTLC and `to_remote` output. HTLC will come second and
8517         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8518         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8519         // outputs order detection for correct spending children filtring.
8520
8521         let chanmon_cfgs = create_chanmon_cfgs(2);
8522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8525
8526         // Create some initial channels
8527         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8528
8529         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8530         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8531         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8532         assert_eq!(local_txn[0].input.len(), 1);
8533         assert_eq!(local_txn[0].output.len(), 3);
8534         check_spends!(local_txn[0], chan_1.3);
8535
8536         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8537         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8538         connect_block(&nodes[0], &block);
8539         // We deliberately connect the local tx twice as this should provoke a failure calling
8540         // this test before #653 fix.
8541         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8542         check_closed_broadcast!(nodes[0], true);
8543         check_added_monitors!(nodes[0], 1);
8544         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8545         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8546
8547         let htlc_timeout = {
8548                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8549                 assert_eq!(node_txn.len(), 1);
8550                 assert_eq!(node_txn[0].input.len(), 1);
8551                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8552                 check_spends!(node_txn[0], local_txn[0]);
8553                 node_txn[0].clone()
8554         };
8555
8556         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8557         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8558         expect_payment_failed!(nodes[0], our_payment_hash, false);
8559 }
8560
8561 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8562         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8563         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8564         // Carol, Alice would be the upstream node, and Carol the downstream.)
8565         //
8566         // Steps of the test:
8567         // 1) Alice sends a HTLC to Carol through Bob.
8568         // 2) Carol doesn't settle the HTLC.
8569         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8570         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8571         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8572         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8573         // 5) Carol release the preimage to Bob off-chain.
8574         // 6) Bob claims the offered output on the broadcasted commitment.
8575         let chanmon_cfgs = create_chanmon_cfgs(3);
8576         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8577         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8578         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8579
8580         // Create some initial channels
8581         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8582         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8583
8584         // Steps (1) and (2):
8585         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8586         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8587
8588         // Check that Alice's commitment transaction now contains an output for this HTLC.
8589         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8590         check_spends!(alice_txn[0], chan_ab.3);
8591         assert_eq!(alice_txn[0].output.len(), 2);
8592         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8593         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8594         assert_eq!(alice_txn.len(), 2);
8595
8596         // Steps (3) and (4):
8597         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8598         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8599         let mut force_closing_node = 0; // Alice force-closes
8600         let mut counterparty_node = 1; // Bob if Alice force-closes
8601
8602         // Bob force-closes
8603         if !broadcast_alice {
8604                 force_closing_node = 1;
8605                 counterparty_node = 0;
8606         }
8607         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8608         check_closed_broadcast!(nodes[force_closing_node], true);
8609         check_added_monitors!(nodes[force_closing_node], 1);
8610         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8611         if go_onchain_before_fulfill {
8612                 let txn_to_broadcast = match broadcast_alice {
8613                         true => alice_txn.clone(),
8614                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8615                 };
8616                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8617                 if broadcast_alice {
8618                         check_closed_broadcast!(nodes[1], true);
8619                         check_added_monitors!(nodes[1], 1);
8620                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8621                 }
8622         }
8623
8624         // Step (5):
8625         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8626         // process of removing the HTLC from their commitment transactions.
8627         nodes[2].node.claim_funds(payment_preimage);
8628         check_added_monitors!(nodes[2], 1);
8629         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8630
8631         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8632         assert!(carol_updates.update_add_htlcs.is_empty());
8633         assert!(carol_updates.update_fail_htlcs.is_empty());
8634         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8635         assert!(carol_updates.update_fee.is_none());
8636         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8637
8638         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8639         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8640         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8641         if !go_onchain_before_fulfill && broadcast_alice {
8642                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8643                 assert_eq!(events.len(), 1);
8644                 match events[0] {
8645                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8646                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8647                         },
8648                         _ => panic!("Unexpected event"),
8649                 };
8650         }
8651         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8652         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8653         // Carol<->Bob's updated commitment transaction info.
8654         check_added_monitors!(nodes[1], 2);
8655
8656         let events = nodes[1].node.get_and_clear_pending_msg_events();
8657         assert_eq!(events.len(), 2);
8658         let bob_revocation = match events[0] {
8659                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8660                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8661                         (*msg).clone()
8662                 },
8663                 _ => panic!("Unexpected event"),
8664         };
8665         let bob_updates = match events[1] {
8666                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8667                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8668                         (*updates).clone()
8669                 },
8670                 _ => panic!("Unexpected event"),
8671         };
8672
8673         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8674         check_added_monitors!(nodes[2], 1);
8675         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8676         check_added_monitors!(nodes[2], 1);
8677
8678         let events = nodes[2].node.get_and_clear_pending_msg_events();
8679         assert_eq!(events.len(), 1);
8680         let carol_revocation = match events[0] {
8681                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8682                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8683                         (*msg).clone()
8684                 },
8685                 _ => panic!("Unexpected event"),
8686         };
8687         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8688         check_added_monitors!(nodes[1], 1);
8689
8690         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8691         // here's where we put said channel's commitment tx on-chain.
8692         let mut txn_to_broadcast = alice_txn.clone();
8693         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8694         if !go_onchain_before_fulfill {
8695                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8696                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8697                 if broadcast_alice {
8698                         check_closed_broadcast!(nodes[1], true);
8699                         check_added_monitors!(nodes[1], 1);
8700                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8701                 }
8702                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8703                 if broadcast_alice {
8704                         assert_eq!(bob_txn.len(), 1);
8705                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8706                 } else {
8707                         assert_eq!(bob_txn.len(), 2);
8708                         check_spends!(bob_txn[0], chan_ab.3);
8709                 }
8710         }
8711
8712         // Step (6):
8713         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8714         // broadcasted commitment transaction.
8715         {
8716                 let script_weight = match broadcast_alice {
8717                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8718                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8719                 };
8720                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8721                 // Bob force-closed and broadcasts the commitment transaction along with a
8722                 // HTLC-output-claiming transaction.
8723                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8724                 if broadcast_alice {
8725                         assert_eq!(bob_txn.len(), 1);
8726                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8727                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8728                 } else {
8729                         assert_eq!(bob_txn.len(), 2);
8730                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8731                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8732                 }
8733         }
8734 }
8735
8736 #[test]
8737 fn test_onchain_htlc_settlement_after_close() {
8738         do_test_onchain_htlc_settlement_after_close(true, true);
8739         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8740         do_test_onchain_htlc_settlement_after_close(true, false);
8741         do_test_onchain_htlc_settlement_after_close(false, false);
8742 }
8743
8744 #[test]
8745 fn test_duplicate_temporary_channel_id_from_different_peers() {
8746         // Tests that we can accept two different `OpenChannel` requests with the same
8747         // `temporary_channel_id`, as long as they are from different peers.
8748         let chanmon_cfgs = create_chanmon_cfgs(3);
8749         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8750         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8751         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8752
8753         // Create an first channel channel
8754         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8755         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8756
8757         // Create an second channel
8758         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8759         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8760
8761         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8762         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8763         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8764
8765         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8766         // `temporary_channel_id` as they are from different peers.
8767         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8768         {
8769                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8770                 assert_eq!(events.len(), 1);
8771                 match &events[0] {
8772                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8773                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8774                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8775                         },
8776                         _ => panic!("Unexpected event"),
8777                 }
8778         }
8779
8780         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8781         {
8782                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8783                 assert_eq!(events.len(), 1);
8784                 match &events[0] {
8785                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8786                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8787                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8788                         },
8789                         _ => panic!("Unexpected event"),
8790                 }
8791         }
8792 }
8793
8794 #[test]
8795 fn test_duplicate_chan_id() {
8796         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8797         // already open we reject it and keep the old channel.
8798         //
8799         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8800         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8801         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8802         // updating logic for the existing channel.
8803         let chanmon_cfgs = create_chanmon_cfgs(2);
8804         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8805         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8806         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8807
8808         // Create an initial channel
8809         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8810         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8811         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8812         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()));
8813
8814         // Try to create a second channel with the same temporary_channel_id as the first and check
8815         // that it is rejected.
8816         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8817         {
8818                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8819                 assert_eq!(events.len(), 1);
8820                 match events[0] {
8821                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8822                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8823                                 // first (valid) and second (invalid) channels are closed, given they both have
8824                                 // the same non-temporary channel_id. However, currently we do not, so we just
8825                                 // move forward with it.
8826                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8827                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8828                         },
8829                         _ => panic!("Unexpected event"),
8830                 }
8831         }
8832
8833         // Move the first channel through the funding flow...
8834         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8835
8836         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8837         check_added_monitors!(nodes[0], 0);
8838
8839         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8840         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8841         {
8842                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8843                 assert_eq!(added_monitors.len(), 1);
8844                 assert_eq!(added_monitors[0].0, funding_output);
8845                 added_monitors.clear();
8846         }
8847         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8848
8849         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8850
8851         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8852         let channel_id = funding_outpoint.to_channel_id();
8853
8854         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8855         // temporary one).
8856
8857         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8858         // Technically this is allowed by the spec, but we don't support it and there's little reason
8859         // to. Still, it shouldn't cause any other issues.
8860         open_chan_msg.temporary_channel_id = channel_id;
8861         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8862         {
8863                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8864                 assert_eq!(events.len(), 1);
8865                 match events[0] {
8866                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8867                                 // Technically, at this point, nodes[1] would be justified in thinking both
8868                                 // channels are closed, but currently we do not, so we just move forward with it.
8869                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8870                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8871                         },
8872                         _ => panic!("Unexpected event"),
8873                 }
8874         }
8875
8876         // Now try to create a second channel which has a duplicate funding output.
8877         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8878         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8879         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8880         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()));
8881         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8882
8883         let (_, funding_created) = {
8884                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8885                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8886                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8887                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8888                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8889                 // channelmanager in a possibly nonsense state instead).
8890                 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8891                 let logger = test_utils::TestLogger::new();
8892                 as_chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8893         };
8894         check_added_monitors!(nodes[0], 0);
8895         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8896         // At this point we'll look up if the channel_id is present and immediately fail the channel
8897         // without trying to persist the `ChannelMonitor`.
8898         check_added_monitors!(nodes[1], 0);
8899
8900         // ...still, nodes[1] will reject the duplicate channel.
8901         {
8902                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8903                 assert_eq!(events.len(), 1);
8904                 match events[0] {
8905                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8906                                 // Technically, at this point, nodes[1] would be justified in thinking both
8907                                 // channels are closed, but currently we do not, so we just move forward with it.
8908                                 assert_eq!(msg.channel_id, channel_id);
8909                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8910                         },
8911                         _ => panic!("Unexpected event"),
8912                 }
8913         }
8914
8915         // finally, finish creating the original channel and send a payment over it to make sure
8916         // everything is functional.
8917         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8918         {
8919                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8920                 assert_eq!(added_monitors.len(), 1);
8921                 assert_eq!(added_monitors[0].0, funding_output);
8922                 added_monitors.clear();
8923         }
8924         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8925
8926         let events_4 = nodes[0].node.get_and_clear_pending_events();
8927         assert_eq!(events_4.len(), 0);
8928         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8929         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8930
8931         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8932         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8933         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8934
8935         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8936 }
8937
8938 #[test]
8939 fn test_error_chans_closed() {
8940         // Test that we properly handle error messages, closing appropriate channels.
8941         //
8942         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8943         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8944         // we can test various edge cases around it to ensure we don't regress.
8945         let chanmon_cfgs = create_chanmon_cfgs(3);
8946         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8947         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8948         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8949
8950         // Create some initial channels
8951         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8952         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8953         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8954
8955         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8956         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8957         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8958
8959         // Closing a channel from a different peer has no effect
8960         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8961         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8962
8963         // Closing one channel doesn't impact others
8964         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8965         check_added_monitors!(nodes[0], 1);
8966         check_closed_broadcast!(nodes[0], false);
8967         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8968         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8969         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8970         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);
8971         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);
8972
8973         // A null channel ID should close all channels
8974         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8975         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8976         check_added_monitors!(nodes[0], 2);
8977         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8978         let events = nodes[0].node.get_and_clear_pending_msg_events();
8979         assert_eq!(events.len(), 2);
8980         match events[0] {
8981                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8982                         assert_eq!(msg.contents.flags & 2, 2);
8983                 },
8984                 _ => panic!("Unexpected event"),
8985         }
8986         match events[1] {
8987                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8988                         assert_eq!(msg.contents.flags & 2, 2);
8989                 },
8990                 _ => panic!("Unexpected event"),
8991         }
8992         // Note that at this point users of a standard PeerHandler will end up calling
8993         // peer_disconnected.
8994         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8995         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8996
8997         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8998         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8999         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9000 }
9001
9002 #[test]
9003 fn test_invalid_funding_tx() {
9004         // Test that we properly handle invalid funding transactions sent to us from a peer.
9005         //
9006         // Previously, all other major lightning implementations had failed to properly sanitize
9007         // funding transactions from their counterparties, leading to a multi-implementation critical
9008         // security vulnerability (though we always sanitized properly, we've previously had
9009         // un-released crashes in the sanitization process).
9010         //
9011         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9012         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9013         // gave up on it. We test this here by generating such a transaction.
9014         let chanmon_cfgs = create_chanmon_cfgs(2);
9015         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9016         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9017         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9018
9019         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9020         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()));
9021         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()));
9022
9023         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9024
9025         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9026         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9027         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9028         // its length.
9029         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9030         let wit_program_script: Script = wit_program.into();
9031         for output in tx.output.iter_mut() {
9032                 // Make the confirmed funding transaction have a bogus script_pubkey
9033                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9034         }
9035
9036         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9037         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()));
9038         check_added_monitors!(nodes[1], 1);
9039         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9040
9041         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()));
9042         check_added_monitors!(nodes[0], 1);
9043         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9044
9045         let events_1 = nodes[0].node.get_and_clear_pending_events();
9046         assert_eq!(events_1.len(), 0);
9047
9048         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9049         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9050         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9051
9052         let expected_err = "funding tx had wrong script/value or output index";
9053         confirm_transaction_at(&nodes[1], &tx, 1);
9054         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9055         check_added_monitors!(nodes[1], 1);
9056         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9057         assert_eq!(events_2.len(), 1);
9058         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9059                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9060                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9061                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9062                 } else { panic!(); }
9063         } else { panic!(); }
9064         assert_eq!(nodes[1].node.list_channels().len(), 0);
9065
9066         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9067         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9068         // as its not 32 bytes long.
9069         let mut spend_tx = Transaction {
9070                 version: 2i32, lock_time: PackedLockTime::ZERO,
9071                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9072                         previous_output: BitcoinOutPoint {
9073                                 txid: tx.txid(),
9074                                 vout: idx as u32,
9075                         },
9076                         script_sig: Script::new(),
9077                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9078                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9079                 }).collect(),
9080                 output: vec![TxOut {
9081                         value: 1000,
9082                         script_pubkey: Script::new(),
9083                 }]
9084         };
9085         check_spends!(spend_tx, tx);
9086         mine_transaction(&nodes[1], &spend_tx);
9087 }
9088
9089 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9090         // In the first version of the chain::Confirm interface, after a refactor was made to not
9091         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9092         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9093         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9094         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9095         // spending transaction until height N+1 (or greater). This was due to the way
9096         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9097         // spending transaction at the height the input transaction was confirmed at, not whether we
9098         // should broadcast a spending transaction at the current height.
9099         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9100         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9101         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9102         // until we learned about an additional block.
9103         //
9104         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9105         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9106         let chanmon_cfgs = create_chanmon_cfgs(3);
9107         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9108         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9109         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9110         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9111
9112         create_announced_chan_between_nodes(&nodes, 0, 1);
9113         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9114         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9115         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9116         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9117
9118         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9119         check_closed_broadcast!(nodes[1], true);
9120         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9121         check_added_monitors!(nodes[1], 1);
9122         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9123         assert_eq!(node_txn.len(), 1);
9124
9125         let conf_height = nodes[1].best_block_info().1;
9126         if !test_height_before_timelock {
9127                 connect_blocks(&nodes[1], 24 * 6);
9128         }
9129         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9130                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9131         if test_height_before_timelock {
9132                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9133                 // generate any events or broadcast any transactions
9134                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9135                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9136         } else {
9137                 // We should broadcast an HTLC transaction spending our funding transaction first
9138                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9139                 assert_eq!(spending_txn.len(), 2);
9140                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9141                 check_spends!(spending_txn[1], node_txn[0]);
9142                 // We should also generate a SpendableOutputs event with the to_self output (as its
9143                 // timelock is up).
9144                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9145                 assert_eq!(descriptor_spend_txn.len(), 1);
9146
9147                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9148                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9149                 // additional block built on top of the current chain.
9150                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9151                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9152                 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 }]);
9153                 check_added_monitors!(nodes[1], 1);
9154
9155                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9156                 assert!(updates.update_add_htlcs.is_empty());
9157                 assert!(updates.update_fulfill_htlcs.is_empty());
9158                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9159                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9160                 assert!(updates.update_fee.is_none());
9161                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9162                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9163                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9164         }
9165 }
9166
9167 #[test]
9168 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9169         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9170         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9171 }
9172
9173 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
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         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9180
9181         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9182                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9183         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9184
9185         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9186
9187         {
9188                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9189                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9190                 check_added_monitors!(nodes[0], 1);
9191                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9192                 assert_eq!(events.len(), 1);
9193                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9194                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9195                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9196         }
9197         expect_pending_htlcs_forwardable!(nodes[1]);
9198         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9199
9200         {
9201                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9202                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9203                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9204                 check_added_monitors!(nodes[0], 1);
9205                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9206                 assert_eq!(events.len(), 1);
9207                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9208                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9209                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9210                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9211                 // assume the second is a privacy attack (no longer particularly relevant
9212                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9213                 // the first HTLC delivered above.
9214         }
9215
9216         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9217         nodes[1].node.process_pending_htlc_forwards();
9218
9219         if test_for_second_fail_panic {
9220                 // Now we go fail back the first HTLC from the user end.
9221                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9222
9223                 let expected_destinations = vec![
9224                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9225                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9226                 ];
9227                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9228                 nodes[1].node.process_pending_htlc_forwards();
9229
9230                 check_added_monitors!(nodes[1], 1);
9231                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9232                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9233
9234                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9235                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9236                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9237
9238                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9239                 assert_eq!(failure_events.len(), 4);
9240                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9241                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9242                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9243                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9244         } else {
9245                 // Let the second HTLC fail and claim the first
9246                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9247                 nodes[1].node.process_pending_htlc_forwards();
9248
9249                 check_added_monitors!(nodes[1], 1);
9250                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9251                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9252                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9253
9254                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9255
9256                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9257         }
9258 }
9259
9260 #[test]
9261 fn test_dup_htlc_second_fail_panic() {
9262         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9263         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9264         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9265         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9266         do_test_dup_htlc_second_rejected(true);
9267 }
9268
9269 #[test]
9270 fn test_dup_htlc_second_rejected() {
9271         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9272         // simply reject the second HTLC but are still able to claim the first HTLC.
9273         do_test_dup_htlc_second_rejected(false);
9274 }
9275
9276 #[test]
9277 fn test_inconsistent_mpp_params() {
9278         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9279         // such HTLC and allow the second to stay.
9280         let chanmon_cfgs = create_chanmon_cfgs(4);
9281         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9282         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9283         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9284
9285         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9286         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9287         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9288         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9289
9290         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9291                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9292         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9293         assert_eq!(route.paths.len(), 2);
9294         route.paths.sort_by(|path_a, _| {
9295                 // Sort the path so that the path through nodes[1] comes first
9296                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9297                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9298         });
9299
9300         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9301
9302         let cur_height = nodes[0].best_block_info().1;
9303         let payment_id = PaymentId([42; 32]);
9304
9305         let session_privs = {
9306                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9307                 // ultimately have, just not right away.
9308                 let mut dup_route = route.clone();
9309                 dup_route.paths.push(route.paths[1].clone());
9310                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9311                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9312         };
9313         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9314                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9315                 &None, session_privs[0]).unwrap();
9316         check_added_monitors!(nodes[0], 1);
9317
9318         {
9319                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9320                 assert_eq!(events.len(), 1);
9321                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9322         }
9323         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9324
9325         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9326                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9327         check_added_monitors!(nodes[0], 1);
9328
9329         {
9330                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9331                 assert_eq!(events.len(), 1);
9332                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9333
9334                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9335                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9336
9337                 expect_pending_htlcs_forwardable!(nodes[2]);
9338                 check_added_monitors!(nodes[2], 1);
9339
9340                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9341                 assert_eq!(events.len(), 1);
9342                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9343
9344                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9345                 check_added_monitors!(nodes[3], 0);
9346                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9347
9348                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9349                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9350                 // post-payment_secrets) and fail back the new HTLC.
9351         }
9352         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9353         nodes[3].node.process_pending_htlc_forwards();
9354         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9355         nodes[3].node.process_pending_htlc_forwards();
9356
9357         check_added_monitors!(nodes[3], 1);
9358
9359         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9360         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9361         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9362
9363         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 }]);
9364         check_added_monitors!(nodes[2], 1);
9365
9366         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9367         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9368         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9369
9370         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9371
9372         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9373                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9374                 &None, session_privs[2]).unwrap();
9375         check_added_monitors!(nodes[0], 1);
9376
9377         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9378         assert_eq!(events.len(), 1);
9379         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9380
9381         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9382         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9383 }
9384
9385 #[test]
9386 fn test_keysend_payments_to_public_node() {
9387         let chanmon_cfgs = create_chanmon_cfgs(2);
9388         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9389         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9390         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9391
9392         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9393         let network_graph = nodes[0].network_graph.clone();
9394         let payer_pubkey = nodes[0].node.get_our_node_id();
9395         let payee_pubkey = nodes[1].node.get_our_node_id();
9396         let route_params = RouteParameters {
9397                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9398                 final_value_msat: 10000,
9399         };
9400         let scorer = test_utils::TestScorer::new();
9401         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9402         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9403
9404         let test_preimage = PaymentPreimage([42; 32]);
9405         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9406                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9407         check_added_monitors!(nodes[0], 1);
9408         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9409         assert_eq!(events.len(), 1);
9410         let event = events.pop().unwrap();
9411         let path = vec![&nodes[1]];
9412         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9413         claim_payment(&nodes[0], &path, test_preimage);
9414 }
9415
9416 #[test]
9417 fn test_keysend_payments_to_private_node() {
9418         let chanmon_cfgs = create_chanmon_cfgs(2);
9419         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9420         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9421         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9422
9423         let payer_pubkey = nodes[0].node.get_our_node_id();
9424         let payee_pubkey = nodes[1].node.get_our_node_id();
9425
9426         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9427         let route_params = RouteParameters {
9428                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9429                 final_value_msat: 10000,
9430         };
9431         let network_graph = nodes[0].network_graph.clone();
9432         let first_hops = nodes[0].node.list_usable_channels();
9433         let scorer = test_utils::TestScorer::new();
9434         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9435         let route = find_route(
9436                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9437                 nodes[0].logger, &scorer, &(), &random_seed_bytes
9438         ).unwrap();
9439
9440         let test_preimage = PaymentPreimage([42; 32]);
9441         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9442                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9443         check_added_monitors!(nodes[0], 1);
9444         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9445         assert_eq!(events.len(), 1);
9446         let event = events.pop().unwrap();
9447         let path = vec![&nodes[1]];
9448         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9449         claim_payment(&nodes[0], &path, test_preimage);
9450 }
9451
9452 #[test]
9453 fn test_double_partial_claim() {
9454         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9455         // time out, the sender resends only some of the MPP parts, then the user processes the
9456         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9457         // amount.
9458         let chanmon_cfgs = create_chanmon_cfgs(4);
9459         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9460         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9461         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9462
9463         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9464         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9465         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9466         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9467
9468         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9469         assert_eq!(route.paths.len(), 2);
9470         route.paths.sort_by(|path_a, _| {
9471                 // Sort the path so that the path through nodes[1] comes first
9472                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9473                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9474         });
9475
9476         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9477         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9478         // amount of time to respond to.
9479
9480         // Connect some blocks to time out the payment
9481         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9482         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9483
9484         let failed_destinations = vec![
9485                 HTLCDestination::FailedPayment { payment_hash },
9486                 HTLCDestination::FailedPayment { payment_hash },
9487         ];
9488         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9489
9490         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9491
9492         // nodes[1] now retries one of the two paths...
9493         nodes[0].node.send_payment_with_route(&route, payment_hash,
9494                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9495         check_added_monitors!(nodes[0], 2);
9496
9497         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9498         assert_eq!(events.len(), 2);
9499         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9500         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9501
9502         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9503         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9504         nodes[3].node.claim_funds(payment_preimage);
9505         check_added_monitors!(nodes[3], 0);
9506         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9507 }
9508
9509 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9510 #[derive(Clone, Copy, PartialEq)]
9511 enum ExposureEvent {
9512         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9513         AtHTLCForward,
9514         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9515         AtHTLCReception,
9516         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9517         AtUpdateFeeOutbound,
9518 }
9519
9520 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9521         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9522         // policy.
9523         //
9524         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9525         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9526         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9527         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9528         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9529         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9530         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9531         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9532
9533         let chanmon_cfgs = create_chanmon_cfgs(2);
9534         let mut config = test_default_channel_config();
9535         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9536                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9537                 // to get roughly the same initial value as the default setting when this test was
9538                 // originally written.
9539                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9540         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9543         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9544
9545         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9546         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9547         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9548         open_channel.max_accepted_htlcs = 60;
9549         if on_holder_tx {
9550                 open_channel.dust_limit_satoshis = 546;
9551         }
9552         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9553         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9554         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9555
9556         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9557
9558         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9559
9560         if on_holder_tx {
9561                 let mut node_0_per_peer_lock;
9562                 let mut node_0_peer_state_lock;
9563                 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);
9564                 chan.context.holder_dust_limit_satoshis = 546;
9565         }
9566
9567         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9568         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()));
9569         check_added_monitors!(nodes[1], 1);
9570         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9571
9572         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()));
9573         check_added_monitors!(nodes[0], 1);
9574         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9575
9576         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9577         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9578         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9579
9580         // Fetch a route in advance as we will be unable to once we're unable to send.
9581         let (mut route, payment_hash, _, payment_secret) =
9582                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9583
9584         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9585                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9586                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9587                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9588                 (chan.context.get_dust_buffer_feerate(None) as u64,
9589                 chan.context.get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9590         };
9591         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;
9592         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9593
9594         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;
9595         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9596
9597         let dust_htlc_on_counterparty_tx: u64 = 4;
9598         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9599
9600         if on_holder_tx {
9601                 if dust_outbound_balance {
9602                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9603                         // Outbound dust balance: 4372 sats
9604                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9605                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9606                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9607                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9608                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9609                         }
9610                 } else {
9611                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9612                         // Inbound dust balance: 4372 sats
9613                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9614                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9615                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9616                         }
9617                 }
9618         } else {
9619                 if dust_outbound_balance {
9620                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9621                         // Outbound dust balance: 5000 sats
9622                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9623                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9624                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9625                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9626                         }
9627                 } else {
9628                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9629                         // Inbound dust balance: 5000 sats
9630                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9631                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9632                         }
9633                 }
9634         }
9635
9636         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9637                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9638                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9639                 // With default dust exposure: 5000 sats
9640                 if on_holder_tx {
9641                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9642                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9643                                 ), true, APIError::ChannelUnavailable { .. }, {});
9644                 } else {
9645                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9646                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9647                                 ), true, APIError::ChannelUnavailable { .. }, {});
9648                 }
9649         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9650                 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 });
9651                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9652                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9653                 check_added_monitors!(nodes[1], 1);
9654                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9655                 assert_eq!(events.len(), 1);
9656                 let payment_event = SendEvent::from_event(events.remove(0));
9657                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9658                 // With default dust exposure: 5000 sats
9659                 if on_holder_tx {
9660                         // Outbound dust balance: 6399 sats
9661                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9662                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9663                         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);
9664                 } else {
9665                         // Outbound dust balance: 5200 sats
9666                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9667                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9668                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9669                                         max_dust_htlc_exposure_msat), 1);
9670                 }
9671         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9672                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9673                 // For the multiplier dust exposure limit, since it scales with feerate,
9674                 // we need to add a lot of HTLCs that will become dust at the new feerate
9675                 // to cross the threshold.
9676                 for _ in 0..20 {
9677                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9678                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9679                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9680                 }
9681                 {
9682                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9683                         *feerate_lock = *feerate_lock * 10;
9684                 }
9685                 nodes[0].node.timer_tick_occurred();
9686                 check_added_monitors!(nodes[0], 1);
9687                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9688         }
9689
9690         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9691         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9692         added_monitors.clear();
9693 }
9694
9695 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9696         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9697         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9698         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9699         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9700         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9701         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9702         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9703         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9704         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9705         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9706         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9707         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9708 }
9709
9710 #[test]
9711 fn test_max_dust_htlc_exposure() {
9712         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9713         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9714 }
9715
9716 #[test]
9717 fn test_non_final_funding_tx() {
9718         let chanmon_cfgs = create_chanmon_cfgs(2);
9719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9722
9723         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9724         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9725         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9726         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9727         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9728
9729         let best_height = nodes[0].node.best_block.read().unwrap().height();
9730
9731         let chan_id = *nodes[0].network_chan_count.borrow();
9732         let events = nodes[0].node.get_and_clear_pending_events();
9733         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9734         assert_eq!(events.len(), 1);
9735         let mut tx = match events[0] {
9736                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9737                         // Timelock the transaction _beyond_ the best client height + 1.
9738                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9739                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9740                         }]}
9741                 },
9742                 _ => panic!("Unexpected event"),
9743         };
9744         // Transaction should fail as it's evaluated as non-final for propagation.
9745         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9746                 Err(APIError::APIMisuseError { err }) => {
9747                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9748                 },
9749                 _ => panic!()
9750         }
9751
9752         // However, transaction should be accepted if it's in a +1 headroom from best block.
9753         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9754         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9755         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9756 }
9757
9758 #[test]
9759 fn accept_busted_but_better_fee() {
9760         // If a peer sends us a fee update that is too low, but higher than our previous channel
9761         // feerate, we should accept it. In the future we may want to consider closing the channel
9762         // later, but for now we only accept the update.
9763         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9766         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9767
9768         create_chan_between_nodes(&nodes[0], &nodes[1]);
9769
9770         // Set nodes[1] to expect 5,000 sat/kW.
9771         {
9772                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9773                 *feerate_lock = 5000;
9774         }
9775
9776         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9777         {
9778                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9779                 *feerate_lock = 1000;
9780         }
9781         nodes[0].node.timer_tick_occurred();
9782         check_added_monitors!(nodes[0], 1);
9783
9784         let events = nodes[0].node.get_and_clear_pending_msg_events();
9785         assert_eq!(events.len(), 1);
9786         match events[0] {
9787                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9788                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9789                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9790                 },
9791                 _ => panic!("Unexpected event"),
9792         };
9793
9794         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9795         // it.
9796         {
9797                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9798                 *feerate_lock = 2000;
9799         }
9800         nodes[0].node.timer_tick_occurred();
9801         check_added_monitors!(nodes[0], 1);
9802
9803         let events = nodes[0].node.get_and_clear_pending_msg_events();
9804         assert_eq!(events.len(), 1);
9805         match events[0] {
9806                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9807                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9808                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9809                 },
9810                 _ => panic!("Unexpected event"),
9811         };
9812
9813         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9814         // channel.
9815         {
9816                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9817                 *feerate_lock = 1000;
9818         }
9819         nodes[0].node.timer_tick_occurred();
9820         check_added_monitors!(nodes[0], 1);
9821
9822         let events = nodes[0].node.get_and_clear_pending_msg_events();
9823         assert_eq!(events.len(), 1);
9824         match events[0] {
9825                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9826                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9827                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9828                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9829                         check_closed_broadcast!(nodes[1], true);
9830                         check_added_monitors!(nodes[1], 1);
9831                 },
9832                 _ => panic!("Unexpected event"),
9833         };
9834 }
9835
9836 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9837         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9838         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9839         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9840         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9841         let min_final_cltv_expiry_delta = 120;
9842         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9843                 min_final_cltv_expiry_delta - 2 };
9844         let recv_value = 100_000;
9845
9846         create_chan_between_nodes(&nodes[0], &nodes[1]);
9847
9848         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9849         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9850                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9851                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9852                 (payment_hash, payment_preimage, payment_secret)
9853         } else {
9854                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9855                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9856         };
9857         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9858         nodes[0].node.send_payment_with_route(&route, payment_hash,
9859                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9860         check_added_monitors!(nodes[0], 1);
9861         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9862         assert_eq!(events.len(), 1);
9863         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9864         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9865         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9866         expect_pending_htlcs_forwardable!(nodes[1]);
9867
9868         if valid_delta {
9869                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9870                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9871
9872                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9873         } else {
9874                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9875
9876                 check_added_monitors!(nodes[1], 1);
9877
9878                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9879                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9880                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9881
9882                 expect_payment_failed!(nodes[0], payment_hash, true);
9883         }
9884 }
9885
9886 #[test]
9887 fn test_payment_with_custom_min_cltv_expiry_delta() {
9888         do_payment_with_custom_min_final_cltv_expiry(false, false);
9889         do_payment_with_custom_min_final_cltv_expiry(false, true);
9890         do_payment_with_custom_min_final_cltv_expiry(true, false);
9891         do_payment_with_custom_min_final_cltv_expiry(true, true);
9892 }
9893
9894 #[test]
9895 fn test_disconnects_peer_awaiting_response_ticks() {
9896         // Tests that nodes which are awaiting on a response critical for channel responsiveness
9897         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9898         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9899         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9900         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9901         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9902
9903         // Asserts a disconnect event is queued to the user.
9904         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9905                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9906                         if let MessageSendEvent::HandleError { action, .. } = event {
9907                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9908                                         Some(())
9909                                 } else {
9910                                         None
9911                                 }
9912                         } else {
9913                                 None
9914                         }
9915                 );
9916                 assert_eq!(disconnect_event.is_some(), should_disconnect);
9917         };
9918
9919         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9920         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9921         let check_disconnect = |node: &Node| {
9922                 // No disconnect without any timer ticks.
9923                 check_disconnect_event(node, false);
9924
9925                 // No disconnect with 1 timer tick less than required.
9926                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9927                         node.node.timer_tick_occurred();
9928                         check_disconnect_event(node, false);
9929                 }
9930
9931                 // Disconnect after reaching the required ticks.
9932                 node.node.timer_tick_occurred();
9933                 check_disconnect_event(node, true);
9934
9935                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9936                 node.node.timer_tick_occurred();
9937                 check_disconnect_event(node, true);
9938         };
9939
9940         create_chan_between_nodes(&nodes[0], &nodes[1]);
9941
9942         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9943         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9944         nodes[0].node.timer_tick_occurred();
9945         check_added_monitors!(&nodes[0], 1);
9946         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9947         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9948         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9949         check_added_monitors!(&nodes[1], 1);
9950
9951         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9952         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9953         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9954         check_added_monitors!(&nodes[0], 1);
9955         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9956         check_added_monitors(&nodes[0], 1);
9957
9958         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9959         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9960         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9961         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9962         check_disconnect(&nodes[1]);
9963
9964         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
9965         //
9966         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
9967         // final `RevokeAndACK` to Bob to complete it.
9968         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9969         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9970         let bob_init = msgs::Init {
9971                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
9972         };
9973         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
9974         let alice_init = msgs::Init {
9975                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9976         };
9977         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
9978
9979         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
9980         // received Bob's yet, so she should disconnect him after reaching
9981         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9982         let alice_channel_reestablish = get_event_msg!(
9983                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
9984         );
9985         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
9986         check_disconnect(&nodes[0]);
9987
9988         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
9989         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
9990                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
9991                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9992                         Some(msg.clone())
9993                 } else {
9994                         None
9995                 }
9996         ).unwrap();
9997         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
9998
9999         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10000         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10001                 nodes[0].node.timer_tick_occurred();
10002                 check_disconnect_event(&nodes[0], false);
10003         }
10004
10005         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10006         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10007         check_disconnect(&nodes[1]);
10008
10009         // Finally, have Bob process the last message.
10010         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10011         check_added_monitors(&nodes[1], 1);
10012
10013         // At this point, neither node should attempt to disconnect each other, since they aren't
10014         // waiting on any messages.
10015         for node in &nodes {
10016                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10017                         node.node.timer_tick_occurred();
10018                         check_disconnect_event(node, false);
10019                 }
10020         }
10021 }
10022
10023 #[test]
10024 fn test_remove_expired_outbound_unfunded_channels() {
10025         let chanmon_cfgs = create_chanmon_cfgs(2);
10026         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10027         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10028         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10029
10030         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10031         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10032         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10033         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10034         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10035
10036         let events = nodes[0].node.get_and_clear_pending_events();
10037         assert_eq!(events.len(), 1);
10038         match events[0] {
10039                 Event::FundingGenerationReady { .. } => (),
10040                 _ => panic!("Unexpected event"),
10041         };
10042
10043         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10044         let check_outbound_channel_existence = |should_exist: bool| {
10045                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10046                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10047                 assert_eq!(chan_lock.outbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10048         };
10049
10050         // Channel should exist without any timer ticks.
10051         check_outbound_channel_existence(true);
10052
10053         // Channel should exist with 1 timer tick less than required.
10054         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10055                 nodes[0].node.timer_tick_occurred();
10056                 check_outbound_channel_existence(true)
10057         }
10058
10059         // Remove channel after reaching the required ticks.
10060         nodes[0].node.timer_tick_occurred();
10061         check_outbound_channel_existence(false);
10062
10063         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
10064 }
10065
10066 #[test]
10067 fn test_remove_expired_inbound_unfunded_channels() {
10068         let chanmon_cfgs = create_chanmon_cfgs(2);
10069         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10070         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10071         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10072
10073         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10074         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10075         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10076         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10077         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10078
10079         let events = nodes[0].node.get_and_clear_pending_events();
10080         assert_eq!(events.len(), 1);
10081         match events[0] {
10082                 Event::FundingGenerationReady { .. } => (),
10083                 _ => panic!("Unexpected event"),
10084         };
10085
10086         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10087         let check_inbound_channel_existence = |should_exist: bool| {
10088                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10089                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10090                 assert_eq!(chan_lock.inbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10091         };
10092
10093         // Channel should exist without any timer ticks.
10094         check_inbound_channel_existence(true);
10095
10096         // Channel should exist with 1 timer tick less than required.
10097         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10098                 nodes[1].node.timer_tick_occurred();
10099                 check_inbound_channel_existence(true)
10100         }
10101
10102         // Remove channel after reaching the required ticks.
10103         nodes[1].node.timer_tick_occurred();
10104         check_inbound_channel_existence(false);
10105
10106         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
10107 }