Add channel_id to SpendableOutputs event
[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, 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                 [nodes[0].node.get_our_node_id()], channel_value);
768 }
769
770 #[test]
771 fn test_update_fee_with_fundee_update_add_htlc() {
772         let chanmon_cfgs = create_chanmon_cfgs(2);
773         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
774         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
775         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
776         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
777
778         // balancing
779         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
780
781         {
782                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
783                 *feerate_lock += 20;
784         }
785         nodes[0].node.timer_tick_occurred();
786         check_added_monitors!(nodes[0], 1);
787
788         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
789         assert_eq!(events_0.len(), 1);
790         let (update_msg, commitment_signed) = match events_0[0] {
791                         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 } } => {
792                         (update_fee.as_ref(), commitment_signed)
793                 },
794                 _ => panic!("Unexpected event"),
795         };
796         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
797         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
798         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799         check_added_monitors!(nodes[1], 1);
800
801         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
802
803         // nothing happens since node[1] is in AwaitingRemoteRevoke
804         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
805                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
806         {
807                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
808                 assert_eq!(added_monitors.len(), 0);
809                 added_monitors.clear();
810         }
811         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
812         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
813         // node[1] has nothing to do
814
815         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
816         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
817         check_added_monitors!(nodes[0], 1);
818
819         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
820         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
821         // No commitment_signed so get_event_msg's assert(len == 1) passes
822         check_added_monitors!(nodes[0], 1);
823         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
824         check_added_monitors!(nodes[1], 1);
825         // AwaitingRemoteRevoke ends here
826
827         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
828         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
829         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
830         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
831         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
832         assert_eq!(commitment_update.update_fee.is_none(), true);
833
834         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
835         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
836         check_added_monitors!(nodes[0], 1);
837         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
838
839         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
840         check_added_monitors!(nodes[1], 1);
841         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
842
843         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
844         check_added_monitors!(nodes[1], 1);
845         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
846         // No commitment_signed so get_event_msg's assert(len == 1) passes
847
848         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
849         check_added_monitors!(nodes[0], 1);
850         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
851
852         expect_pending_htlcs_forwardable!(nodes[0]);
853
854         let events = nodes[0].node.get_and_clear_pending_events();
855         assert_eq!(events.len(), 1);
856         match events[0] {
857                 Event::PaymentClaimable { .. } => { },
858                 _ => panic!("Unexpected event"),
859         };
860
861         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
862
863         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
864         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
865         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
866         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
867         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
868 }
869
870 #[test]
871 fn test_update_fee() {
872         let chanmon_cfgs = create_chanmon_cfgs(2);
873         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
874         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
875         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
876         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
877         let channel_id = chan.2;
878
879         // A                                        B
880         // (1) update_fee/commitment_signed      ->
881         //                                       <- (2) revoke_and_ack
882         //                                       .- send (3) commitment_signed
883         // (4) update_fee/commitment_signed      ->
884         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
885         //                                       <- (3) commitment_signed delivered
886         // send (6) revoke_and_ack               -.
887         //                                       <- (5) deliver revoke_and_ack
888         // (6) deliver revoke_and_ack            ->
889         //                                       .- send (7) commitment_signed in response to (4)
890         //                                       <- (7) deliver commitment_signed
891         // revoke_and_ack                        ->
892
893         // Create and deliver (1)...
894         let feerate;
895         {
896                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897                 feerate = *feerate_lock;
898                 *feerate_lock = feerate + 20;
899         }
900         nodes[0].node.timer_tick_occurred();
901         check_added_monitors!(nodes[0], 1);
902
903         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
904         assert_eq!(events_0.len(), 1);
905         let (update_msg, commitment_signed) = match events_0[0] {
906                         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 } } => {
907                         (update_fee.as_ref(), commitment_signed)
908                 },
909                 _ => panic!("Unexpected event"),
910         };
911         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
912
913         // Generate (2) and (3):
914         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
916         check_added_monitors!(nodes[1], 1);
917
918         // Deliver (2):
919         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
920         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
921         check_added_monitors!(nodes[0], 1);
922
923         // Create and deliver (4)...
924         {
925                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
926                 *feerate_lock = feerate + 30;
927         }
928         nodes[0].node.timer_tick_occurred();
929         check_added_monitors!(nodes[0], 1);
930         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
931         assert_eq!(events_0.len(), 1);
932         let (update_msg, commitment_signed) = match events_0[0] {
933                         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 } } => {
934                         (update_fee.as_ref(), commitment_signed)
935                 },
936                 _ => panic!("Unexpected event"),
937         };
938
939         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
940         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
941         check_added_monitors!(nodes[1], 1);
942         // ... creating (5)
943         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
944         // No commitment_signed so get_event_msg's assert(len == 1) passes
945
946         // Handle (3), creating (6):
947         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
948         check_added_monitors!(nodes[0], 1);
949         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950         // No commitment_signed so get_event_msg's assert(len == 1) passes
951
952         // Deliver (5):
953         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
954         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
955         check_added_monitors!(nodes[0], 1);
956
957         // Deliver (6), creating (7):
958         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
959         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
960         assert!(commitment_update.update_add_htlcs.is_empty());
961         assert!(commitment_update.update_fulfill_htlcs.is_empty());
962         assert!(commitment_update.update_fail_htlcs.is_empty());
963         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
964         assert!(commitment_update.update_fee.is_none());
965         check_added_monitors!(nodes[1], 1);
966
967         // Deliver (7)
968         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
969         check_added_monitors!(nodes[0], 1);
970         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
971         // No commitment_signed so get_event_msg's assert(len == 1) passes
972
973         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
974         check_added_monitors!(nodes[1], 1);
975         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
976
977         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
978         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
979         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
980         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
981         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
982 }
983
984 #[test]
985 fn fake_network_test() {
986         // Simple test which builds a network of ChannelManagers, connects them to each other, and
987         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
988         let chanmon_cfgs = create_chanmon_cfgs(4);
989         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
990         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
991         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
992
993         // Create some initial channels
994         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
995         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
996         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
997
998         // Rebalance the network a bit by relaying one payment through all the channels...
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         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1003
1004         // Send some more payments
1005         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1006         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1007         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1008
1009         // Test failure packets
1010         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1011         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1012
1013         // Add a new channel that skips 3
1014         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1015
1016         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1017         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1023
1024         // Do some rebalance loop payments, simultaneously
1025         let mut hops = Vec::with_capacity(3);
1026         hops.push(RouteHop {
1027                 pubkey: nodes[2].node.get_our_node_id(),
1028                 node_features: NodeFeatures::empty(),
1029                 short_channel_id: chan_2.0.contents.short_channel_id,
1030                 channel_features: ChannelFeatures::empty(),
1031                 fee_msat: 0,
1032                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1033         });
1034         hops.push(RouteHop {
1035                 pubkey: nodes[3].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_3.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1041         });
1042         hops.push(RouteHop {
1043                 pubkey: nodes[1].node.get_our_node_id(),
1044                 node_features: nodes[1].node.node_features(),
1045                 short_channel_id: chan_4.0.contents.short_channel_id,
1046                 channel_features: nodes[1].node.channel_features(),
1047                 fee_msat: 1000000,
1048                 cltv_expiry_delta: TEST_FINAL_CLTV,
1049         });
1050         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;
1051         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;
1052         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;
1053
1054         let mut hops = Vec::with_capacity(3);
1055         hops.push(RouteHop {
1056                 pubkey: nodes[3].node.get_our_node_id(),
1057                 node_features: NodeFeatures::empty(),
1058                 short_channel_id: chan_4.0.contents.short_channel_id,
1059                 channel_features: ChannelFeatures::empty(),
1060                 fee_msat: 0,
1061                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1062         });
1063         hops.push(RouteHop {
1064                 pubkey: nodes[2].node.get_our_node_id(),
1065                 node_features: NodeFeatures::empty(),
1066                 short_channel_id: chan_3.0.contents.short_channel_id,
1067                 channel_features: ChannelFeatures::empty(),
1068                 fee_msat: 0,
1069                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1070         });
1071         hops.push(RouteHop {
1072                 pubkey: nodes[1].node.get_our_node_id(),
1073                 node_features: nodes[1].node.node_features(),
1074                 short_channel_id: chan_2.0.contents.short_channel_id,
1075                 channel_features: nodes[1].node.channel_features(),
1076                 fee_msat: 1000000,
1077                 cltv_expiry_delta: TEST_FINAL_CLTV,
1078         });
1079         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;
1080         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;
1081         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;
1082
1083         // Claim the rebalances...
1084         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1085         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1086
1087         // Close down the channels...
1088         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1089         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1090         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1091         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1092         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1093         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1094         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1095         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1096         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1097         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1098         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1099         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1100 }
1101
1102 #[test]
1103 fn holding_cell_htlc_counting() {
1104         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1105         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1106         // commitment dance rounds.
1107         let chanmon_cfgs = create_chanmon_cfgs(3);
1108         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1109         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1110         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1111         create_announced_chan_between_nodes(&nodes, 0, 1);
1112         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1113
1114         // Fetch a route in advance as we will be unable to once we're unable to send.
1115         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1116
1117         let mut payments = Vec::new();
1118         for _ in 0..50 {
1119                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1120                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1121                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1122                 payments.push((payment_preimage, payment_hash));
1123         }
1124         check_added_monitors!(nodes[1], 1);
1125
1126         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1127         assert_eq!(events.len(), 1);
1128         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1129         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1130
1131         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1132         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1133         // another HTLC.
1134         {
1135                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1136                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1137                         ), true, APIError::ChannelUnavailable { .. }, {});
1138                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1139         }
1140
1141         // This should also be true if we try to forward a payment.
1142         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1143         {
1144                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1145                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1146                 check_added_monitors!(nodes[0], 1);
1147         }
1148
1149         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1150         assert_eq!(events.len(), 1);
1151         let payment_event = SendEvent::from_event(events.pop().unwrap());
1152         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1153
1154         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1155         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1156         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1157         // fails), the second will process the resulting failure and fail the HTLC backward.
1158         expect_pending_htlcs_forwardable!(nodes[1]);
1159         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 }]);
1160         check_added_monitors!(nodes[1], 1);
1161
1162         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1163         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1164         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1165
1166         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1167
1168         // Now forward all the pending HTLCs and claim them back
1169         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1170         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1171         check_added_monitors!(nodes[2], 1);
1172
1173         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1174         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1175         check_added_monitors!(nodes[1], 1);
1176         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1177
1178         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1179         check_added_monitors!(nodes[1], 1);
1180         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1181
1182         for ref update in as_updates.update_add_htlcs.iter() {
1183                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1184         }
1185         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1186         check_added_monitors!(nodes[2], 1);
1187         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1188         check_added_monitors!(nodes[2], 1);
1189         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1190
1191         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1192         check_added_monitors!(nodes[1], 1);
1193         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1194         check_added_monitors!(nodes[1], 1);
1195         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1196
1197         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1198         check_added_monitors!(nodes[2], 1);
1199
1200         expect_pending_htlcs_forwardable!(nodes[2]);
1201
1202         let events = nodes[2].node.get_and_clear_pending_events();
1203         assert_eq!(events.len(), payments.len());
1204         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1205                 match event {
1206                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1207                                 assert_eq!(*payment_hash, *hash);
1208                         },
1209                         _ => panic!("Unexpected event"),
1210                 };
1211         }
1212
1213         for (preimage, _) in payments.drain(..) {
1214                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1215         }
1216
1217         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1218 }
1219
1220 #[test]
1221 fn duplicate_htlc_test() {
1222         // Test that we accept duplicate payment_hash HTLCs across the network and that
1223         // claiming/failing them are all separate and don't affect each other
1224         let chanmon_cfgs = create_chanmon_cfgs(6);
1225         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1226         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1227         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1228
1229         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1230         create_announced_chan_between_nodes(&nodes, 0, 3);
1231         create_announced_chan_between_nodes(&nodes, 1, 3);
1232         create_announced_chan_between_nodes(&nodes, 2, 3);
1233         create_announced_chan_between_nodes(&nodes, 3, 4);
1234         create_announced_chan_between_nodes(&nodes, 3, 5);
1235
1236         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1237
1238         *nodes[0].network_payment_count.borrow_mut() -= 1;
1239         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1240
1241         *nodes[0].network_payment_count.borrow_mut() -= 1;
1242         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1243
1244         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1245         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1246         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1247 }
1248
1249 #[test]
1250 fn test_duplicate_htlc_different_direction_onchain() {
1251         // Test that ChannelMonitor doesn't generate 2 preimage txn
1252         // when we have 2 HTLCs with same preimage that go across a node
1253         // in opposite directions, even with the same payment secret.
1254         let chanmon_cfgs = create_chanmon_cfgs(2);
1255         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1256         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1257         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1258
1259         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1260
1261         // balancing
1262         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1263
1264         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1265
1266         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1267         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1268         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1269
1270         // Provide preimage to node 0 by claiming payment
1271         nodes[0].node.claim_funds(payment_preimage);
1272         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1273         check_added_monitors!(nodes[0], 1);
1274
1275         // Broadcast node 1 commitment txn
1276         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1277
1278         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1279         let mut has_both_htlcs = 0; // check htlcs match ones committed
1280         for outp in remote_txn[0].output.iter() {
1281                 if outp.value == 800_000 / 1000 {
1282                         has_both_htlcs += 1;
1283                 } else if outp.value == 900_000 / 1000 {
1284                         has_both_htlcs += 1;
1285                 }
1286         }
1287         assert_eq!(has_both_htlcs, 2);
1288
1289         mine_transaction(&nodes[0], &remote_txn[0]);
1290         check_added_monitors!(nodes[0], 1);
1291         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1292         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1293
1294         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1295         assert_eq!(claim_txn.len(), 3);
1296
1297         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1298         check_spends!(claim_txn[1], remote_txn[0]);
1299         check_spends!(claim_txn[2], remote_txn[0]);
1300         let preimage_tx = &claim_txn[0];
1301         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1302                 (&claim_txn[1], &claim_txn[2])
1303         } else {
1304                 (&claim_txn[2], &claim_txn[1])
1305         };
1306
1307         assert_eq!(preimage_tx.input.len(), 1);
1308         assert_eq!(preimage_bump_tx.input.len(), 1);
1309
1310         assert_eq!(preimage_tx.input.len(), 1);
1311         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1312         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1313
1314         assert_eq!(timeout_tx.input.len(), 1);
1315         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1316         check_spends!(timeout_tx, remote_txn[0]);
1317         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1318
1319         let events = nodes[0].node.get_and_clear_pending_msg_events();
1320         assert_eq!(events.len(), 3);
1321         for e in events {
1322                 match e {
1323                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1324                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1325                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1326                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1327                         },
1328                         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, .. } } => {
1329                                 assert!(update_add_htlcs.is_empty());
1330                                 assert!(update_fail_htlcs.is_empty());
1331                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1332                                 assert!(update_fail_malformed_htlcs.is_empty());
1333                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1334                         },
1335                         _ => panic!("Unexpected event"),
1336                 }
1337         }
1338 }
1339
1340 #[test]
1341 fn test_basic_channel_reserve() {
1342         let chanmon_cfgs = create_chanmon_cfgs(2);
1343         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1344         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1345         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1346         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1347
1348         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1349         let channel_reserve = chan_stat.channel_reserve_msat;
1350
1351         // The 2* and +1 are for the fee spike reserve.
1352         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));
1353         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1354         let (mut route, our_payment_hash, _, our_payment_secret) =
1355                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1356         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1357         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1358                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1359         match err {
1360                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1361                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1362                         else { panic!("Unexpected error variant"); }
1363                 },
1364                 _ => panic!("Unexpected error variant"),
1365         }
1366         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1367
1368         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1369 }
1370
1371 #[test]
1372 fn test_fee_spike_violation_fails_htlc() {
1373         let chanmon_cfgs = create_chanmon_cfgs(2);
1374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1376         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1377         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1378
1379         let (mut route, payment_hash, _, payment_secret) =
1380                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1381         route.paths[0].hops[0].fee_msat += 1;
1382         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1383         let secp_ctx = Secp256k1::new();
1384         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1385
1386         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1387
1388         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1389         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1390                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1391         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1392         let msg = msgs::UpdateAddHTLC {
1393                 channel_id: chan.2,
1394                 htlc_id: 0,
1395                 amount_msat: htlc_msat,
1396                 payment_hash: payment_hash,
1397                 cltv_expiry: htlc_cltv,
1398                 onion_routing_packet: onion_packet,
1399                 skimmed_fee_msat: None,
1400         };
1401
1402         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1403
1404         // Now manually create the commitment_signed message corresponding to the update_add
1405         // nodes[0] just sent. In the code for construction of this message, "local" refers
1406         // to the sender of the message, and "remote" refers to the receiver.
1407
1408         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1409
1410         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1411
1412         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1413         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1414         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1415                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1416                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1417                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1418                 let chan_signer = local_chan.get_signer();
1419                 // Make the signer believe we validated another commitment, so we can release the secret
1420                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1421
1422                 let pubkeys = chan_signer.pubkeys();
1423                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1424                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1425                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1426                  chan_signer.pubkeys().funding_pubkey)
1427         };
1428         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1429                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1430                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1431                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1432                 let chan_signer = remote_chan.get_signer();
1433                 let pubkeys = chan_signer.pubkeys();
1434                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1435                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1436                  chan_signer.pubkeys().funding_pubkey)
1437         };
1438
1439         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1440         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1441                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1442
1443         // Build the remote commitment transaction so we can sign it, and then later use the
1444         // signature for the commitment_signed message.
1445         let local_chan_balance = 1313;
1446
1447         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1448                 offered: false,
1449                 amount_msat: 3460001,
1450                 cltv_expiry: htlc_cltv,
1451                 payment_hash,
1452                 transaction_output_index: Some(1),
1453         };
1454
1455         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1456
1457         let res = {
1458                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1459                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1460                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1461                 let local_chan_signer = local_chan.get_signer();
1462                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1463                         commitment_number,
1464                         95000,
1465                         local_chan_balance,
1466                         local_funding, remote_funding,
1467                         commit_tx_keys.clone(),
1468                         feerate_per_kw,
1469                         &mut vec![(accepted_htlc_info, ())],
1470                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1471                 );
1472                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1473         };
1474
1475         let commit_signed_msg = msgs::CommitmentSigned {
1476                 channel_id: chan.2,
1477                 signature: res.0,
1478                 htlc_signatures: res.1,
1479                 #[cfg(taproot)]
1480                 partial_signature_with_nonce: None,
1481         };
1482
1483         // Send the commitment_signed message to the nodes[1].
1484         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1485         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1486
1487         // Send the RAA to nodes[1].
1488         let raa_msg = msgs::RevokeAndACK {
1489                 channel_id: chan.2,
1490                 per_commitment_secret: local_secret,
1491                 next_per_commitment_point: next_local_point,
1492                 #[cfg(taproot)]
1493                 next_local_nonce: None,
1494         };
1495         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1496
1497         let events = nodes[1].node.get_and_clear_pending_msg_events();
1498         assert_eq!(events.len(), 1);
1499         // Make sure the HTLC failed in the way we expect.
1500         match events[0] {
1501                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1502                         assert_eq!(update_fail_htlcs.len(), 1);
1503                         update_fail_htlcs[0].clone()
1504                 },
1505                 _ => panic!("Unexpected event"),
1506         };
1507         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1508                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1509
1510         check_added_monitors!(nodes[1], 2);
1511 }
1512
1513 #[test]
1514 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1515         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1516         // Set the fee rate for the channel very high, to the point where the fundee
1517         // sending any above-dust amount would result in a channel reserve violation.
1518         // In this test we check that we would be prevented from sending an HTLC in
1519         // this situation.
1520         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1521         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1522         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1523         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1524         let default_config = UserConfig::default();
1525         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1526
1527         let mut push_amt = 100_000_000;
1528         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1529
1530         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1531
1532         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1533
1534         // Fetch a route in advance as we will be unable to once we're unable to send.
1535         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1536         // Sending exactly enough to hit the reserve amount should be accepted
1537         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1538                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1539         }
1540
1541         // However one more HTLC should be significantly over the reserve amount and fail.
1542         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1543                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1544                 ), true, APIError::ChannelUnavailable { .. }, {});
1545         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1546 }
1547
1548 #[test]
1549 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1550         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1551         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1552         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1553         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1554         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1555         let default_config = UserConfig::default();
1556         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1557
1558         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1559         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1560         // transaction fee with 0 HTLCs (183 sats)).
1561         let mut push_amt = 100_000_000;
1562         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1563         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1564         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1565
1566         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1567         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1568                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1569         }
1570
1571         let (mut route, payment_hash, _, payment_secret) =
1572                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1573         route.paths[0].hops[0].fee_msat = 700_000;
1574         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1575         let secp_ctx = Secp256k1::new();
1576         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1577         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1578         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1579         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1580                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1581         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1582         let msg = msgs::UpdateAddHTLC {
1583                 channel_id: chan.2,
1584                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1585                 amount_msat: htlc_msat,
1586                 payment_hash: payment_hash,
1587                 cltv_expiry: htlc_cltv,
1588                 onion_routing_packet: onion_packet,
1589                 skimmed_fee_msat: None,
1590         };
1591
1592         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1593         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1594         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);
1595         assert_eq!(nodes[0].node.list_channels().len(), 0);
1596         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1597         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1598         check_added_monitors!(nodes[0], 1);
1599         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() },
1600                 [nodes[1].node.get_our_node_id()], 100000);
1601 }
1602
1603 #[test]
1604 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1605         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1606         // calculating our commitment transaction fee (this was previously broken).
1607         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1608         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1609
1610         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1611         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1612         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1613         let default_config = UserConfig::default();
1614         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1615
1616         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1617         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1618         // transaction fee with 0 HTLCs (183 sats)).
1619         let mut push_amt = 100_000_000;
1620         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1621         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1622         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1623
1624         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1625                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1626         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1627         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1628         // commitment transaction fee.
1629         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1630
1631         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1632         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1633                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1634         }
1635
1636         // One more than the dust amt should fail, however.
1637         let (mut route, our_payment_hash, _, our_payment_secret) =
1638                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1639         route.paths[0].hops[0].fee_msat += 1;
1640         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1641                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1642                 ), true, APIError::ChannelUnavailable { .. }, {});
1643 }
1644
1645 #[test]
1646 fn test_chan_init_feerate_unaffordability() {
1647         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1648         // channel reserve and feerate requirements.
1649         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1650         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1653         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1654         let default_config = UserConfig::default();
1655         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1656
1657         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1658         // HTLC.
1659         let mut push_amt = 100_000_000;
1660         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1661         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1662                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1663
1664         // During open, we don't have a "counterparty channel reserve" to check against, so that
1665         // requirement only comes into play on the open_channel handling side.
1666         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1667         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1668         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1669         open_channel_msg.push_msat += 1;
1670         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1671
1672         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1673         assert_eq!(msg_events.len(), 1);
1674         match msg_events[0] {
1675                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1676                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1677                 },
1678                 _ => panic!("Unexpected event"),
1679         }
1680 }
1681
1682 #[test]
1683 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1684         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1685         // calculating our counterparty's commitment transaction fee (this was previously broken).
1686         let chanmon_cfgs = create_chanmon_cfgs(2);
1687         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1688         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1689         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1690         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1691
1692         let payment_amt = 46000; // Dust amount
1693         // In the previous code, these first four payments would succeed.
1694         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1697         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698
1699         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1704         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1705
1706         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1707         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1708         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1709         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1710 }
1711
1712 #[test]
1713 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1714         let chanmon_cfgs = create_chanmon_cfgs(3);
1715         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1716         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1717         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1718         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1719         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1720
1721         let feemsat = 239;
1722         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1723         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1724         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1725         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1726
1727         // Add a 2* and +1 for the fee spike reserve.
1728         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1729         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;
1730         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1731
1732         // Add a pending HTLC.
1733         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1734         let payment_event_1 = {
1735                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1736                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1737                 check_added_monitors!(nodes[0], 1);
1738
1739                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1740                 assert_eq!(events.len(), 1);
1741                 SendEvent::from_event(events.remove(0))
1742         };
1743         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1744
1745         // Attempt to trigger a channel reserve violation --> payment failure.
1746         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1747         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;
1748         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1749         let mut route_2 = route_1.clone();
1750         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1751
1752         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1753         let secp_ctx = Secp256k1::new();
1754         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1755         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1756         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1757         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1758                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1759         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1760         let msg = msgs::UpdateAddHTLC {
1761                 channel_id: chan.2,
1762                 htlc_id: 1,
1763                 amount_msat: htlc_msat + 1,
1764                 payment_hash: our_payment_hash_1,
1765                 cltv_expiry: htlc_cltv,
1766                 onion_routing_packet: onion_packet,
1767                 skimmed_fee_msat: None,
1768         };
1769
1770         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1771         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1772         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1773         assert_eq!(nodes[1].node.list_channels().len(), 1);
1774         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1775         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1776         check_added_monitors!(nodes[1], 1);
1777         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1778                 [nodes[0].node.get_our_node_id()], 100000);
1779 }
1780
1781 #[test]
1782 fn test_inbound_outbound_capacity_is_not_zero() {
1783         let chanmon_cfgs = create_chanmon_cfgs(2);
1784         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1785         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1786         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1787         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1788         let channels0 = node_chanmgrs[0].list_channels();
1789         let channels1 = node_chanmgrs[1].list_channels();
1790         let default_config = UserConfig::default();
1791         assert_eq!(channels0.len(), 1);
1792         assert_eq!(channels1.len(), 1);
1793
1794         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1795         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1796         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1797
1798         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1799         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1800 }
1801
1802 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1803         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1804 }
1805
1806 #[test]
1807 fn test_channel_reserve_holding_cell_htlcs() {
1808         let chanmon_cfgs = create_chanmon_cfgs(3);
1809         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1810         // When this test was written, the default base fee floated based on the HTLC count.
1811         // It is now fixed, so we simply set the fee to the expected value here.
1812         let mut config = test_default_channel_config();
1813         config.channel_config.forwarding_fee_base_msat = 239;
1814         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1815         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1816         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1817         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1818
1819         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1820         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1821
1822         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1823         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1824
1825         macro_rules! expect_forward {
1826                 ($node: expr) => {{
1827                         let mut events = $node.node.get_and_clear_pending_msg_events();
1828                         assert_eq!(events.len(), 1);
1829                         check_added_monitors!($node, 1);
1830                         let payment_event = SendEvent::from_event(events.remove(0));
1831                         payment_event
1832                 }}
1833         }
1834
1835         let feemsat = 239; // set above
1836         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1837         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1838         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1839
1840         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1841
1842         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1843         {
1844                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1845                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1846                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1847                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1848                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1849
1850                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1851                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1852                         ), true, APIError::ChannelUnavailable { .. }, {});
1853                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1854         }
1855
1856         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1857         // nodes[0]'s wealth
1858         loop {
1859                 let amt_msat = recv_value_0 + total_fee_msat;
1860                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1861                 // Also, ensure that each payment has enough to be over the dust limit to
1862                 // ensure it'll be included in each commit tx fee calculation.
1863                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1864                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1865                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1866                         break;
1867                 }
1868
1869                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1870                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1871                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1872                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1873                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1874
1875                 let (stat01_, stat11_, stat12_, stat22_) = (
1876                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1877                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1878                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1879                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1880                 );
1881
1882                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1883                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1884                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1885                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1886                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1887         }
1888
1889         // adding pending output.
1890         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1891         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1892         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1893         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1894         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1895         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1896         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1897         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1898         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1899         // policy.
1900         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1901         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1902         let amt_msat_1 = recv_value_1 + total_fee_msat;
1903
1904         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);
1905         let payment_event_1 = {
1906                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1907                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1908                 check_added_monitors!(nodes[0], 1);
1909
1910                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1911                 assert_eq!(events.len(), 1);
1912                 SendEvent::from_event(events.remove(0))
1913         };
1914         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1915
1916         // channel reserve test with htlc pending output > 0
1917         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1918         {
1919                 let mut route = route_1.clone();
1920                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1921                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1922                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1923                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1924                         ), true, APIError::ChannelUnavailable { .. }, {});
1925                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1926         }
1927
1928         // split the rest to test holding cell
1929         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1930         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1931         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1932         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1933         {
1934                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1935                 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);
1936         }
1937
1938         // now see if they go through on both sides
1939         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);
1940         // but this will stuck in the holding cell
1941         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1942                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1943         check_added_monitors!(nodes[0], 0);
1944         let events = nodes[0].node.get_and_clear_pending_events();
1945         assert_eq!(events.len(), 0);
1946
1947         // test with outbound holding cell amount > 0
1948         {
1949                 let (mut route, our_payment_hash, _, our_payment_secret) =
1950                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1951                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1952                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1953                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1954                         ), true, APIError::ChannelUnavailable { .. }, {});
1955                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1956         }
1957
1958         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);
1959         // this will also stuck in the holding cell
1960         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1961                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1962         check_added_monitors!(nodes[0], 0);
1963         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1964         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1965
1966         // flush the pending htlc
1967         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1968         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1969         check_added_monitors!(nodes[1], 1);
1970
1971         // the pending htlc should be promoted to committed
1972         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1973         check_added_monitors!(nodes[0], 1);
1974         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1975
1976         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1977         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1978         // No commitment_signed so get_event_msg's assert(len == 1) passes
1979         check_added_monitors!(nodes[0], 1);
1980
1981         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1982         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1983         check_added_monitors!(nodes[1], 1);
1984
1985         expect_pending_htlcs_forwardable!(nodes[1]);
1986
1987         let ref payment_event_11 = expect_forward!(nodes[1]);
1988         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1989         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1990
1991         expect_pending_htlcs_forwardable!(nodes[2]);
1992         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1993
1994         // flush the htlcs in the holding cell
1995         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1996         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1997         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1998         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1999         expect_pending_htlcs_forwardable!(nodes[1]);
2000
2001         let ref payment_event_3 = expect_forward!(nodes[1]);
2002         assert_eq!(payment_event_3.msgs.len(), 2);
2003         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2004         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2005
2006         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2007         expect_pending_htlcs_forwardable!(nodes[2]);
2008
2009         let events = nodes[2].node.get_and_clear_pending_events();
2010         assert_eq!(events.len(), 2);
2011         match events[0] {
2012                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2013                         assert_eq!(our_payment_hash_21, *payment_hash);
2014                         assert_eq!(recv_value_21, amount_msat);
2015                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2016                         assert_eq!(via_channel_id, Some(chan_2.2));
2017                         match &purpose {
2018                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2019                                         assert!(payment_preimage.is_none());
2020                                         assert_eq!(our_payment_secret_21, *payment_secret);
2021                                 },
2022                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2023                         }
2024                 },
2025                 _ => panic!("Unexpected event"),
2026         }
2027         match events[1] {
2028                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2029                         assert_eq!(our_payment_hash_22, *payment_hash);
2030                         assert_eq!(recv_value_22, amount_msat);
2031                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2032                         assert_eq!(via_channel_id, Some(chan_2.2));
2033                         match &purpose {
2034                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2035                                         assert!(payment_preimage.is_none());
2036                                         assert_eq!(our_payment_secret_22, *payment_secret);
2037                                 },
2038                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2039                         }
2040                 },
2041                 _ => panic!("Unexpected event"),
2042         }
2043
2044         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2045         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2046         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2047
2048         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2049         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2050         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2051
2052         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2053         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);
2054         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2055         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2056         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2057
2058         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2059         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2060 }
2061
2062 #[test]
2063 fn channel_reserve_in_flight_removes() {
2064         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2065         // can send to its counterparty, but due to update ordering, the other side may not yet have
2066         // considered those HTLCs fully removed.
2067         // This tests that we don't count HTLCs which will not be included in the next remote
2068         // commitment transaction towards the reserve value (as it implies no commitment transaction
2069         // will be generated which violates the remote reserve value).
2070         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2071         // To test this we:
2072         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2073         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2074         //    you only consider the value of the first HTLC, it may not),
2075         //  * start routing a third HTLC from A to B,
2076         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2077         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2078         //  * deliver the first fulfill from B
2079         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2080         //    claim,
2081         //  * deliver A's response CS and RAA.
2082         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2083         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2084         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2085         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2086         let chanmon_cfgs = create_chanmon_cfgs(2);
2087         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2088         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2089         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2090         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2091
2092         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2093         // Route the first two HTLCs.
2094         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2095         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2096         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2097
2098         // Start routing the third HTLC (this is just used to get everyone in the right state).
2099         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2100         let send_1 = {
2101                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2102                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2103                 check_added_monitors!(nodes[0], 1);
2104                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2105                 assert_eq!(events.len(), 1);
2106                 SendEvent::from_event(events.remove(0))
2107         };
2108
2109         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2110         // initial fulfill/CS.
2111         nodes[1].node.claim_funds(payment_preimage_1);
2112         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2113         check_added_monitors!(nodes[1], 1);
2114         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2115
2116         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2117         // remove the second HTLC when we send the HTLC back from B to A.
2118         nodes[1].node.claim_funds(payment_preimage_2);
2119         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2120         check_added_monitors!(nodes[1], 1);
2121         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2122
2123         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2124         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2125         check_added_monitors!(nodes[0], 1);
2126         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2127         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2128
2129         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2130         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2131         check_added_monitors!(nodes[1], 1);
2132         // B is already AwaitingRAA, so cant generate a CS here
2133         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2134
2135         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2136         check_added_monitors!(nodes[1], 1);
2137         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2138
2139         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2140         check_added_monitors!(nodes[0], 1);
2141         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2142
2143         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144         check_added_monitors!(nodes[1], 1);
2145         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146
2147         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2148         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2149         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2150         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2151         // on-chain as necessary).
2152         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2153         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2154         check_added_monitors!(nodes[0], 1);
2155         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2156         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2157
2158         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2159         check_added_monitors!(nodes[1], 1);
2160         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2161
2162         expect_pending_htlcs_forwardable!(nodes[1]);
2163         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2164
2165         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2166         // resolve the second HTLC from A's point of view.
2167         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2168         check_added_monitors!(nodes[0], 1);
2169         expect_payment_path_successful!(nodes[0]);
2170         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2171
2172         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2173         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2174         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2175         let send_2 = {
2176                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2177                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2178                 check_added_monitors!(nodes[1], 1);
2179                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2180                 assert_eq!(events.len(), 1);
2181                 SendEvent::from_event(events.remove(0))
2182         };
2183
2184         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2185         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2186         check_added_monitors!(nodes[0], 1);
2187         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2188
2189         // Now just resolve all the outstanding messages/HTLCs for completeness...
2190
2191         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2192         check_added_monitors!(nodes[1], 1);
2193         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2194
2195         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2196         check_added_monitors!(nodes[1], 1);
2197
2198         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2199         check_added_monitors!(nodes[0], 1);
2200         expect_payment_path_successful!(nodes[0]);
2201         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2202
2203         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2204         check_added_monitors!(nodes[1], 1);
2205         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2206
2207         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2208         check_added_monitors!(nodes[0], 1);
2209
2210         expect_pending_htlcs_forwardable!(nodes[0]);
2211         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2212
2213         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2214         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2215 }
2216
2217 #[test]
2218 fn channel_monitor_network_test() {
2219         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2220         // tests that ChannelMonitor is able to recover from various states.
2221         let chanmon_cfgs = create_chanmon_cfgs(5);
2222         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2223         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2224         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2225
2226         // Create some initial channels
2227         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2228         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2229         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2230         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2231
2232         // Make sure all nodes are at the same starting height
2233         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2234         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2235         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2236         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2237         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2238
2239         // Rebalance the network a bit by relaying one payment through all the channels...
2240         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2241         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2242         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2243         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2244
2245         // Simple case with no pending HTLCs:
2246         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2247         check_added_monitors!(nodes[1], 1);
2248         check_closed_broadcast!(nodes[1], true);
2249         {
2250                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2251                 assert_eq!(node_txn.len(), 1);
2252                 mine_transaction(&nodes[0], &node_txn[0]);
2253                 check_added_monitors!(nodes[0], 1);
2254                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2255         }
2256         check_closed_broadcast!(nodes[0], true);
2257         assert_eq!(nodes[0].node.list_channels().len(), 0);
2258         assert_eq!(nodes[1].node.list_channels().len(), 1);
2259         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2260         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2261
2262         // One pending HTLC is discarded by the force-close:
2263         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2264
2265         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2266         // broadcasted until we reach the timelock time).
2267         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2268         check_closed_broadcast!(nodes[1], true);
2269         check_added_monitors!(nodes[1], 1);
2270         {
2271                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2272                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2273                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2274                 mine_transaction(&nodes[2], &node_txn[0]);
2275                 check_added_monitors!(nodes[2], 1);
2276                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2277         }
2278         check_closed_broadcast!(nodes[2], true);
2279         assert_eq!(nodes[1].node.list_channels().len(), 0);
2280         assert_eq!(nodes[2].node.list_channels().len(), 1);
2281         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2282         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2283
2284         macro_rules! claim_funds {
2285                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2286                         {
2287                                 $node.node.claim_funds($preimage);
2288                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2289                                 check_added_monitors!($node, 1);
2290
2291                                 let events = $node.node.get_and_clear_pending_msg_events();
2292                                 assert_eq!(events.len(), 1);
2293                                 match events[0] {
2294                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2295                                                 assert!(update_add_htlcs.is_empty());
2296                                                 assert!(update_fail_htlcs.is_empty());
2297                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2298                                         },
2299                                         _ => panic!("Unexpected event"),
2300                                 };
2301                         }
2302                 }
2303         }
2304
2305         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2306         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2307         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2308         check_added_monitors!(nodes[2], 1);
2309         check_closed_broadcast!(nodes[2], true);
2310         let node2_commitment_txid;
2311         {
2312                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2313                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2314                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2315                 node2_commitment_txid = node_txn[0].txid();
2316
2317                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2318                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2319                 mine_transaction(&nodes[3], &node_txn[0]);
2320                 check_added_monitors!(nodes[3], 1);
2321                 check_preimage_claim(&nodes[3], &node_txn);
2322         }
2323         check_closed_broadcast!(nodes[3], true);
2324         assert_eq!(nodes[2].node.list_channels().len(), 0);
2325         assert_eq!(nodes[3].node.list_channels().len(), 1);
2326         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2327         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2328
2329         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2330         // confusing us in the following tests.
2331         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2332
2333         // One pending HTLC to time out:
2334         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2335         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2336         // buffer space).
2337
2338         let (close_chan_update_1, close_chan_update_2) = {
2339                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2340                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2341                 assert_eq!(events.len(), 2);
2342                 let close_chan_update_1 = match events[0] {
2343                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2344                                 msg.clone()
2345                         },
2346                         _ => panic!("Unexpected event"),
2347                 };
2348                 match events[1] {
2349                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2350                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2351                         },
2352                         _ => panic!("Unexpected event"),
2353                 }
2354                 check_added_monitors!(nodes[3], 1);
2355
2356                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2357                 {
2358                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2359                         node_txn.retain(|tx| {
2360                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2361                                         false
2362                                 } else { true }
2363                         });
2364                 }
2365
2366                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2367
2368                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2369                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2370
2371                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2372                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2373                 assert_eq!(events.len(), 2);
2374                 let close_chan_update_2 = match events[0] {
2375                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2376                                 msg.clone()
2377                         },
2378                         _ => panic!("Unexpected event"),
2379                 };
2380                 match events[1] {
2381                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2382                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2383                         },
2384                         _ => panic!("Unexpected event"),
2385                 }
2386                 check_added_monitors!(nodes[4], 1);
2387                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2388
2389                 mine_transaction(&nodes[4], &node_txn[0]);
2390                 check_preimage_claim(&nodes[4], &node_txn);
2391                 (close_chan_update_1, close_chan_update_2)
2392         };
2393         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2394         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2395         assert_eq!(nodes[3].node.list_channels().len(), 0);
2396         assert_eq!(nodes[4].node.list_channels().len(), 0);
2397
2398         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2399                 ChannelMonitorUpdateStatus::Completed);
2400         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2401         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2402 }
2403
2404 #[test]
2405 fn test_justice_tx_htlc_timeout() {
2406         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2407         let mut alice_config = UserConfig::default();
2408         alice_config.channel_handshake_config.announced_channel = true;
2409         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2410         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2411         let mut bob_config = UserConfig::default();
2412         bob_config.channel_handshake_config.announced_channel = true;
2413         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2414         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2415         let user_cfgs = [Some(alice_config), Some(bob_config)];
2416         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2417         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2418         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2419         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2420         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2421         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2422         // Create some new channels:
2423         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2424
2425         // A pending HTLC which will be revoked:
2426         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2427         // Get the will-be-revoked local txn from nodes[0]
2428         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2429         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2430         assert_eq!(revoked_local_txn[0].input.len(), 1);
2431         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2432         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2433         assert_eq!(revoked_local_txn[1].input.len(), 1);
2434         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2435         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2436         // Revoke the old state
2437         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2438
2439         {
2440                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2441                 {
2442                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2444                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2445                         check_spends!(node_txn[0], revoked_local_txn[0]);
2446                         node_txn.swap_remove(0);
2447                 }
2448                 check_added_monitors!(nodes[1], 1);
2449                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2450                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2451
2452                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2453                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2454                 // Verify broadcast of revoked HTLC-timeout
2455                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2456                 check_added_monitors!(nodes[0], 1);
2457                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2458                 // Broadcast revoked HTLC-timeout on node 1
2459                 mine_transaction(&nodes[1], &node_txn[1]);
2460                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2461         }
2462         get_announce_close_broadcast_events(&nodes, 0, 1);
2463         assert_eq!(nodes[0].node.list_channels().len(), 0);
2464         assert_eq!(nodes[1].node.list_channels().len(), 0);
2465 }
2466
2467 #[test]
2468 fn test_justice_tx_htlc_success() {
2469         // Test justice txn built on revoked HTLC-Success tx, against both sides
2470         let mut alice_config = UserConfig::default();
2471         alice_config.channel_handshake_config.announced_channel = true;
2472         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2473         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2474         let mut bob_config = UserConfig::default();
2475         bob_config.channel_handshake_config.announced_channel = true;
2476         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2477         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2478         let user_cfgs = [Some(alice_config), Some(bob_config)];
2479         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2480         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2481         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2482         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2483         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2484         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2485         // Create some new channels:
2486         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2487
2488         // A pending HTLC which will be revoked:
2489         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2490         // Get the will-be-revoked local txn from B
2491         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2492         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2493         assert_eq!(revoked_local_txn[0].input.len(), 1);
2494         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2495         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2496         // Revoke the old state
2497         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2498         {
2499                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2500                 {
2501                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2502                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2503                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2504
2505                         check_spends!(node_txn[0], revoked_local_txn[0]);
2506                         node_txn.swap_remove(0);
2507                 }
2508                 check_added_monitors!(nodes[0], 1);
2509                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2510
2511                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2512                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2513                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2514                 check_added_monitors!(nodes[1], 1);
2515                 mine_transaction(&nodes[0], &node_txn[1]);
2516                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2517                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2518         }
2519         get_announce_close_broadcast_events(&nodes, 0, 1);
2520         assert_eq!(nodes[0].node.list_channels().len(), 0);
2521         assert_eq!(nodes[1].node.list_channels().len(), 0);
2522 }
2523
2524 #[test]
2525 fn revoked_output_claim() {
2526         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2527         // transaction is broadcast by its counterparty
2528         let chanmon_cfgs = create_chanmon_cfgs(2);
2529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2531         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2532         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2533         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2534         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2535         assert_eq!(revoked_local_txn.len(), 1);
2536         // Only output is the full channel value back to nodes[0]:
2537         assert_eq!(revoked_local_txn[0].output.len(), 1);
2538         // Send a payment through, updating everyone's latest commitment txn
2539         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2540
2541         // Inform nodes[1] that nodes[0] broadcast a stale tx
2542         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2543         check_added_monitors!(nodes[1], 1);
2544         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2545         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2546         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2547
2548         check_spends!(node_txn[0], revoked_local_txn[0]);
2549
2550         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2551         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2552         get_announce_close_broadcast_events(&nodes, 0, 1);
2553         check_added_monitors!(nodes[0], 1);
2554         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2555 }
2556
2557 #[test]
2558 fn claim_htlc_outputs_shared_tx() {
2559         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2560         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2561         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2564         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2565
2566         // Create some new channel:
2567         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2568
2569         // Rebalance the network to generate htlc in the two directions
2570         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2571         // 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
2572         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2573         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2574
2575         // Get the will-be-revoked local txn from node[0]
2576         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2577         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2578         assert_eq!(revoked_local_txn[0].input.len(), 1);
2579         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2580         assert_eq!(revoked_local_txn[1].input.len(), 1);
2581         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2582         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2583         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2584
2585         //Revoke the old state
2586         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2587
2588         {
2589                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2590                 check_added_monitors!(nodes[0], 1);
2591                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2592                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2593                 check_added_monitors!(nodes[1], 1);
2594                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2595                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2596                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2597
2598                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2599                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2600
2601                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2602                 check_spends!(node_txn[0], revoked_local_txn[0]);
2603
2604                 let mut witness_lens = BTreeSet::new();
2605                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2606                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2607                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2608                 assert_eq!(witness_lens.len(), 3);
2609                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2610                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2611                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2612
2613                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2614                 // ANTI_REORG_DELAY confirmations.
2615                 mine_transaction(&nodes[1], &node_txn[0]);
2616                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2617                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2618         }
2619         get_announce_close_broadcast_events(&nodes, 0, 1);
2620         assert_eq!(nodes[0].node.list_channels().len(), 0);
2621         assert_eq!(nodes[1].node.list_channels().len(), 0);
2622 }
2623
2624 #[test]
2625 fn claim_htlc_outputs_single_tx() {
2626         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2627         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2628         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2629         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2630         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2631         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2632
2633         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2634
2635         // Rebalance the network to generate htlc in the two directions
2636         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2637         // 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
2638         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2639         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2640         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2641
2642         // Get the will-be-revoked local txn from node[0]
2643         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2644
2645         //Revoke the old state
2646         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2647
2648         {
2649                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2650                 check_added_monitors!(nodes[0], 1);
2651                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2652                 check_added_monitors!(nodes[1], 1);
2653                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2654                 let mut events = nodes[0].node.get_and_clear_pending_events();
2655                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2656                 match events.last().unwrap() {
2657                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2658                         _ => panic!("Unexpected event"),
2659                 }
2660
2661                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2662                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2663
2664                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2665
2666                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2667                 assert_eq!(node_txn[0].input.len(), 1);
2668                 check_spends!(node_txn[0], chan_1.3);
2669                 assert_eq!(node_txn[1].input.len(), 1);
2670                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2671                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2672                 check_spends!(node_txn[1], node_txn[0]);
2673
2674                 // Filter out any non justice transactions.
2675                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2676                 assert!(node_txn.len() > 3);
2677
2678                 assert_eq!(node_txn[0].input.len(), 1);
2679                 assert_eq!(node_txn[1].input.len(), 1);
2680                 assert_eq!(node_txn[2].input.len(), 1);
2681
2682                 check_spends!(node_txn[0], revoked_local_txn[0]);
2683                 check_spends!(node_txn[1], revoked_local_txn[0]);
2684                 check_spends!(node_txn[2], revoked_local_txn[0]);
2685
2686                 let mut witness_lens = BTreeSet::new();
2687                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2688                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2689                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2690                 assert_eq!(witness_lens.len(), 3);
2691                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2692                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2693                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2694
2695                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2696                 // ANTI_REORG_DELAY confirmations.
2697                 mine_transaction(&nodes[1], &node_txn[0]);
2698                 mine_transaction(&nodes[1], &node_txn[1]);
2699                 mine_transaction(&nodes[1], &node_txn[2]);
2700                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2701                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2702         }
2703         get_announce_close_broadcast_events(&nodes, 0, 1);
2704         assert_eq!(nodes[0].node.list_channels().len(), 0);
2705         assert_eq!(nodes[1].node.list_channels().len(), 0);
2706 }
2707
2708 #[test]
2709 fn test_htlc_on_chain_success() {
2710         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2711         // the preimage backward accordingly. So here we test that ChannelManager is
2712         // broadcasting the right event to other nodes in payment path.
2713         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2714         // A --------------------> B ----------------------> C (preimage)
2715         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2716         // commitment transaction was broadcast.
2717         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2718         // towards B.
2719         // B should be able to claim via preimage if A then broadcasts its local tx.
2720         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2721         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2722         // PaymentSent event).
2723
2724         let chanmon_cfgs = create_chanmon_cfgs(3);
2725         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2726         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2727         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2728
2729         // Create some initial channels
2730         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2731         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2732
2733         // Ensure all nodes are at the same height
2734         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2735         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2736         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2737         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2738
2739         // Rebalance the network a bit by relaying one payment through all the channels...
2740         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2741         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2742
2743         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2744         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2745
2746         // Broadcast legit commitment tx from C on B's chain
2747         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2748         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2749         assert_eq!(commitment_tx.len(), 1);
2750         check_spends!(commitment_tx[0], chan_2.3);
2751         nodes[2].node.claim_funds(our_payment_preimage);
2752         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2753         nodes[2].node.claim_funds(our_payment_preimage_2);
2754         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2755         check_added_monitors!(nodes[2], 2);
2756         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2757         assert!(updates.update_add_htlcs.is_empty());
2758         assert!(updates.update_fail_htlcs.is_empty());
2759         assert!(updates.update_fail_malformed_htlcs.is_empty());
2760         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2761
2762         mine_transaction(&nodes[2], &commitment_tx[0]);
2763         check_closed_broadcast!(nodes[2], true);
2764         check_added_monitors!(nodes[2], 1);
2765         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2766         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2767         assert_eq!(node_txn.len(), 2);
2768         check_spends!(node_txn[0], commitment_tx[0]);
2769         check_spends!(node_txn[1], commitment_tx[0]);
2770         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2771         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2772         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2773         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2774         assert_eq!(node_txn[0].lock_time.0, 0);
2775         assert_eq!(node_txn[1].lock_time.0, 0);
2776
2777         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2778         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()]));
2779         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2780         {
2781                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2782                 assert_eq!(added_monitors.len(), 1);
2783                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2784                 added_monitors.clear();
2785         }
2786         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2787         assert_eq!(forwarded_events.len(), 3);
2788         match forwarded_events[0] {
2789                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2790                 _ => panic!("Unexpected event"),
2791         }
2792         let chan_id = Some(chan_1.2);
2793         match forwarded_events[1] {
2794                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2795                         assert_eq!(fee_earned_msat, Some(1000));
2796                         assert_eq!(prev_channel_id, chan_id);
2797                         assert_eq!(claim_from_onchain_tx, true);
2798                         assert_eq!(next_channel_id, Some(chan_2.2));
2799                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2800                 },
2801                 _ => panic!()
2802         }
2803         match forwarded_events[2] {
2804                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2805                         assert_eq!(fee_earned_msat, Some(1000));
2806                         assert_eq!(prev_channel_id, chan_id);
2807                         assert_eq!(claim_from_onchain_tx, true);
2808                         assert_eq!(next_channel_id, Some(chan_2.2));
2809                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2810                 },
2811                 _ => panic!()
2812         }
2813         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2814         {
2815                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2816                 assert_eq!(added_monitors.len(), 2);
2817                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2818                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2819                 added_monitors.clear();
2820         }
2821         assert_eq!(events.len(), 3);
2822
2823         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2824         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2825
2826         match nodes_2_event {
2827                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2828                 _ => panic!("Unexpected event"),
2829         }
2830
2831         match nodes_0_event {
2832                 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, .. } } => {
2833                         assert!(update_add_htlcs.is_empty());
2834                         assert!(update_fail_htlcs.is_empty());
2835                         assert_eq!(update_fulfill_htlcs.len(), 1);
2836                         assert!(update_fail_malformed_htlcs.is_empty());
2837                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2838                 },
2839                 _ => panic!("Unexpected event"),
2840         };
2841
2842         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2843         match events[0] {
2844                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2845                 _ => panic!("Unexpected event"),
2846         }
2847
2848         macro_rules! check_tx_local_broadcast {
2849                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2850                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2851                         assert_eq!(node_txn.len(), 2);
2852                         // Node[1]: 2 * HTLC-timeout tx
2853                         // Node[0]: 2 * HTLC-timeout tx
2854                         check_spends!(node_txn[0], $commitment_tx);
2855                         check_spends!(node_txn[1], $commitment_tx);
2856                         assert_ne!(node_txn[0].lock_time.0, 0);
2857                         assert_ne!(node_txn[1].lock_time.0, 0);
2858                         if $htlc_offered {
2859                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2860                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2861                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2862                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2863                         } else {
2864                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2865                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2866                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2867                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2868                         }
2869                         node_txn.clear();
2870                 } }
2871         }
2872         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2873         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2874
2875         // Broadcast legit commitment tx from A on B's chain
2876         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2877         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2878         check_spends!(node_a_commitment_tx[0], chan_1.3);
2879         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2880         check_closed_broadcast!(nodes[1], true);
2881         check_added_monitors!(nodes[1], 1);
2882         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2883         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2884         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2885         let commitment_spend =
2886                 if node_txn.len() == 1 {
2887                         &node_txn[0]
2888                 } else {
2889                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2890                         // FullBlockViaListen
2891                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2892                                 check_spends!(node_txn[1], commitment_tx[0]);
2893                                 check_spends!(node_txn[2], commitment_tx[0]);
2894                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2895                                 &node_txn[0]
2896                         } else {
2897                                 check_spends!(node_txn[0], commitment_tx[0]);
2898                                 check_spends!(node_txn[1], commitment_tx[0]);
2899                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2900                                 &node_txn[2]
2901                         }
2902                 };
2903
2904         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2905         assert_eq!(commitment_spend.input.len(), 2);
2906         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2907         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2908         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2909         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2910         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2911         // we already checked the same situation with A.
2912
2913         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2914         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2915         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2916         check_closed_broadcast!(nodes[0], true);
2917         check_added_monitors!(nodes[0], 1);
2918         let events = nodes[0].node.get_and_clear_pending_events();
2919         assert_eq!(events.len(), 5);
2920         let mut first_claimed = false;
2921         for event in events {
2922                 match event {
2923                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2924                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2925                                         assert!(!first_claimed);
2926                                         first_claimed = true;
2927                                 } else {
2928                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2929                                         assert_eq!(payment_hash, payment_hash_2);
2930                                 }
2931                         },
2932                         Event::PaymentPathSuccessful { .. } => {},
2933                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2934                         _ => panic!("Unexpected event"),
2935                 }
2936         }
2937         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2938 }
2939
2940 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2941         // Test that in case of a unilateral close onchain, we detect the state of output and
2942         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2943         // broadcasting the right event to other nodes in payment path.
2944         // A ------------------> B ----------------------> C (timeout)
2945         //    B's commitment tx                 C's commitment tx
2946         //            \                                  \
2947         //         B's HTLC timeout tx               B's timeout tx
2948
2949         let chanmon_cfgs = create_chanmon_cfgs(3);
2950         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2951         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2952         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2953         *nodes[0].connect_style.borrow_mut() = connect_style;
2954         *nodes[1].connect_style.borrow_mut() = connect_style;
2955         *nodes[2].connect_style.borrow_mut() = connect_style;
2956
2957         // Create some intial channels
2958         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2959         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2960
2961         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2962         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2963         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2964
2965         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2966
2967         // Broadcast legit commitment tx from C on B's chain
2968         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2969         check_spends!(commitment_tx[0], chan_2.3);
2970         nodes[2].node.fail_htlc_backwards(&payment_hash);
2971         check_added_monitors!(nodes[2], 0);
2972         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2973         check_added_monitors!(nodes[2], 1);
2974
2975         let events = nodes[2].node.get_and_clear_pending_msg_events();
2976         assert_eq!(events.len(), 1);
2977         match events[0] {
2978                 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, .. } } => {
2979                         assert!(update_add_htlcs.is_empty());
2980                         assert!(!update_fail_htlcs.is_empty());
2981                         assert!(update_fulfill_htlcs.is_empty());
2982                         assert!(update_fail_malformed_htlcs.is_empty());
2983                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2984                 },
2985                 _ => panic!("Unexpected event"),
2986         };
2987         mine_transaction(&nodes[2], &commitment_tx[0]);
2988         check_closed_broadcast!(nodes[2], true);
2989         check_added_monitors!(nodes[2], 1);
2990         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2991         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2992         assert_eq!(node_txn.len(), 0);
2993
2994         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2995         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2996         mine_transaction(&nodes[1], &commitment_tx[0]);
2997         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
2998                 , [nodes[2].node.get_our_node_id()], 100000);
2999         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3000         let timeout_tx = {
3001                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3002                 if nodes[1].connect_style.borrow().skips_blocks() {
3003                         assert_eq!(txn.len(), 1);
3004                 } else {
3005                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3006                 }
3007                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3008                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3009                 txn.remove(0)
3010         };
3011
3012         mine_transaction(&nodes[1], &timeout_tx);
3013         check_added_monitors!(nodes[1], 1);
3014         check_closed_broadcast!(nodes[1], true);
3015
3016         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3017
3018         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 }]);
3019         check_added_monitors!(nodes[1], 1);
3020         let events = nodes[1].node.get_and_clear_pending_msg_events();
3021         assert_eq!(events.len(), 1);
3022         match events[0] {
3023                 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, .. } } => {
3024                         assert!(update_add_htlcs.is_empty());
3025                         assert!(!update_fail_htlcs.is_empty());
3026                         assert!(update_fulfill_htlcs.is_empty());
3027                         assert!(update_fail_malformed_htlcs.is_empty());
3028                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3029                 },
3030                 _ => panic!("Unexpected event"),
3031         };
3032
3033         // Broadcast legit commitment tx from B on A's chain
3034         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3035         check_spends!(commitment_tx[0], chan_1.3);
3036
3037         mine_transaction(&nodes[0], &commitment_tx[0]);
3038         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3039
3040         check_closed_broadcast!(nodes[0], true);
3041         check_added_monitors!(nodes[0], 1);
3042         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3043         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3044         assert_eq!(node_txn.len(), 1);
3045         check_spends!(node_txn[0], commitment_tx[0]);
3046         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3047 }
3048
3049 #[test]
3050 fn test_htlc_on_chain_timeout() {
3051         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3052         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3053         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3054 }
3055
3056 #[test]
3057 fn test_simple_commitment_revoked_fail_backward() {
3058         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3059         // and fail backward accordingly.
3060
3061         let chanmon_cfgs = create_chanmon_cfgs(3);
3062         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3063         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3064         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3065
3066         // Create some initial channels
3067         create_announced_chan_between_nodes(&nodes, 0, 1);
3068         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3069
3070         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3071         // Get the will-be-revoked local txn from nodes[2]
3072         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3073         // Revoke the old state
3074         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3075
3076         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3077
3078         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3079         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3080         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3081         check_added_monitors!(nodes[1], 1);
3082         check_closed_broadcast!(nodes[1], true);
3083
3084         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 }]);
3085         check_added_monitors!(nodes[1], 1);
3086         let events = nodes[1].node.get_and_clear_pending_msg_events();
3087         assert_eq!(events.len(), 1);
3088         match events[0] {
3089                 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, .. } } => {
3090                         assert!(update_add_htlcs.is_empty());
3091                         assert_eq!(update_fail_htlcs.len(), 1);
3092                         assert!(update_fulfill_htlcs.is_empty());
3093                         assert!(update_fail_malformed_htlcs.is_empty());
3094                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3095
3096                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3097                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3098                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3099                 },
3100                 _ => panic!("Unexpected event"),
3101         }
3102 }
3103
3104 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3105         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3106         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3107         // commitment transaction anymore.
3108         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3109         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3110         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3111         // technically disallowed and we should probably handle it reasonably.
3112         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3113         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3114         // transactions:
3115         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3116         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3117         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3118         //   and once they revoke the previous commitment transaction (allowing us to send a new
3119         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3120         let chanmon_cfgs = create_chanmon_cfgs(3);
3121         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3122         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3123         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3124
3125         // Create some initial channels
3126         create_announced_chan_between_nodes(&nodes, 0, 1);
3127         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3128
3129         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 });
3130         // Get the will-be-revoked local txn from nodes[2]
3131         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3132         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3133         // Revoke the old state
3134         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3135
3136         let value = if use_dust {
3137                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3138                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3139                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3140                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3141         } else { 3000000 };
3142
3143         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3144         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3145         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3146
3147         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3148         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3149         check_added_monitors!(nodes[2], 1);
3150         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3151         assert!(updates.update_add_htlcs.is_empty());
3152         assert!(updates.update_fulfill_htlcs.is_empty());
3153         assert!(updates.update_fail_malformed_htlcs.is_empty());
3154         assert_eq!(updates.update_fail_htlcs.len(), 1);
3155         assert!(updates.update_fee.is_none());
3156         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3157         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3158         // Drop the last RAA from 3 -> 2
3159
3160         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3161         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3162         check_added_monitors!(nodes[2], 1);
3163         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3164         assert!(updates.update_add_htlcs.is_empty());
3165         assert!(updates.update_fulfill_htlcs.is_empty());
3166         assert!(updates.update_fail_malformed_htlcs.is_empty());
3167         assert_eq!(updates.update_fail_htlcs.len(), 1);
3168         assert!(updates.update_fee.is_none());
3169         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3170         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3171         check_added_monitors!(nodes[1], 1);
3172         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3173         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3174         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3175         check_added_monitors!(nodes[2], 1);
3176
3177         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3178         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3179         check_added_monitors!(nodes[2], 1);
3180         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3181         assert!(updates.update_add_htlcs.is_empty());
3182         assert!(updates.update_fulfill_htlcs.is_empty());
3183         assert!(updates.update_fail_malformed_htlcs.is_empty());
3184         assert_eq!(updates.update_fail_htlcs.len(), 1);
3185         assert!(updates.update_fee.is_none());
3186         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3187         // At this point first_payment_hash has dropped out of the latest two commitment
3188         // transactions that nodes[1] is tracking...
3189         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3190         check_added_monitors!(nodes[1], 1);
3191         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3192         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3193         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3194         check_added_monitors!(nodes[2], 1);
3195
3196         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3197         // on nodes[2]'s RAA.
3198         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3199         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3200                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3201         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3202         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3203         check_added_monitors!(nodes[1], 0);
3204
3205         if deliver_bs_raa {
3206                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3207                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3208                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3209                 check_added_monitors!(nodes[1], 1);
3210                 let events = nodes[1].node.get_and_clear_pending_events();
3211                 assert_eq!(events.len(), 2);
3212                 match events[0] {
3213                         Event::PendingHTLCsForwardable { .. } => { },
3214                         _ => panic!("Unexpected event"),
3215                 };
3216                 match events[1] {
3217                         Event::HTLCHandlingFailed { .. } => { },
3218                         _ => panic!("Unexpected event"),
3219                 }
3220                 // Deliberately don't process the pending fail-back so they all fail back at once after
3221                 // block connection just like the !deliver_bs_raa case
3222         }
3223
3224         let mut failed_htlcs = HashSet::new();
3225         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3226
3227         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3228         check_added_monitors!(nodes[1], 1);
3229         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3230
3231         let events = nodes[1].node.get_and_clear_pending_events();
3232         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3233         match events[0] {
3234                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3235                 _ => panic!("Unexepected event"),
3236         }
3237         match events[1] {
3238                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3239                         assert_eq!(*payment_hash, fourth_payment_hash);
3240                 },
3241                 _ => panic!("Unexpected event"),
3242         }
3243         match events[2] {
3244                 Event::PaymentFailed { ref payment_hash, .. } => {
3245                         assert_eq!(*payment_hash, fourth_payment_hash);
3246                 },
3247                 _ => panic!("Unexpected event"),
3248         }
3249
3250         nodes[1].node.process_pending_htlc_forwards();
3251         check_added_monitors!(nodes[1], 1);
3252
3253         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3254         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3255
3256         if deliver_bs_raa {
3257                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3258                 match nodes_2_event {
3259                         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, .. } } => {
3260                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3261                                 assert_eq!(update_add_htlcs.len(), 1);
3262                                 assert!(update_fulfill_htlcs.is_empty());
3263                                 assert!(update_fail_htlcs.is_empty());
3264                                 assert!(update_fail_malformed_htlcs.is_empty());
3265                         },
3266                         _ => panic!("Unexpected event"),
3267                 }
3268         }
3269
3270         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3271         match nodes_2_event {
3272                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3273                         assert_eq!(channel_id, chan_2.2);
3274                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3275                 },
3276                 _ => panic!("Unexpected event"),
3277         }
3278
3279         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3280         match nodes_0_event {
3281                 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, .. } } => {
3282                         assert!(update_add_htlcs.is_empty());
3283                         assert_eq!(update_fail_htlcs.len(), 3);
3284                         assert!(update_fulfill_htlcs.is_empty());
3285                         assert!(update_fail_malformed_htlcs.is_empty());
3286                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3287
3288                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3289                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3290                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3291
3292                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3293
3294                         let events = nodes[0].node.get_and_clear_pending_events();
3295                         assert_eq!(events.len(), 6);
3296                         match events[0] {
3297                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3298                                         assert!(failed_htlcs.insert(payment_hash.0));
3299                                         // If we delivered B's RAA we got an unknown preimage error, not something
3300                                         // that we should update our routing table for.
3301                                         if !deliver_bs_raa {
3302                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3303                                         }
3304                                 },
3305                                 _ => panic!("Unexpected event"),
3306                         }
3307                         match events[1] {
3308                                 Event::PaymentFailed { ref payment_hash, .. } => {
3309                                         assert_eq!(*payment_hash, first_payment_hash);
3310                                 },
3311                                 _ => panic!("Unexpected event"),
3312                         }
3313                         match events[2] {
3314                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3315                                         assert!(failed_htlcs.insert(payment_hash.0));
3316                                 },
3317                                 _ => panic!("Unexpected event"),
3318                         }
3319                         match events[3] {
3320                                 Event::PaymentFailed { ref payment_hash, .. } => {
3321                                         assert_eq!(*payment_hash, second_payment_hash);
3322                                 },
3323                                 _ => panic!("Unexpected event"),
3324                         }
3325                         match events[4] {
3326                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3327                                         assert!(failed_htlcs.insert(payment_hash.0));
3328                                 },
3329                                 _ => panic!("Unexpected event"),
3330                         }
3331                         match events[5] {
3332                                 Event::PaymentFailed { ref payment_hash, .. } => {
3333                                         assert_eq!(*payment_hash, third_payment_hash);
3334                                 },
3335                                 _ => panic!("Unexpected event"),
3336                         }
3337                 },
3338                 _ => panic!("Unexpected event"),
3339         }
3340
3341         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3342         match events[0] {
3343                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3344                 _ => panic!("Unexpected event"),
3345         }
3346
3347         assert!(failed_htlcs.contains(&first_payment_hash.0));
3348         assert!(failed_htlcs.contains(&second_payment_hash.0));
3349         assert!(failed_htlcs.contains(&third_payment_hash.0));
3350 }
3351
3352 #[test]
3353 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3354         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3355         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3356         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3357         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3358 }
3359
3360 #[test]
3361 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3362         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3363         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3364         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3365         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3366 }
3367
3368 #[test]
3369 fn fail_backward_pending_htlc_upon_channel_failure() {
3370         let chanmon_cfgs = create_chanmon_cfgs(2);
3371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3373         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3374         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3375
3376         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3377         {
3378                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3379                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3380                         PaymentId(payment_hash.0)).unwrap();
3381                 check_added_monitors!(nodes[0], 1);
3382
3383                 let payment_event = {
3384                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3385                         assert_eq!(events.len(), 1);
3386                         SendEvent::from_event(events.remove(0))
3387                 };
3388                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3389                 assert_eq!(payment_event.msgs.len(), 1);
3390         }
3391
3392         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3393         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3394         {
3395                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3396                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3397                 check_added_monitors!(nodes[0], 0);
3398
3399                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3400         }
3401
3402         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3403         {
3404                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3405
3406                 let secp_ctx = Secp256k1::new();
3407                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3408                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3409                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3410                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3411                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3412                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3413
3414                 // Send a 0-msat update_add_htlc to fail the channel.
3415                 let update_add_htlc = msgs::UpdateAddHTLC {
3416                         channel_id: chan.2,
3417                         htlc_id: 0,
3418                         amount_msat: 0,
3419                         payment_hash,
3420                         cltv_expiry,
3421                         onion_routing_packet,
3422                         skimmed_fee_msat: None,
3423                 };
3424                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3425         }
3426         let events = nodes[0].node.get_and_clear_pending_events();
3427         assert_eq!(events.len(), 3);
3428         // Check that Alice fails backward the pending HTLC from the second payment.
3429         match events[0] {
3430                 Event::PaymentPathFailed { payment_hash, .. } => {
3431                         assert_eq!(payment_hash, failed_payment_hash);
3432                 },
3433                 _ => panic!("Unexpected event"),
3434         }
3435         match events[1] {
3436                 Event::PaymentFailed { payment_hash, .. } => {
3437                         assert_eq!(payment_hash, failed_payment_hash);
3438                 },
3439                 _ => panic!("Unexpected event"),
3440         }
3441         match events[2] {
3442                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3443                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3444                 },
3445                 _ => panic!("Unexpected event {:?}", events[1]),
3446         }
3447         check_closed_broadcast!(nodes[0], true);
3448         check_added_monitors!(nodes[0], 1);
3449 }
3450
3451 #[test]
3452 fn test_htlc_ignore_latest_remote_commitment() {
3453         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3454         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3455         let chanmon_cfgs = create_chanmon_cfgs(2);
3456         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3457         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3458         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3459         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3460                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3461                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3462                 // connect_style.
3463                 return;
3464         }
3465         create_announced_chan_between_nodes(&nodes, 0, 1);
3466
3467         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3468         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3469         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3470         check_closed_broadcast!(nodes[0], true);
3471         check_added_monitors!(nodes[0], 1);
3472         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3473
3474         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3475         assert_eq!(node_txn.len(), 3);
3476         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3477
3478         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3479         connect_block(&nodes[1], &block);
3480         check_closed_broadcast!(nodes[1], true);
3481         check_added_monitors!(nodes[1], 1);
3482         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3483
3484         // Duplicate the connect_block call since this may happen due to other listeners
3485         // registering new transactions
3486         connect_block(&nodes[1], &block);
3487 }
3488
3489 #[test]
3490 fn test_force_close_fail_back() {
3491         // Check which HTLCs are failed-backwards on channel force-closure
3492         let chanmon_cfgs = create_chanmon_cfgs(3);
3493         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3494         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3495         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3496         create_announced_chan_between_nodes(&nodes, 0, 1);
3497         create_announced_chan_between_nodes(&nodes, 1, 2);
3498
3499         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3500
3501         let mut payment_event = {
3502                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3503                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3504                 check_added_monitors!(nodes[0], 1);
3505
3506                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3507                 assert_eq!(events.len(), 1);
3508                 SendEvent::from_event(events.remove(0))
3509         };
3510
3511         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3512         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3513
3514         expect_pending_htlcs_forwardable!(nodes[1]);
3515
3516         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3517         assert_eq!(events_2.len(), 1);
3518         payment_event = SendEvent::from_event(events_2.remove(0));
3519         assert_eq!(payment_event.msgs.len(), 1);
3520
3521         check_added_monitors!(nodes[1], 1);
3522         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3523         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3524         check_added_monitors!(nodes[2], 1);
3525         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3526
3527         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3528         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3529         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3530
3531         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3532         check_closed_broadcast!(nodes[2], true);
3533         check_added_monitors!(nodes[2], 1);
3534         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3535         let tx = {
3536                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3537                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3538                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3539                 // back to nodes[1] upon timeout otherwise.
3540                 assert_eq!(node_txn.len(), 1);
3541                 node_txn.remove(0)
3542         };
3543
3544         mine_transaction(&nodes[1], &tx);
3545
3546         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3547         check_closed_broadcast!(nodes[1], true);
3548         check_added_monitors!(nodes[1], 1);
3549         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3550
3551         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3552         {
3553                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3554                         .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);
3555         }
3556         mine_transaction(&nodes[2], &tx);
3557         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3558         assert_eq!(node_txn.len(), 1);
3559         assert_eq!(node_txn[0].input.len(), 1);
3560         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3561         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3562         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3563
3564         check_spends!(node_txn[0], tx);
3565 }
3566
3567 #[test]
3568 fn test_dup_events_on_peer_disconnect() {
3569         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3570         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3571         // as we used to generate the event immediately upon receipt of the payment preimage in the
3572         // update_fulfill_htlc message.
3573
3574         let chanmon_cfgs = create_chanmon_cfgs(2);
3575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3577         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3578         create_announced_chan_between_nodes(&nodes, 0, 1);
3579
3580         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3581
3582         nodes[1].node.claim_funds(payment_preimage);
3583         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3584         check_added_monitors!(nodes[1], 1);
3585         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3586         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3587         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3588
3589         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3590         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3591
3592         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3593         reconnect_args.pending_htlc_claims.0 = 1;
3594         reconnect_nodes(reconnect_args);
3595         expect_payment_path_successful!(nodes[0]);
3596 }
3597
3598 #[test]
3599 fn test_peer_disconnected_before_funding_broadcasted() {
3600         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3601         // before the funding transaction has been broadcasted.
3602         let chanmon_cfgs = create_chanmon_cfgs(2);
3603         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3604         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3605         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3606
3607         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3608         // broadcasted, even though it's created by `nodes[0]`.
3609         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();
3610         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3611         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3612         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3613         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3614
3615         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3616         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3617
3618         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3619
3620         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3621         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3622
3623         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3624         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3625         // broadcasted.
3626         {
3627                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3628         }
3629
3630         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3631         // disconnected before the funding transaction was broadcasted.
3632         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3633         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3634
3635         check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3636                 , [nodes[1].node.get_our_node_id()], 1000000);
3637         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3638                 , [nodes[0].node.get_our_node_id()], 1000000);
3639 }
3640
3641 #[test]
3642 fn test_simple_peer_disconnect() {
3643         // Test that we can reconnect when there are no lost messages
3644         let chanmon_cfgs = create_chanmon_cfgs(3);
3645         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3646         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3647         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3648         create_announced_chan_between_nodes(&nodes, 0, 1);
3649         create_announced_chan_between_nodes(&nodes, 1, 2);
3650
3651         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3652         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3653         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3654         reconnect_args.send_channel_ready = (true, true);
3655         reconnect_nodes(reconnect_args);
3656
3657         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3658         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3659         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3660         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3661
3662         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3663         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3664         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3665
3666         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3667         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3668         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3669         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3670
3671         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3672         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3673
3674         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3675         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3676
3677         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3678         reconnect_args.pending_cell_htlc_fails.0 = 1;
3679         reconnect_args.pending_cell_htlc_claims.0 = 1;
3680         reconnect_nodes(reconnect_args);
3681         {
3682                 let events = nodes[0].node.get_and_clear_pending_events();
3683                 assert_eq!(events.len(), 4);
3684                 match events[0] {
3685                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3686                                 assert_eq!(payment_preimage, payment_preimage_3);
3687                                 assert_eq!(payment_hash, payment_hash_3);
3688                         },
3689                         _ => panic!("Unexpected event"),
3690                 }
3691                 match events[1] {
3692                         Event::PaymentPathSuccessful { .. } => {},
3693                         _ => panic!("Unexpected event"),
3694                 }
3695                 match events[2] {
3696                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3697                                 assert_eq!(payment_hash, payment_hash_5);
3698                                 assert!(payment_failed_permanently);
3699                         },
3700                         _ => panic!("Unexpected event"),
3701                 }
3702                 match events[3] {
3703                         Event::PaymentFailed { payment_hash, .. } => {
3704                                 assert_eq!(payment_hash, payment_hash_5);
3705                         },
3706                         _ => panic!("Unexpected event"),
3707                 }
3708         }
3709
3710         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3711         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3712 }
3713
3714 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3715         // Test that we can reconnect when in-flight HTLC updates get dropped
3716         let chanmon_cfgs = create_chanmon_cfgs(2);
3717         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3718         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3719         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3720
3721         let mut as_channel_ready = None;
3722         let channel_id = if messages_delivered == 0 {
3723                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3724                 as_channel_ready = Some(channel_ready);
3725                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3726                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3727                 // it before the channel_reestablish message.
3728                 chan_id
3729         } else {
3730                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3731         };
3732
3733         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3734
3735         let payment_event = {
3736                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3737                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3738                 check_added_monitors!(nodes[0], 1);
3739
3740                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3741                 assert_eq!(events.len(), 1);
3742                 SendEvent::from_event(events.remove(0))
3743         };
3744         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3745
3746         if messages_delivered < 2 {
3747                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3748         } else {
3749                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3750                 if messages_delivered >= 3 {
3751                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3752                         check_added_monitors!(nodes[1], 1);
3753                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3754
3755                         if messages_delivered >= 4 {
3756                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3757                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3758                                 check_added_monitors!(nodes[0], 1);
3759
3760                                 if messages_delivered >= 5 {
3761                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3762                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3763                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3764                                         check_added_monitors!(nodes[0], 1);
3765
3766                                         if messages_delivered >= 6 {
3767                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3768                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3769                                                 check_added_monitors!(nodes[1], 1);
3770                                         }
3771                                 }
3772                         }
3773                 }
3774         }
3775
3776         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3777         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3778         if messages_delivered < 3 {
3779                 if simulate_broken_lnd {
3780                         // lnd has a long-standing bug where they send a channel_ready prior to a
3781                         // channel_reestablish if you reconnect prior to channel_ready time.
3782                         //
3783                         // Here we simulate that behavior, delivering a channel_ready immediately on
3784                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3785                         // in `reconnect_nodes` but we currently don't fail based on that.
3786                         //
3787                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3788                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3789                 }
3790                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3791                 // received on either side, both sides will need to resend them.
3792                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3793                 reconnect_args.send_channel_ready = (true, true);
3794                 reconnect_args.pending_htlc_adds.1 = 1;
3795                 reconnect_nodes(reconnect_args);
3796         } else if messages_delivered == 3 {
3797                 // nodes[0] still wants its RAA + commitment_signed
3798                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3799                 reconnect_args.pending_htlc_adds.0 = -1;
3800                 reconnect_args.pending_raa.0 = true;
3801                 reconnect_nodes(reconnect_args);
3802         } else if messages_delivered == 4 {
3803                 // nodes[0] still wants its commitment_signed
3804                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3805                 reconnect_args.pending_htlc_adds.0 = -1;
3806                 reconnect_nodes(reconnect_args);
3807         } else if messages_delivered == 5 {
3808                 // nodes[1] still wants its final RAA
3809                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3810                 reconnect_args.pending_raa.1 = true;
3811                 reconnect_nodes(reconnect_args);
3812         } else if messages_delivered == 6 {
3813                 // Everything was delivered...
3814                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3815         }
3816
3817         let events_1 = nodes[1].node.get_and_clear_pending_events();
3818         if messages_delivered == 0 {
3819                 assert_eq!(events_1.len(), 2);
3820                 match events_1[0] {
3821                         Event::ChannelReady { .. } => { },
3822                         _ => panic!("Unexpected event"),
3823                 };
3824                 match events_1[1] {
3825                         Event::PendingHTLCsForwardable { .. } => { },
3826                         _ => panic!("Unexpected event"),
3827                 };
3828         } else {
3829                 assert_eq!(events_1.len(), 1);
3830                 match events_1[0] {
3831                         Event::PendingHTLCsForwardable { .. } => { },
3832                         _ => panic!("Unexpected event"),
3833                 };
3834         }
3835
3836         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3837         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3838         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3839
3840         nodes[1].node.process_pending_htlc_forwards();
3841
3842         let events_2 = nodes[1].node.get_and_clear_pending_events();
3843         assert_eq!(events_2.len(), 1);
3844         match events_2[0] {
3845                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3846                         assert_eq!(payment_hash_1, *payment_hash);
3847                         assert_eq!(amount_msat, 1_000_000);
3848                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3849                         assert_eq!(via_channel_id, Some(channel_id));
3850                         match &purpose {
3851                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3852                                         assert!(payment_preimage.is_none());
3853                                         assert_eq!(payment_secret_1, *payment_secret);
3854                                 },
3855                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3856                         }
3857                 },
3858                 _ => panic!("Unexpected event"),
3859         }
3860
3861         nodes[1].node.claim_funds(payment_preimage_1);
3862         check_added_monitors!(nodes[1], 1);
3863         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3864
3865         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3866         assert_eq!(events_3.len(), 1);
3867         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3868                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3869                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3870                         assert!(updates.update_add_htlcs.is_empty());
3871                         assert!(updates.update_fail_htlcs.is_empty());
3872                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3873                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3874                         assert!(updates.update_fee.is_none());
3875                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3876                 },
3877                 _ => panic!("Unexpected event"),
3878         };
3879
3880         if messages_delivered >= 1 {
3881                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3882
3883                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3884                 assert_eq!(events_4.len(), 1);
3885                 match events_4[0] {
3886                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3887                                 assert_eq!(payment_preimage_1, *payment_preimage);
3888                                 assert_eq!(payment_hash_1, *payment_hash);
3889                         },
3890                         _ => panic!("Unexpected event"),
3891                 }
3892
3893                 if messages_delivered >= 2 {
3894                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3895                         check_added_monitors!(nodes[0], 1);
3896                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3897
3898                         if messages_delivered >= 3 {
3899                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3900                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3901                                 check_added_monitors!(nodes[1], 1);
3902
3903                                 if messages_delivered >= 4 {
3904                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3905                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3906                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3907                                         check_added_monitors!(nodes[1], 1);
3908
3909                                         if messages_delivered >= 5 {
3910                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3911                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3912                                                 check_added_monitors!(nodes[0], 1);
3913                                         }
3914                                 }
3915                         }
3916                 }
3917         }
3918
3919         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3920         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3921         if messages_delivered < 2 {
3922                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3923                 reconnect_args.pending_htlc_claims.0 = 1;
3924                 reconnect_nodes(reconnect_args);
3925                 if messages_delivered < 1 {
3926                         expect_payment_sent!(nodes[0], payment_preimage_1);
3927                 } else {
3928                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3929                 }
3930         } else if messages_delivered == 2 {
3931                 // nodes[0] still wants its RAA + commitment_signed
3932                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3933                 reconnect_args.pending_htlc_adds.1 = -1;
3934                 reconnect_args.pending_raa.1 = true;
3935                 reconnect_nodes(reconnect_args);
3936         } else if messages_delivered == 3 {
3937                 // nodes[0] still wants its commitment_signed
3938                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3939                 reconnect_args.pending_htlc_adds.1 = -1;
3940                 reconnect_nodes(reconnect_args);
3941         } else if messages_delivered == 4 {
3942                 // nodes[1] still wants its final RAA
3943                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3944                 reconnect_args.pending_raa.0 = true;
3945                 reconnect_nodes(reconnect_args);
3946         } else if messages_delivered == 5 {
3947                 // Everything was delivered...
3948                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3949         }
3950
3951         if messages_delivered == 1 || messages_delivered == 2 {
3952                 expect_payment_path_successful!(nodes[0]);
3953         }
3954         if messages_delivered <= 5 {
3955                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3956                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3957         }
3958         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3959
3960         if messages_delivered > 2 {
3961                 expect_payment_path_successful!(nodes[0]);
3962         }
3963
3964         // Channel should still work fine...
3965         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3966         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3967         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3968 }
3969
3970 #[test]
3971 fn test_drop_messages_peer_disconnect_a() {
3972         do_test_drop_messages_peer_disconnect(0, true);
3973         do_test_drop_messages_peer_disconnect(0, false);
3974         do_test_drop_messages_peer_disconnect(1, false);
3975         do_test_drop_messages_peer_disconnect(2, false);
3976 }
3977
3978 #[test]
3979 fn test_drop_messages_peer_disconnect_b() {
3980         do_test_drop_messages_peer_disconnect(3, false);
3981         do_test_drop_messages_peer_disconnect(4, false);
3982         do_test_drop_messages_peer_disconnect(5, false);
3983         do_test_drop_messages_peer_disconnect(6, false);
3984 }
3985
3986 #[test]
3987 fn test_channel_ready_without_best_block_updated() {
3988         // Previously, if we were offline when a funding transaction was locked in, and then we came
3989         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3990         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3991         // channel_ready immediately instead.
3992         let chanmon_cfgs = create_chanmon_cfgs(2);
3993         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3994         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3995         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3996         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3997
3998         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3999
4000         let conf_height = nodes[0].best_block_info().1 + 1;
4001         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4002         let block_txn = [funding_tx];
4003         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4004         let conf_block_header = nodes[0].get_block_header(conf_height);
4005         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4006
4007         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4008         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4009         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4010 }
4011
4012 #[test]
4013 fn test_drop_messages_peer_disconnect_dual_htlc() {
4014         // Test that we can handle reconnecting when both sides of a channel have pending
4015         // commitment_updates when we disconnect.
4016         let chanmon_cfgs = create_chanmon_cfgs(2);
4017         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4018         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4019         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4020         create_announced_chan_between_nodes(&nodes, 0, 1);
4021
4022         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4023
4024         // Now try to send a second payment which will fail to send
4025         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4026         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4027                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4028         check_added_monitors!(nodes[0], 1);
4029
4030         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4031         assert_eq!(events_1.len(), 1);
4032         match events_1[0] {
4033                 MessageSendEvent::UpdateHTLCs { .. } => {},
4034                 _ => panic!("Unexpected event"),
4035         }
4036
4037         nodes[1].node.claim_funds(payment_preimage_1);
4038         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4039         check_added_monitors!(nodes[1], 1);
4040
4041         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4042         assert_eq!(events_2.len(), 1);
4043         match events_2[0] {
4044                 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 } } => {
4045                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4046                         assert!(update_add_htlcs.is_empty());
4047                         assert_eq!(update_fulfill_htlcs.len(), 1);
4048                         assert!(update_fail_htlcs.is_empty());
4049                         assert!(update_fail_malformed_htlcs.is_empty());
4050                         assert!(update_fee.is_none());
4051
4052                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4053                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4054                         assert_eq!(events_3.len(), 1);
4055                         match events_3[0] {
4056                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4057                                         assert_eq!(*payment_preimage, payment_preimage_1);
4058                                         assert_eq!(*payment_hash, payment_hash_1);
4059                                 },
4060                                 _ => panic!("Unexpected event"),
4061                         }
4062
4063                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4064                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4065                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4066                         check_added_monitors!(nodes[0], 1);
4067                 },
4068                 _ => panic!("Unexpected event"),
4069         }
4070
4071         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4072         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4073
4074         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4075                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4076         }, true).unwrap();
4077         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4078         assert_eq!(reestablish_1.len(), 1);
4079         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4080                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4081         }, false).unwrap();
4082         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4083         assert_eq!(reestablish_2.len(), 1);
4084
4085         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4086         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4087         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4088         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4089
4090         assert!(as_resp.0.is_none());
4091         assert!(bs_resp.0.is_none());
4092
4093         assert!(bs_resp.1.is_none());
4094         assert!(bs_resp.2.is_none());
4095
4096         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4097
4098         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4099         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4100         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4101         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4102         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4103         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4104         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4105         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4106         // No commitment_signed so get_event_msg's assert(len == 1) passes
4107         check_added_monitors!(nodes[1], 1);
4108
4109         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4110         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4111         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4112         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4113         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4114         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4115         assert!(bs_second_commitment_signed.update_fee.is_none());
4116         check_added_monitors!(nodes[1], 1);
4117
4118         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4119         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4120         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4121         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4122         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4123         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4124         assert!(as_commitment_signed.update_fee.is_none());
4125         check_added_monitors!(nodes[0], 1);
4126
4127         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4128         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4129         // No commitment_signed so get_event_msg's assert(len == 1) passes
4130         check_added_monitors!(nodes[0], 1);
4131
4132         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4133         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4134         // No commitment_signed so get_event_msg's assert(len == 1) passes
4135         check_added_monitors!(nodes[1], 1);
4136
4137         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4138         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4139         check_added_monitors!(nodes[1], 1);
4140
4141         expect_pending_htlcs_forwardable!(nodes[1]);
4142
4143         let events_5 = nodes[1].node.get_and_clear_pending_events();
4144         assert_eq!(events_5.len(), 1);
4145         match events_5[0] {
4146                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4147                         assert_eq!(payment_hash_2, *payment_hash);
4148                         match &purpose {
4149                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4150                                         assert!(payment_preimage.is_none());
4151                                         assert_eq!(payment_secret_2, *payment_secret);
4152                                 },
4153                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4154                         }
4155                 },
4156                 _ => panic!("Unexpected event"),
4157         }
4158
4159         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4160         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4161         check_added_monitors!(nodes[0], 1);
4162
4163         expect_payment_path_successful!(nodes[0]);
4164         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4165 }
4166
4167 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4168         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4169         // to avoid our counterparty failing the channel.
4170         let chanmon_cfgs = create_chanmon_cfgs(2);
4171         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4172         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4173         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4174
4175         create_announced_chan_between_nodes(&nodes, 0, 1);
4176
4177         let our_payment_hash = if send_partial_mpp {
4178                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4179                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4180                 // indicates there are more HTLCs coming.
4181                 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.
4182                 let payment_id = PaymentId([42; 32]);
4183                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4184                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4185                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4186                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4187                         &None, session_privs[0]).unwrap();
4188                 check_added_monitors!(nodes[0], 1);
4189                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4190                 assert_eq!(events.len(), 1);
4191                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4192                 // hop should *not* yet generate any PaymentClaimable event(s).
4193                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4194                 our_payment_hash
4195         } else {
4196                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4197         };
4198
4199         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4200         connect_block(&nodes[0], &block);
4201         connect_block(&nodes[1], &block);
4202         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4203         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4204                 block.header.prev_blockhash = block.block_hash();
4205                 connect_block(&nodes[0], &block);
4206                 connect_block(&nodes[1], &block);
4207         }
4208
4209         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4210
4211         check_added_monitors!(nodes[1], 1);
4212         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4213         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4214         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4215         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4216         assert!(htlc_timeout_updates.update_fee.is_none());
4217
4218         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4219         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4220         // 100_000 msat as u64, followed by the height at which we failed back above
4221         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4222         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4223         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4224 }
4225
4226 #[test]
4227 fn test_htlc_timeout() {
4228         do_test_htlc_timeout(true);
4229         do_test_htlc_timeout(false);
4230 }
4231
4232 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4233         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4234         let chanmon_cfgs = create_chanmon_cfgs(3);
4235         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4236         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4237         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4238         create_announced_chan_between_nodes(&nodes, 0, 1);
4239         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4240
4241         // Make sure all nodes are at the same starting height
4242         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4243         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4244         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4245
4246         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4247         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4248         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4249                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4250         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4251         check_added_monitors!(nodes[1], 1);
4252
4253         // Now attempt to route a second payment, which should be placed in the holding cell
4254         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4255         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4256         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4257                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4258         if forwarded_htlc {
4259                 check_added_monitors!(nodes[0], 1);
4260                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4261                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4262                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4263                 expect_pending_htlcs_forwardable!(nodes[1]);
4264         }
4265         check_added_monitors!(nodes[1], 0);
4266
4267         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4268         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4269         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4270         connect_blocks(&nodes[1], 1);
4271
4272         if forwarded_htlc {
4273                 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 }]);
4274                 check_added_monitors!(nodes[1], 1);
4275                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4276                 assert_eq!(fail_commit.len(), 1);
4277                 match fail_commit[0] {
4278                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4279                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4280                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4281                         },
4282                         _ => unreachable!(),
4283                 }
4284                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4285         } else {
4286                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4287         }
4288 }
4289
4290 #[test]
4291 fn test_holding_cell_htlc_add_timeouts() {
4292         do_test_holding_cell_htlc_add_timeouts(false);
4293         do_test_holding_cell_htlc_add_timeouts(true);
4294 }
4295
4296 macro_rules! check_spendable_outputs {
4297         ($node: expr, $keysinterface: expr) => {
4298                 {
4299                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4300                         let mut txn = Vec::new();
4301                         let mut all_outputs = Vec::new();
4302                         let secp_ctx = Secp256k1::new();
4303                         for event in events.drain(..) {
4304                                 match event {
4305                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4306                                                 for outp in outputs.drain(..) {
4307                                                         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());
4308                                                         all_outputs.push(outp);
4309                                                 }
4310                                         },
4311                                         _ => panic!("Unexpected event"),
4312                                 };
4313                         }
4314                         if all_outputs.len() > 1 {
4315                                 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) {
4316                                         txn.push(tx);
4317                                 }
4318                         }
4319                         txn
4320                 }
4321         }
4322 }
4323
4324 #[test]
4325 fn test_claim_sizeable_push_msat() {
4326         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4327         let chanmon_cfgs = create_chanmon_cfgs(2);
4328         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4329         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4330         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4331
4332         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4333         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4334         check_closed_broadcast!(nodes[1], true);
4335         check_added_monitors!(nodes[1], 1);
4336         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4337         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4338         assert_eq!(node_txn.len(), 1);
4339         check_spends!(node_txn[0], chan.3);
4340         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
4341
4342         mine_transaction(&nodes[1], &node_txn[0]);
4343         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4344
4345         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4346         assert_eq!(spend_txn.len(), 1);
4347         assert_eq!(spend_txn[0].input.len(), 1);
4348         check_spends!(spend_txn[0], node_txn[0]);
4349         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4350 }
4351
4352 #[test]
4353 fn test_claim_on_remote_sizeable_push_msat() {
4354         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4355         // to_remote output is encumbered by a P2WPKH
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, 100_000, 98_000_000);
4362         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4363         check_closed_broadcast!(nodes[0], true);
4364         check_added_monitors!(nodes[0], 1);
4365         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4366
4367         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4368         assert_eq!(node_txn.len(), 1);
4369         check_spends!(node_txn[0], chan.3);
4370         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
4371
4372         mine_transaction(&nodes[1], &node_txn[0]);
4373         check_closed_broadcast!(nodes[1], true);
4374         check_added_monitors!(nodes[1], 1);
4375         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4376         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4377
4378         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4379         assert_eq!(spend_txn.len(), 1);
4380         check_spends!(spend_txn[0], node_txn[0]);
4381 }
4382
4383 #[test]
4384 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4385         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4386         // to_remote output is encumbered by a P2WPKH
4387
4388         let chanmon_cfgs = create_chanmon_cfgs(2);
4389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4391         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4392
4393         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4394         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4395         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4396         assert_eq!(revoked_local_txn[0].input.len(), 1);
4397         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4398
4399         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4400         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4401         check_closed_broadcast!(nodes[1], true);
4402         check_added_monitors!(nodes[1], 1);
4403         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4404
4405         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4406         mine_transaction(&nodes[1], &node_txn[0]);
4407         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4408
4409         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4410         assert_eq!(spend_txn.len(), 3);
4411         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4412         check_spends!(spend_txn[1], node_txn[0]);
4413         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4414 }
4415
4416 #[test]
4417 fn test_static_spendable_outputs_preimage_tx() {
4418         let chanmon_cfgs = create_chanmon_cfgs(2);
4419         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4420         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4421         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4422
4423         // Create some initial channels
4424         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4425
4426         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4427
4428         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4429         assert_eq!(commitment_tx[0].input.len(), 1);
4430         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4431
4432         // Settle A's commitment tx on B's chain
4433         nodes[1].node.claim_funds(payment_preimage);
4434         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4435         check_added_monitors!(nodes[1], 1);
4436         mine_transaction(&nodes[1], &commitment_tx[0]);
4437         check_added_monitors!(nodes[1], 1);
4438         let events = nodes[1].node.get_and_clear_pending_msg_events();
4439         match events[0] {
4440                 MessageSendEvent::UpdateHTLCs { .. } => {},
4441                 _ => panic!("Unexpected event"),
4442         }
4443         match events[1] {
4444                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4445                 _ => panic!("Unexepected event"),
4446         }
4447
4448         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4449         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4450         assert_eq!(node_txn.len(), 1);
4451         check_spends!(node_txn[0], commitment_tx[0]);
4452         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4453
4454         mine_transaction(&nodes[1], &node_txn[0]);
4455         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4456         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4457
4458         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4459         assert_eq!(spend_txn.len(), 1);
4460         check_spends!(spend_txn[0], node_txn[0]);
4461 }
4462
4463 #[test]
4464 fn test_static_spendable_outputs_timeout_tx() {
4465         let chanmon_cfgs = create_chanmon_cfgs(2);
4466         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4467         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4468         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4469
4470         // Create some initial channels
4471         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4472
4473         // Rebalance the network a bit by relaying one payment through all the channels ...
4474         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4475
4476         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4477
4478         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4479         assert_eq!(commitment_tx[0].input.len(), 1);
4480         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4481
4482         // Settle A's commitment tx on B' chain
4483         mine_transaction(&nodes[1], &commitment_tx[0]);
4484         check_added_monitors!(nodes[1], 1);
4485         let events = nodes[1].node.get_and_clear_pending_msg_events();
4486         match events[0] {
4487                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4488                 _ => panic!("Unexpected event"),
4489         }
4490         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4491
4492         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4493         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4494         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4495         check_spends!(node_txn[0],  commitment_tx[0].clone());
4496         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4497
4498         mine_transaction(&nodes[1], &node_txn[0]);
4499         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4500         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4501         expect_payment_failed!(nodes[1], our_payment_hash, false);
4502
4503         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4504         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4505         check_spends!(spend_txn[0], commitment_tx[0]);
4506         check_spends!(spend_txn[1], node_txn[0]);
4507         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4508 }
4509
4510 #[test]
4511 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4512         let chanmon_cfgs = create_chanmon_cfgs(2);
4513         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4514         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4515         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4516
4517         // Create some initial channels
4518         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4519
4520         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4521         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4522         assert_eq!(revoked_local_txn[0].input.len(), 1);
4523         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4524
4525         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4526
4527         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4528         check_closed_broadcast!(nodes[1], true);
4529         check_added_monitors!(nodes[1], 1);
4530         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4531
4532         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4533         assert_eq!(node_txn.len(), 1);
4534         assert_eq!(node_txn[0].input.len(), 2);
4535         check_spends!(node_txn[0], revoked_local_txn[0]);
4536
4537         mine_transaction(&nodes[1], &node_txn[0]);
4538         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4539
4540         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4541         assert_eq!(spend_txn.len(), 1);
4542         check_spends!(spend_txn[0], node_txn[0]);
4543 }
4544
4545 #[test]
4546 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4547         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4548         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4549         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4550         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4551         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4552
4553         // Create some initial channels
4554         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4555
4556         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4557         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4558         assert_eq!(revoked_local_txn[0].input.len(), 1);
4559         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4560
4561         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4562
4563         // A will generate HTLC-Timeout from revoked commitment tx
4564         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4565         check_closed_broadcast!(nodes[0], true);
4566         check_added_monitors!(nodes[0], 1);
4567         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4568         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4569
4570         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4571         assert_eq!(revoked_htlc_txn.len(), 1);
4572         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4573         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4574         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4575         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4576
4577         // B will generate justice tx from A's revoked commitment/HTLC tx
4578         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4579         check_closed_broadcast!(nodes[1], true);
4580         check_added_monitors!(nodes[1], 1);
4581         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4582
4583         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4584         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4585         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4586         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4587         // transactions next...
4588         assert_eq!(node_txn[0].input.len(), 3);
4589         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4590
4591         assert_eq!(node_txn[1].input.len(), 2);
4592         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4593         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4594                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4595         } else {
4596                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4597                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4598         }
4599
4600         mine_transaction(&nodes[1], &node_txn[1]);
4601         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4602
4603         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4604         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4605         assert_eq!(spend_txn.len(), 1);
4606         assert_eq!(spend_txn[0].input.len(), 1);
4607         check_spends!(spend_txn[0], node_txn[1]);
4608 }
4609
4610 #[test]
4611 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4612         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4613         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4614         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4615         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4616         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4617
4618         // Create some initial channels
4619         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4620
4621         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4622         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4623         assert_eq!(revoked_local_txn[0].input.len(), 1);
4624         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4625
4626         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4627         assert_eq!(revoked_local_txn[0].output.len(), 2);
4628
4629         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4630
4631         // B will generate HTLC-Success from revoked commitment tx
4632         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4633         check_closed_broadcast!(nodes[1], true);
4634         check_added_monitors!(nodes[1], 1);
4635         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4636         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4637
4638         assert_eq!(revoked_htlc_txn.len(), 1);
4639         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4640         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4641         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4642
4643         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4644         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4645         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4646
4647         // A will generate justice tx from B's revoked commitment/HTLC tx
4648         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4649         check_closed_broadcast!(nodes[0], true);
4650         check_added_monitors!(nodes[0], 1);
4651         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4652
4653         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4654         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4655
4656         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4657         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4658         // transactions next...
4659         assert_eq!(node_txn[0].input.len(), 2);
4660         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4661         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4662                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4663         } else {
4664                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4665                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4666         }
4667
4668         assert_eq!(node_txn[1].input.len(), 1);
4669         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4670
4671         mine_transaction(&nodes[0], &node_txn[1]);
4672         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4673
4674         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4675         // didn't try to generate any new transactions.
4676
4677         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4678         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4679         assert_eq!(spend_txn.len(), 3);
4680         assert_eq!(spend_txn[0].input.len(), 1);
4681         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4682         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4683         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4684         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4685 }
4686
4687 #[test]
4688 fn test_onchain_to_onchain_claim() {
4689         // Test that in case of channel closure, we detect the state of output and claim HTLC
4690         // on downstream peer's remote commitment tx.
4691         // First, have C claim an HTLC against its own latest commitment transaction.
4692         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4693         // channel.
4694         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4695         // gets broadcast.
4696
4697         let chanmon_cfgs = create_chanmon_cfgs(3);
4698         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4699         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4700         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4701
4702         // Create some initial channels
4703         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4704         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4705
4706         // Ensure all nodes are at the same height
4707         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4708         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4709         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4710         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4711
4712         // Rebalance the network a bit by relaying one payment through all the channels ...
4713         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4714         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4715
4716         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4717         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4718         check_spends!(commitment_tx[0], chan_2.3);
4719         nodes[2].node.claim_funds(payment_preimage);
4720         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4721         check_added_monitors!(nodes[2], 1);
4722         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4723         assert!(updates.update_add_htlcs.is_empty());
4724         assert!(updates.update_fail_htlcs.is_empty());
4725         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4726         assert!(updates.update_fail_malformed_htlcs.is_empty());
4727
4728         mine_transaction(&nodes[2], &commitment_tx[0]);
4729         check_closed_broadcast!(nodes[2], true);
4730         check_added_monitors!(nodes[2], 1);
4731         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4732
4733         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4734         assert_eq!(c_txn.len(), 1);
4735         check_spends!(c_txn[0], commitment_tx[0]);
4736         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4737         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4738         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4739
4740         // 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
4741         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4742         check_added_monitors!(nodes[1], 1);
4743         let events = nodes[1].node.get_and_clear_pending_events();
4744         assert_eq!(events.len(), 2);
4745         match events[0] {
4746                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4747                 _ => panic!("Unexpected event"),
4748         }
4749         match events[1] {
4750                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4751                         assert_eq!(fee_earned_msat, Some(1000));
4752                         assert_eq!(prev_channel_id, Some(chan_1.2));
4753                         assert_eq!(claim_from_onchain_tx, true);
4754                         assert_eq!(next_channel_id, Some(chan_2.2));
4755                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4756                 },
4757                 _ => panic!("Unexpected event"),
4758         }
4759         check_added_monitors!(nodes[1], 1);
4760         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4761         assert_eq!(msg_events.len(), 3);
4762         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4763         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4764
4765         match nodes_2_event {
4766                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4767                 _ => panic!("Unexpected event"),
4768         }
4769
4770         match nodes_0_event {
4771                 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, .. } } => {
4772                         assert!(update_add_htlcs.is_empty());
4773                         assert!(update_fail_htlcs.is_empty());
4774                         assert_eq!(update_fulfill_htlcs.len(), 1);
4775                         assert!(update_fail_malformed_htlcs.is_empty());
4776                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4777                 },
4778                 _ => panic!("Unexpected event"),
4779         };
4780
4781         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4782         match msg_events[0] {
4783                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4784                 _ => panic!("Unexpected event"),
4785         }
4786
4787         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4788         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4789         mine_transaction(&nodes[1], &commitment_tx[0]);
4790         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4791         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4792         // ChannelMonitor: HTLC-Success tx
4793         assert_eq!(b_txn.len(), 1);
4794         check_spends!(b_txn[0], commitment_tx[0]);
4795         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4796         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4797         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4798
4799         check_closed_broadcast!(nodes[1], true);
4800         check_added_monitors!(nodes[1], 1);
4801 }
4802
4803 #[test]
4804 fn test_duplicate_payment_hash_one_failure_one_success() {
4805         // Topology : A --> B --> C --> D
4806         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4807         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4808         // we forward one of the payments onwards to D.
4809         let chanmon_cfgs = create_chanmon_cfgs(4);
4810         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4811         // When this test was written, the default base fee floated based on the HTLC count.
4812         // It is now fixed, so we simply set the fee to the expected value here.
4813         let mut config = test_default_channel_config();
4814         config.channel_config.forwarding_fee_base_msat = 196;
4815         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4816                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4817         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4818
4819         create_announced_chan_between_nodes(&nodes, 0, 1);
4820         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4821         create_announced_chan_between_nodes(&nodes, 2, 3);
4822
4823         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4824         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4825         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4826         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4827         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4828
4829         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4830
4831         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4832         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4833         // script push size limit so that the below script length checks match
4834         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4835         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4836                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4837         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4838         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4839
4840         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4841         assert_eq!(commitment_txn[0].input.len(), 1);
4842         check_spends!(commitment_txn[0], chan_2.3);
4843
4844         mine_transaction(&nodes[1], &commitment_txn[0]);
4845         check_closed_broadcast!(nodes[1], true);
4846         check_added_monitors!(nodes[1], 1);
4847         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4848         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4849
4850         let htlc_timeout_tx;
4851         { // Extract one of the two HTLC-Timeout transaction
4852                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4853                 // ChannelMonitor: timeout tx * 2-or-3
4854                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4855
4856                 check_spends!(node_txn[0], commitment_txn[0]);
4857                 assert_eq!(node_txn[0].input.len(), 1);
4858                 assert_eq!(node_txn[0].output.len(), 1);
4859
4860                 if node_txn.len() > 2 {
4861                         check_spends!(node_txn[1], commitment_txn[0]);
4862                         assert_eq!(node_txn[1].input.len(), 1);
4863                         assert_eq!(node_txn[1].output.len(), 1);
4864                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4865
4866                         check_spends!(node_txn[2], commitment_txn[0]);
4867                         assert_eq!(node_txn[2].input.len(), 1);
4868                         assert_eq!(node_txn[2].output.len(), 1);
4869                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4870                 } else {
4871                         check_spends!(node_txn[1], commitment_txn[0]);
4872                         assert_eq!(node_txn[1].input.len(), 1);
4873                         assert_eq!(node_txn[1].output.len(), 1);
4874                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4875                 }
4876
4877                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4878                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4879                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4880                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4881                 if node_txn.len() > 2 {
4882                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4883                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4884                 } else {
4885                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4886                 }
4887         }
4888
4889         nodes[2].node.claim_funds(our_payment_preimage);
4890         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4891
4892         mine_transaction(&nodes[2], &commitment_txn[0]);
4893         check_added_monitors!(nodes[2], 2);
4894         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4895         let events = nodes[2].node.get_and_clear_pending_msg_events();
4896         match events[0] {
4897                 MessageSendEvent::UpdateHTLCs { .. } => {},
4898                 _ => panic!("Unexpected event"),
4899         }
4900         match events[1] {
4901                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4902                 _ => panic!("Unexepected event"),
4903         }
4904         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4905         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4906         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4907         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4908         assert_eq!(htlc_success_txn[0].input.len(), 1);
4909         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4910         assert_eq!(htlc_success_txn[1].input.len(), 1);
4911         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4912         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4913         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4914
4915         mine_transaction(&nodes[1], &htlc_timeout_tx);
4916         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4917         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 }]);
4918         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4919         assert!(htlc_updates.update_add_htlcs.is_empty());
4920         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4921         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4922         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4923         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4924         check_added_monitors!(nodes[1], 1);
4925
4926         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4927         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4928         {
4929                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4930         }
4931         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4932
4933         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4934         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4935         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4936         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4937         assert!(updates.update_add_htlcs.is_empty());
4938         assert!(updates.update_fail_htlcs.is_empty());
4939         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4940         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4941         assert!(updates.update_fail_malformed_htlcs.is_empty());
4942         check_added_monitors!(nodes[1], 1);
4943
4944         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4945         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4946         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4947 }
4948
4949 #[test]
4950 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4951         let chanmon_cfgs = create_chanmon_cfgs(2);
4952         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4953         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4954         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4955
4956         // Create some initial channels
4957         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4958
4959         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4960         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4961         assert_eq!(local_txn.len(), 1);
4962         assert_eq!(local_txn[0].input.len(), 1);
4963         check_spends!(local_txn[0], chan_1.3);
4964
4965         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4966         nodes[1].node.claim_funds(payment_preimage);
4967         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4968         check_added_monitors!(nodes[1], 1);
4969
4970         mine_transaction(&nodes[1], &local_txn[0]);
4971         check_added_monitors!(nodes[1], 1);
4972         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4973         let events = nodes[1].node.get_and_clear_pending_msg_events();
4974         match events[0] {
4975                 MessageSendEvent::UpdateHTLCs { .. } => {},
4976                 _ => panic!("Unexpected event"),
4977         }
4978         match events[1] {
4979                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4980                 _ => panic!("Unexepected event"),
4981         }
4982         let node_tx = {
4983                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4984                 assert_eq!(node_txn.len(), 1);
4985                 assert_eq!(node_txn[0].input.len(), 1);
4986                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4987                 check_spends!(node_txn[0], local_txn[0]);
4988                 node_txn[0].clone()
4989         };
4990
4991         mine_transaction(&nodes[1], &node_tx);
4992         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4993
4994         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4995         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4996         assert_eq!(spend_txn.len(), 1);
4997         assert_eq!(spend_txn[0].input.len(), 1);
4998         check_spends!(spend_txn[0], node_tx);
4999         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5000 }
5001
5002 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5003         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5004         // unrevoked commitment transaction.
5005         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5006         // a remote RAA before they could be failed backwards (and combinations thereof).
5007         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5008         // use the same payment hashes.
5009         // Thus, we use a six-node network:
5010         //
5011         // A \         / E
5012         //    - C - D -
5013         // B /         \ F
5014         // And test where C fails back to A/B when D announces its latest commitment transaction
5015         let chanmon_cfgs = create_chanmon_cfgs(6);
5016         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5017         // When this test was written, the default base fee floated based on the HTLC count.
5018         // It is now fixed, so we simply set the fee to the expected value here.
5019         let mut config = test_default_channel_config();
5020         config.channel_config.forwarding_fee_base_msat = 196;
5021         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5022                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5023         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5024
5025         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5026         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5027         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5028         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5029         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5030
5031         // Rebalance and check output sanity...
5032         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5033         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5034         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5035
5036         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5037                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5038         // 0th HTLC:
5039         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
5040         // 1st HTLC:
5041         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
5042         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5043         // 2nd HTLC:
5044         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
5045         // 3rd HTLC:
5046         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
5047         // 4th HTLC:
5048         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5049         // 5th HTLC:
5050         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5051         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5052         // 6th HTLC:
5053         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());
5054         // 7th HTLC:
5055         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());
5056
5057         // 8th HTLC:
5058         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5059         // 9th HTLC:
5060         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5061         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
5062
5063         // 10th HTLC:
5064         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
5065         // 11th HTLC:
5066         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5067         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());
5068
5069         // Double-check that six of the new HTLC were added
5070         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5071         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5072         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5073         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5074
5075         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5076         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5077         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5078         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5079         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5080         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5081         check_added_monitors!(nodes[4], 0);
5082
5083         let failed_destinations = vec![
5084                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5085                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5086                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5087                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5088         ];
5089         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5090         check_added_monitors!(nodes[4], 1);
5091
5092         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5093         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5094         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5095         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5096         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5097         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5098
5099         // Fail 3rd below-dust and 7th above-dust HTLCs
5100         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5101         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5102         check_added_monitors!(nodes[5], 0);
5103
5104         let failed_destinations_2 = vec![
5105                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5106                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5107         ];
5108         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5109         check_added_monitors!(nodes[5], 1);
5110
5111         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5112         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5113         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5114         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5115
5116         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5117
5118         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5119         let failed_destinations_3 = vec![
5120                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5121                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5122                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5123                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5124                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5125                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5126         ];
5127         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5128         check_added_monitors!(nodes[3], 1);
5129         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5130         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5131         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5132         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5133         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5134         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5135         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5136         if deliver_last_raa {
5137                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5138         } else {
5139                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5140         }
5141
5142         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5143         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5144         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5145         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5146         //
5147         // We now broadcast the latest commitment transaction, which *should* result in failures for
5148         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5149         // the non-broadcast above-dust HTLCs.
5150         //
5151         // Alternatively, we may broadcast the previous commitment transaction, which should only
5152         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5153         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5154
5155         if announce_latest {
5156                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5157         } else {
5158                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5159         }
5160         let events = nodes[2].node.get_and_clear_pending_events();
5161         let close_event = if deliver_last_raa {
5162                 assert_eq!(events.len(), 2 + 6);
5163                 events.last().clone().unwrap()
5164         } else {
5165                 assert_eq!(events.len(), 1);
5166                 events.last().clone().unwrap()
5167         };
5168         match close_event {
5169                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5170                 _ => panic!("Unexpected event"),
5171         }
5172
5173         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5174         check_closed_broadcast!(nodes[2], true);
5175         if deliver_last_raa {
5176                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5177
5178                 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();
5179                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5180         } else {
5181                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5182                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5183                 } else {
5184                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5185                 };
5186
5187                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5188         }
5189         check_added_monitors!(nodes[2], 3);
5190
5191         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5192         assert_eq!(cs_msgs.len(), 2);
5193         let mut a_done = false;
5194         for msg in cs_msgs {
5195                 match msg {
5196                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5197                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5198                                 // should be failed-backwards here.
5199                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5200                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5201                                         for htlc in &updates.update_fail_htlcs {
5202                                                 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 });
5203                                         }
5204                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5205                                         assert!(!a_done);
5206                                         a_done = true;
5207                                         &nodes[0]
5208                                 } else {
5209                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5210                                         for htlc in &updates.update_fail_htlcs {
5211                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5212                                         }
5213                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5214                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5215                                         &nodes[1]
5216                                 };
5217                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5218                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5219                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5220                                 if announce_latest {
5221                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5222                                         if *node_id == nodes[0].node.get_our_node_id() {
5223                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5224                                         }
5225                                 }
5226                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5227                         },
5228                         _ => panic!("Unexpected event"),
5229                 }
5230         }
5231
5232         let as_events = nodes[0].node.get_and_clear_pending_events();
5233         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5234         let mut as_failds = HashSet::new();
5235         let mut as_updates = 0;
5236         for event in as_events.iter() {
5237                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5238                         assert!(as_failds.insert(*payment_hash));
5239                         if *payment_hash != payment_hash_2 {
5240                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5241                         } else {
5242                                 assert!(!payment_failed_permanently);
5243                         }
5244                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5245                                 as_updates += 1;
5246                         }
5247                 } else if let &Event::PaymentFailed { .. } = event {
5248                 } else { panic!("Unexpected event"); }
5249         }
5250         assert!(as_failds.contains(&payment_hash_1));
5251         assert!(as_failds.contains(&payment_hash_2));
5252         if announce_latest {
5253                 assert!(as_failds.contains(&payment_hash_3));
5254                 assert!(as_failds.contains(&payment_hash_5));
5255         }
5256         assert!(as_failds.contains(&payment_hash_6));
5257
5258         let bs_events = nodes[1].node.get_and_clear_pending_events();
5259         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5260         let mut bs_failds = HashSet::new();
5261         let mut bs_updates = 0;
5262         for event in bs_events.iter() {
5263                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5264                         assert!(bs_failds.insert(*payment_hash));
5265                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5266                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5267                         } else {
5268                                 assert!(!payment_failed_permanently);
5269                         }
5270                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5271                                 bs_updates += 1;
5272                         }
5273                 } else if let &Event::PaymentFailed { .. } = event {
5274                 } else { panic!("Unexpected event"); }
5275         }
5276         assert!(bs_failds.contains(&payment_hash_1));
5277         assert!(bs_failds.contains(&payment_hash_2));
5278         if announce_latest {
5279                 assert!(bs_failds.contains(&payment_hash_4));
5280         }
5281         assert!(bs_failds.contains(&payment_hash_5));
5282
5283         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5284         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5285         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5286         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5287         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5288         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5289 }
5290
5291 #[test]
5292 fn test_fail_backwards_latest_remote_announce_a() {
5293         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5294 }
5295
5296 #[test]
5297 fn test_fail_backwards_latest_remote_announce_b() {
5298         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5299 }
5300
5301 #[test]
5302 fn test_fail_backwards_previous_remote_announce() {
5303         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5304         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5305         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5306 }
5307
5308 #[test]
5309 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5310         let chanmon_cfgs = create_chanmon_cfgs(2);
5311         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5312         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5313         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5314
5315         // Create some initial channels
5316         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5317
5318         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5319         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5320         assert_eq!(local_txn[0].input.len(), 1);
5321         check_spends!(local_txn[0], chan_1.3);
5322
5323         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5324         mine_transaction(&nodes[0], &local_txn[0]);
5325         check_closed_broadcast!(nodes[0], true);
5326         check_added_monitors!(nodes[0], 1);
5327         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5328         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5329
5330         let htlc_timeout = {
5331                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5332                 assert_eq!(node_txn.len(), 1);
5333                 assert_eq!(node_txn[0].input.len(), 1);
5334                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5335                 check_spends!(node_txn[0], local_txn[0]);
5336                 node_txn[0].clone()
5337         };
5338
5339         mine_transaction(&nodes[0], &htlc_timeout);
5340         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5341         expect_payment_failed!(nodes[0], our_payment_hash, false);
5342
5343         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5344         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5345         assert_eq!(spend_txn.len(), 3);
5346         check_spends!(spend_txn[0], local_txn[0]);
5347         assert_eq!(spend_txn[1].input.len(), 1);
5348         check_spends!(spend_txn[1], htlc_timeout);
5349         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5350         assert_eq!(spend_txn[2].input.len(), 2);
5351         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5352         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5353                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5354 }
5355
5356 #[test]
5357 fn test_key_derivation_params() {
5358         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5359         // manager rotation to test that `channel_keys_id` returned in
5360         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5361         // then derive a `delayed_payment_key`.
5362
5363         let chanmon_cfgs = create_chanmon_cfgs(3);
5364
5365         // We manually create the node configuration to backup the seed.
5366         let seed = [42; 32];
5367         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5368         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);
5369         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5370         let scorer = Mutex::new(test_utils::TestScorer::new());
5371         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5372         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)) };
5373         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5374         node_cfgs.remove(0);
5375         node_cfgs.insert(0, node);
5376
5377         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5378         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5379
5380         // Create some initial channels
5381         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5382         // for node 0
5383         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5384         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5385         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5386
5387         // Ensure all nodes are at the same height
5388         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5389         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5390         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5391         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5392
5393         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5394         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5395         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5396         assert_eq!(local_txn_1[0].input.len(), 1);
5397         check_spends!(local_txn_1[0], chan_1.3);
5398
5399         // We check funding pubkey are unique
5400         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]));
5401         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]));
5402         if from_0_funding_key_0 == from_1_funding_key_0
5403             || from_0_funding_key_0 == from_1_funding_key_1
5404             || from_0_funding_key_1 == from_1_funding_key_0
5405             || from_0_funding_key_1 == from_1_funding_key_1 {
5406                 panic!("Funding pubkeys aren't unique");
5407         }
5408
5409         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5410         mine_transaction(&nodes[0], &local_txn_1[0]);
5411         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5412         check_closed_broadcast!(nodes[0], true);
5413         check_added_monitors!(nodes[0], 1);
5414         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5415
5416         let htlc_timeout = {
5417                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5418                 assert_eq!(node_txn.len(), 1);
5419                 assert_eq!(node_txn[0].input.len(), 1);
5420                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5421                 check_spends!(node_txn[0], local_txn_1[0]);
5422                 node_txn[0].clone()
5423         };
5424
5425         mine_transaction(&nodes[0], &htlc_timeout);
5426         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5427         expect_payment_failed!(nodes[0], our_payment_hash, false);
5428
5429         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5430         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5431         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5432         assert_eq!(spend_txn.len(), 3);
5433         check_spends!(spend_txn[0], local_txn_1[0]);
5434         assert_eq!(spend_txn[1].input.len(), 1);
5435         check_spends!(spend_txn[1], htlc_timeout);
5436         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5437         assert_eq!(spend_txn[2].input.len(), 2);
5438         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5439         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5440                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5441 }
5442
5443 #[test]
5444 fn test_static_output_closing_tx() {
5445         let chanmon_cfgs = create_chanmon_cfgs(2);
5446         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5447         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5448         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5449
5450         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5451
5452         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5453         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5454
5455         mine_transaction(&nodes[0], &closing_tx);
5456         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5457         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5458
5459         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5460         assert_eq!(spend_txn.len(), 1);
5461         check_spends!(spend_txn[0], closing_tx);
5462
5463         mine_transaction(&nodes[1], &closing_tx);
5464         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5465         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5466
5467         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5468         assert_eq!(spend_txn.len(), 1);
5469         check_spends!(spend_txn[0], closing_tx);
5470 }
5471
5472 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5473         let chanmon_cfgs = create_chanmon_cfgs(2);
5474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5476         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5477         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5478
5479         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5480
5481         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5482         // present in B's local commitment transaction, but none of A's commitment transactions.
5483         nodes[1].node.claim_funds(payment_preimage);
5484         check_added_monitors!(nodes[1], 1);
5485         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5486
5487         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5488         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5489         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5490
5491         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5492         check_added_monitors!(nodes[0], 1);
5493         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5494         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5495         check_added_monitors!(nodes[1], 1);
5496
5497         let starting_block = nodes[1].best_block_info();
5498         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5499         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5500                 connect_block(&nodes[1], &block);
5501                 block.header.prev_blockhash = block.block_hash();
5502         }
5503         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5504         check_closed_broadcast!(nodes[1], true);
5505         check_added_monitors!(nodes[1], 1);
5506         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5507 }
5508
5509 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5510         let chanmon_cfgs = create_chanmon_cfgs(2);
5511         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5512         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5513         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5514         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5515
5516         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5517         nodes[0].node.send_payment_with_route(&route, payment_hash,
5518                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5519         check_added_monitors!(nodes[0], 1);
5520
5521         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5522
5523         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5524         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5525         // to "time out" the HTLC.
5526
5527         let starting_block = nodes[1].best_block_info();
5528         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5529
5530         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5531                 connect_block(&nodes[0], &block);
5532                 block.header.prev_blockhash = block.block_hash();
5533         }
5534         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5535         check_closed_broadcast!(nodes[0], true);
5536         check_added_monitors!(nodes[0], 1);
5537         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5538 }
5539
5540 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5541         let chanmon_cfgs = create_chanmon_cfgs(3);
5542         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5543         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5544         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5545         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5546
5547         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5548         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5549         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5550         // actually revoked.
5551         let htlc_value = if use_dust { 50000 } else { 3000000 };
5552         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5553         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5554         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5555         check_added_monitors!(nodes[1], 1);
5556
5557         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5558         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5559         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5560         check_added_monitors!(nodes[0], 1);
5561         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5562         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5563         check_added_monitors!(nodes[1], 1);
5564         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5565         check_added_monitors!(nodes[1], 1);
5566         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5567
5568         if check_revoke_no_close {
5569                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5570                 check_added_monitors!(nodes[0], 1);
5571         }
5572
5573         let starting_block = nodes[1].best_block_info();
5574         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5575         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5576                 connect_block(&nodes[0], &block);
5577                 block.header.prev_blockhash = block.block_hash();
5578         }
5579         if !check_revoke_no_close {
5580                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5581                 check_closed_broadcast!(nodes[0], true);
5582                 check_added_monitors!(nodes[0], 1);
5583                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5584         } else {
5585                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5586         }
5587 }
5588
5589 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5590 // There are only a few cases to test here:
5591 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5592 //    broadcastable commitment transactions result in channel closure,
5593 //  * its included in an unrevoked-but-previous remote commitment transaction,
5594 //  * its included in the latest remote or local commitment transactions.
5595 // We test each of the three possible commitment transactions individually and use both dust and
5596 // non-dust HTLCs.
5597 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5598 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5599 // tested for at least one of the cases in other tests.
5600 #[test]
5601 fn htlc_claim_single_commitment_only_a() {
5602         do_htlc_claim_local_commitment_only(true);
5603         do_htlc_claim_local_commitment_only(false);
5604
5605         do_htlc_claim_current_remote_commitment_only(true);
5606         do_htlc_claim_current_remote_commitment_only(false);
5607 }
5608
5609 #[test]
5610 fn htlc_claim_single_commitment_only_b() {
5611         do_htlc_claim_previous_remote_commitment_only(true, false);
5612         do_htlc_claim_previous_remote_commitment_only(false, false);
5613         do_htlc_claim_previous_remote_commitment_only(true, true);
5614         do_htlc_claim_previous_remote_commitment_only(false, true);
5615 }
5616
5617 #[test]
5618 #[should_panic]
5619 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5620         let chanmon_cfgs = create_chanmon_cfgs(2);
5621         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5622         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5623         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5624         // Force duplicate randomness for every get-random call
5625         for node in nodes.iter() {
5626                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5627         }
5628
5629         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5630         let channel_value_satoshis=10000;
5631         let push_msat=10001;
5632         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5633         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5634         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5635         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5636
5637         // Create a second channel with the same random values. This used to panic due to a colliding
5638         // channel_id, but now panics due to a colliding outbound SCID alias.
5639         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5640 }
5641
5642 #[test]
5643 fn bolt2_open_channel_sending_node_checks_part2() {
5644         let chanmon_cfgs = create_chanmon_cfgs(2);
5645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5647         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5648
5649         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5650         let channel_value_satoshis=2^24;
5651         let push_msat=10001;
5652         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5653
5654         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5655         let channel_value_satoshis=10000;
5656         // Test when push_msat is equal to 1000 * funding_satoshis.
5657         let push_msat=1000*channel_value_satoshis+1;
5658         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5659
5660         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5661         let channel_value_satoshis=10000;
5662         let push_msat=10001;
5663         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
5664         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5665         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5666
5667         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5668         // 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
5669         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5670
5671         // 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.
5672         assert!(BREAKDOWN_TIMEOUT>0);
5673         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5674
5675         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5676         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5677         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5678
5679         // 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.
5680         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5681         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5682         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5683         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5684         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5685 }
5686
5687 #[test]
5688 fn bolt2_open_channel_sane_dust_limit() {
5689         let chanmon_cfgs = create_chanmon_cfgs(2);
5690         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5691         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5692         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5693
5694         let channel_value_satoshis=1000000;
5695         let push_msat=10001;
5696         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5697         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5698         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5699         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5700
5701         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5702         let events = nodes[1].node.get_and_clear_pending_msg_events();
5703         let err_msg = match events[0] {
5704                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5705                         msg.clone()
5706                 },
5707                 _ => panic!("Unexpected event"),
5708         };
5709         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5710 }
5711
5712 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5713 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5714 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5715 // is no longer affordable once it's freed.
5716 #[test]
5717 fn test_fail_holding_cell_htlc_upon_free() {
5718         let chanmon_cfgs = create_chanmon_cfgs(2);
5719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5721         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5722         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5723
5724         // First nodes[0] generates an update_fee, setting the channel's
5725         // pending_update_fee.
5726         {
5727                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5728                 *feerate_lock += 20;
5729         }
5730         nodes[0].node.timer_tick_occurred();
5731         check_added_monitors!(nodes[0], 1);
5732
5733         let events = nodes[0].node.get_and_clear_pending_msg_events();
5734         assert_eq!(events.len(), 1);
5735         let (update_msg, commitment_signed) = match events[0] {
5736                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5737                         (update_fee.as_ref(), commitment_signed)
5738                 },
5739                 _ => panic!("Unexpected event"),
5740         };
5741
5742         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5743
5744         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5745         let channel_reserve = chan_stat.channel_reserve_msat;
5746         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5747         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5748
5749         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5750         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5751         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5752
5753         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5754         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5755                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5756         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5757         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5758
5759         // Flush the pending fee update.
5760         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5761         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5762         check_added_monitors!(nodes[1], 1);
5763         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5764         check_added_monitors!(nodes[0], 1);
5765
5766         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5767         // HTLC, but now that the fee has been raised the payment will now fail, causing
5768         // us to surface its failure to the user.
5769         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5770         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5771         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);
5772
5773         // Check that the payment failed to be sent out.
5774         let events = nodes[0].node.get_and_clear_pending_events();
5775         assert_eq!(events.len(), 2);
5776         match &events[0] {
5777                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5778                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5779                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5780                         assert_eq!(*payment_failed_permanently, false);
5781                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5782                 },
5783                 _ => panic!("Unexpected event"),
5784         }
5785         match &events[1] {
5786                 &Event::PaymentFailed { ref payment_hash, .. } => {
5787                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5788                 },
5789                 _ => panic!("Unexpected event"),
5790         }
5791 }
5792
5793 // Test that if multiple HTLCs are released from the holding cell and one is
5794 // valid but the other is no longer valid upon release, the valid HTLC can be
5795 // successfully completed while the other one fails as expected.
5796 #[test]
5797 fn test_free_and_fail_holding_cell_htlcs() {
5798         let chanmon_cfgs = create_chanmon_cfgs(2);
5799         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5800         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5801         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5802         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5803
5804         // First nodes[0] generates an update_fee, setting the channel's
5805         // pending_update_fee.
5806         {
5807                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5808                 *feerate_lock += 200;
5809         }
5810         nodes[0].node.timer_tick_occurred();
5811         check_added_monitors!(nodes[0], 1);
5812
5813         let events = nodes[0].node.get_and_clear_pending_msg_events();
5814         assert_eq!(events.len(), 1);
5815         let (update_msg, commitment_signed) = match events[0] {
5816                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5817                         (update_fee.as_ref(), commitment_signed)
5818                 },
5819                 _ => panic!("Unexpected event"),
5820         };
5821
5822         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5823
5824         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5825         let channel_reserve = chan_stat.channel_reserve_msat;
5826         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5827         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5828
5829         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5830         let amt_1 = 20000;
5831         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5832         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5833         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5834
5835         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5836         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5837                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5838         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5839         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5840         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5841         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5842                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5843         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5844         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5845
5846         // Flush the pending fee update.
5847         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5848         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5849         check_added_monitors!(nodes[1], 1);
5850         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5851         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5852         check_added_monitors!(nodes[0], 2);
5853
5854         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5855         // but now that the fee has been raised the second payment will now fail, causing us
5856         // to surface its failure to the user. The first payment should succeed.
5857         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5858         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5859         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);
5860
5861         // Check that the second payment failed to be sent out.
5862         let events = nodes[0].node.get_and_clear_pending_events();
5863         assert_eq!(events.len(), 2);
5864         match &events[0] {
5865                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5866                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5867                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5868                         assert_eq!(*payment_failed_permanently, false);
5869                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5870                 },
5871                 _ => panic!("Unexpected event"),
5872         }
5873         match &events[1] {
5874                 &Event::PaymentFailed { ref payment_hash, .. } => {
5875                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5876                 },
5877                 _ => panic!("Unexpected event"),
5878         }
5879
5880         // Complete the first payment and the RAA from the fee update.
5881         let (payment_event, send_raa_event) = {
5882                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5883                 assert_eq!(msgs.len(), 2);
5884                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5885         };
5886         let raa = match send_raa_event {
5887                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5888                 _ => panic!("Unexpected event"),
5889         };
5890         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5891         check_added_monitors!(nodes[1], 1);
5892         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5893         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5894         let events = nodes[1].node.get_and_clear_pending_events();
5895         assert_eq!(events.len(), 1);
5896         match events[0] {
5897                 Event::PendingHTLCsForwardable { .. } => {},
5898                 _ => panic!("Unexpected event"),
5899         }
5900         nodes[1].node.process_pending_htlc_forwards();
5901         let events = nodes[1].node.get_and_clear_pending_events();
5902         assert_eq!(events.len(), 1);
5903         match events[0] {
5904                 Event::PaymentClaimable { .. } => {},
5905                 _ => panic!("Unexpected event"),
5906         }
5907         nodes[1].node.claim_funds(payment_preimage_1);
5908         check_added_monitors!(nodes[1], 1);
5909         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5910
5911         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5912         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5913         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5914         expect_payment_sent!(nodes[0], payment_preimage_1);
5915 }
5916
5917 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5918 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5919 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5920 // once it's freed.
5921 #[test]
5922 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5923         let chanmon_cfgs = create_chanmon_cfgs(3);
5924         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5925         // Avoid having to include routing fees in calculations
5926         let mut config = test_default_channel_config();
5927         config.channel_config.forwarding_fee_base_msat = 0;
5928         config.channel_config.forwarding_fee_proportional_millionths = 0;
5929         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5930         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5931         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5932         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5933
5934         // First nodes[1] generates an update_fee, setting the channel's
5935         // pending_update_fee.
5936         {
5937                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5938                 *feerate_lock += 20;
5939         }
5940         nodes[1].node.timer_tick_occurred();
5941         check_added_monitors!(nodes[1], 1);
5942
5943         let events = nodes[1].node.get_and_clear_pending_msg_events();
5944         assert_eq!(events.len(), 1);
5945         let (update_msg, commitment_signed) = match events[0] {
5946                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5947                         (update_fee.as_ref(), commitment_signed)
5948                 },
5949                 _ => panic!("Unexpected event"),
5950         };
5951
5952         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5953
5954         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5955         let channel_reserve = chan_stat.channel_reserve_msat;
5956         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5957         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
5958
5959         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5960         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5961         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5962         let payment_event = {
5963                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5964                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5965                 check_added_monitors!(nodes[0], 1);
5966
5967                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5968                 assert_eq!(events.len(), 1);
5969
5970                 SendEvent::from_event(events.remove(0))
5971         };
5972         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5973         check_added_monitors!(nodes[1], 0);
5974         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5975         expect_pending_htlcs_forwardable!(nodes[1]);
5976
5977         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5978         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5979
5980         // Flush the pending fee update.
5981         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5982         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5983         check_added_monitors!(nodes[2], 1);
5984         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5985         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5986         check_added_monitors!(nodes[1], 2);
5987
5988         // A final RAA message is generated to finalize the fee update.
5989         let events = nodes[1].node.get_and_clear_pending_msg_events();
5990         assert_eq!(events.len(), 1);
5991
5992         let raa_msg = match &events[0] {
5993                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5994                         msg.clone()
5995                 },
5996                 _ => panic!("Unexpected event"),
5997         };
5998
5999         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6000         check_added_monitors!(nodes[2], 1);
6001         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6002
6003         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6004         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6005         assert_eq!(process_htlc_forwards_event.len(), 2);
6006         match &process_htlc_forwards_event[0] {
6007                 &Event::PendingHTLCsForwardable { .. } => {},
6008                 _ => panic!("Unexpected event"),
6009         }
6010
6011         // In response, we call ChannelManager's process_pending_htlc_forwards
6012         nodes[1].node.process_pending_htlc_forwards();
6013         check_added_monitors!(nodes[1], 1);
6014
6015         // This causes the HTLC to be failed backwards.
6016         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6017         assert_eq!(fail_event.len(), 1);
6018         let (fail_msg, commitment_signed) = match &fail_event[0] {
6019                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6020                         assert_eq!(updates.update_add_htlcs.len(), 0);
6021                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6022                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6023                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6024                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6025                 },
6026                 _ => panic!("Unexpected event"),
6027         };
6028
6029         // Pass the failure messages back to nodes[0].
6030         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6031         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6032
6033         // Complete the HTLC failure+removal process.
6034         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6035         check_added_monitors!(nodes[0], 1);
6036         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6037         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6038         check_added_monitors!(nodes[1], 2);
6039         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6040         assert_eq!(final_raa_event.len(), 1);
6041         let raa = match &final_raa_event[0] {
6042                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6043                 _ => panic!("Unexpected event"),
6044         };
6045         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6046         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6047         check_added_monitors!(nodes[0], 1);
6048 }
6049
6050 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6051 // 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.
6052 //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.
6053
6054 #[test]
6055 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6056         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6057         let chanmon_cfgs = create_chanmon_cfgs(2);
6058         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6059         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6060         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6061         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6062
6063         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6064         route.paths[0].hops[0].fee_msat = 100;
6065
6066         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6067                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6068                 ), true, APIError::ChannelUnavailable { .. }, {});
6069         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6070 }
6071
6072 #[test]
6073 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6074         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6075         let chanmon_cfgs = create_chanmon_cfgs(2);
6076         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6077         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6078         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6079         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6080
6081         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6082         route.paths[0].hops[0].fee_msat = 0;
6083         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6084                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6085                 true, APIError::ChannelUnavailable { ref err },
6086                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6087
6088         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6089         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6090 }
6091
6092 #[test]
6093 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6094         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6095         let chanmon_cfgs = create_chanmon_cfgs(2);
6096         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6097         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6098         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6099         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6100
6101         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6102         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6103                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6104         check_added_monitors!(nodes[0], 1);
6105         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6106         updates.update_add_htlcs[0].amount_msat = 0;
6107
6108         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6109         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6110         check_closed_broadcast!(nodes[1], true).unwrap();
6111         check_added_monitors!(nodes[1], 1);
6112         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() }, 
6113                 [nodes[0].node.get_our_node_id()], 100000);
6114 }
6115
6116 #[test]
6117 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6118         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6119         //It is enforced when constructing a route.
6120         let chanmon_cfgs = create_chanmon_cfgs(2);
6121         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6122         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6123         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6124         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6125
6126         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6127                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6128         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6129         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6130         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6131                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6132                 ), true, APIError::InvalidRoute { ref err },
6133                 assert_eq!(err, &"Channel CLTV overflowed?"));
6134 }
6135
6136 #[test]
6137 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6138         //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.
6139         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6140         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6141         let chanmon_cfgs = create_chanmon_cfgs(2);
6142         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6143         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6144         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6145         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6146         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6147                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6148
6149         // Fetch a route in advance as we will be unable to once we're unable to send.
6150         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6151         for i in 0..max_accepted_htlcs {
6152                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6153                 let payment_event = {
6154                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6155                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6156                         check_added_monitors!(nodes[0], 1);
6157
6158                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6159                         assert_eq!(events.len(), 1);
6160                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6161                                 assert_eq!(htlcs[0].htlc_id, i);
6162                         } else {
6163                                 assert!(false);
6164                         }
6165                         SendEvent::from_event(events.remove(0))
6166                 };
6167                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6168                 check_added_monitors!(nodes[1], 0);
6169                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6170
6171                 expect_pending_htlcs_forwardable!(nodes[1]);
6172                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6173         }
6174         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6175                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6176                 ), true, APIError::ChannelUnavailable { .. }, {});
6177
6178         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6179 }
6180
6181 #[test]
6182 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6183         //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.
6184         let chanmon_cfgs = create_chanmon_cfgs(2);
6185         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6186         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6187         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6188         let channel_value = 100000;
6189         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6190         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6191
6192         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6193
6194         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6195         // Manually create a route over our max in flight (which our router normally automatically
6196         // limits us to.
6197         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6198         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6199                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6200                 ), true, APIError::ChannelUnavailable { .. }, {});
6201         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6202
6203         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6204 }
6205
6206 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6207 #[test]
6208 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6209         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6210         let chanmon_cfgs = create_chanmon_cfgs(2);
6211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6213         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6214         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6215         let htlc_minimum_msat: u64;
6216         {
6217                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6218                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6219                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6220                 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6221         }
6222
6223         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6224         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6225                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6226         check_added_monitors!(nodes[0], 1);
6227         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6228         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6229         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6230         assert!(nodes[1].node.list_channels().is_empty());
6231         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6232         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()));
6233         check_added_monitors!(nodes[1], 1);
6234         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6235 }
6236
6237 #[test]
6238 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6239         //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
6240         let chanmon_cfgs = create_chanmon_cfgs(2);
6241         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6242         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6243         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6244         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6245
6246         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6247         let channel_reserve = chan_stat.channel_reserve_msat;
6248         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6249         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6250         // The 2* and +1 are for the fee spike reserve.
6251         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6252
6253         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6254         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6255         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6256                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6257         check_added_monitors!(nodes[0], 1);
6258         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6259
6260         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6261         // at this time channel-initiatee receivers are not required to enforce that senders
6262         // respect the fee_spike_reserve.
6263         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6264         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6265
6266         assert!(nodes[1].node.list_channels().is_empty());
6267         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6268         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6269         check_added_monitors!(nodes[1], 1);
6270         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6271 }
6272
6273 #[test]
6274 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6275         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6276         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6277         let chanmon_cfgs = create_chanmon_cfgs(2);
6278         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6279         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6280         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6281         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6282
6283         let send_amt = 3999999;
6284         let (mut route, our_payment_hash, _, our_payment_secret) =
6285                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6286         route.paths[0].hops[0].fee_msat = send_amt;
6287         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6288         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6289         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6290         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6291                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6292         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6293
6294         let mut msg = msgs::UpdateAddHTLC {
6295                 channel_id: chan.2,
6296                 htlc_id: 0,
6297                 amount_msat: 1000,
6298                 payment_hash: our_payment_hash,
6299                 cltv_expiry: htlc_cltv,
6300                 onion_routing_packet: onion_packet.clone(),
6301                 skimmed_fee_msat: None,
6302         };
6303
6304         for i in 0..50 {
6305                 msg.htlc_id = i as u64;
6306                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6307         }
6308         msg.htlc_id = (50) as u64;
6309         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6310
6311         assert!(nodes[1].node.list_channels().is_empty());
6312         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6313         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6314         check_added_monitors!(nodes[1], 1);
6315         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6316 }
6317
6318 #[test]
6319 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6320         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6321         let chanmon_cfgs = create_chanmon_cfgs(2);
6322         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6323         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6324         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6325         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6326
6327         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6328         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6329                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6330         check_added_monitors!(nodes[0], 1);
6331         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6332         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;
6333         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6334
6335         assert!(nodes[1].node.list_channels().is_empty());
6336         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6337         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6338         check_added_monitors!(nodes[1], 1);
6339         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6340 }
6341
6342 #[test]
6343 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6344         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6345         let chanmon_cfgs = create_chanmon_cfgs(2);
6346         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6347         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6348         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6349
6350         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6351         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6352         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6353                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6354         check_added_monitors!(nodes[0], 1);
6355         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6356         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6357         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6358
6359         assert!(nodes[1].node.list_channels().is_empty());
6360         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6361         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6362         check_added_monitors!(nodes[1], 1);
6363         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6364 }
6365
6366 #[test]
6367 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6368         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6369         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6370         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6371         let chanmon_cfgs = create_chanmon_cfgs(2);
6372         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6373         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6374         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6375
6376         create_announced_chan_between_nodes(&nodes, 0, 1);
6377         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6378         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6379                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6380         check_added_monitors!(nodes[0], 1);
6381         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6382         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6383
6384         //Disconnect and Reconnect
6385         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6386         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6387         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6388                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6389         }, true).unwrap();
6390         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6391         assert_eq!(reestablish_1.len(), 1);
6392         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6393                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6394         }, false).unwrap();
6395         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6396         assert_eq!(reestablish_2.len(), 1);
6397         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6398         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6399         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6400         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6401
6402         //Resend HTLC
6403         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6404         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6405         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6406         check_added_monitors!(nodes[1], 1);
6407         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6408
6409         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6410
6411         assert!(nodes[1].node.list_channels().is_empty());
6412         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6413         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6414         check_added_monitors!(nodes[1], 1);
6415         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6416 }
6417
6418 #[test]
6419 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6420         //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.
6421
6422         let chanmon_cfgs = create_chanmon_cfgs(2);
6423         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6424         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6425         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6426         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6427         let (route, our_payment_hash, our_payment_preimage, 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
6431         check_added_monitors!(nodes[0], 1);
6432         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6433         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6434
6435         let update_msg = msgs::UpdateFulfillHTLC{
6436                 channel_id: chan.2,
6437                 htlc_id: 0,
6438                 payment_preimage: our_payment_preimage,
6439         };
6440
6441         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6442
6443         assert!(nodes[0].node.list_channels().is_empty());
6444         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6445         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()));
6446         check_added_monitors!(nodes[0], 1);
6447         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6448 }
6449
6450 #[test]
6451 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6452         //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.
6453
6454         let chanmon_cfgs = create_chanmon_cfgs(2);
6455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6457         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6458         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6459
6460         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6461         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6462                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6463         check_added_monitors!(nodes[0], 1);
6464         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6465         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6466
6467         let update_msg = msgs::UpdateFailHTLC{
6468                 channel_id: chan.2,
6469                 htlc_id: 0,
6470                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6471         };
6472
6473         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6474
6475         assert!(nodes[0].node.list_channels().is_empty());
6476         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6477         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()));
6478         check_added_monitors!(nodes[0], 1);
6479         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6480 }
6481
6482 #[test]
6483 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6484         //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.
6485
6486         let chanmon_cfgs = create_chanmon_cfgs(2);
6487         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6488         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6489         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6490         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6491
6492         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6493         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6494                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6495         check_added_monitors!(nodes[0], 1);
6496         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6497         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6498         let update_msg = msgs::UpdateFailMalformedHTLC{
6499                 channel_id: chan.2,
6500                 htlc_id: 0,
6501                 sha256_of_onion: [1; 32],
6502                 failure_code: 0x8000,
6503         };
6504
6505         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6506
6507         assert!(nodes[0].node.list_channels().is_empty());
6508         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6509         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()));
6510         check_added_monitors!(nodes[0], 1);
6511         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6512 }
6513
6514 #[test]
6515 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6516         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6517
6518         let chanmon_cfgs = create_chanmon_cfgs(2);
6519         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6520         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6521         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6522         create_announced_chan_between_nodes(&nodes, 0, 1);
6523
6524         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6525
6526         nodes[1].node.claim_funds(our_payment_preimage);
6527         check_added_monitors!(nodes[1], 1);
6528         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6529
6530         let events = nodes[1].node.get_and_clear_pending_msg_events();
6531         assert_eq!(events.len(), 1);
6532         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6533                 match events[0] {
6534                         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, .. } } => {
6535                                 assert!(update_add_htlcs.is_empty());
6536                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6537                                 assert!(update_fail_htlcs.is_empty());
6538                                 assert!(update_fail_malformed_htlcs.is_empty());
6539                                 assert!(update_fee.is_none());
6540                                 update_fulfill_htlcs[0].clone()
6541                         },
6542                         _ => panic!("Unexpected event"),
6543                 }
6544         };
6545
6546         update_fulfill_msg.htlc_id = 1;
6547
6548         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6549
6550         assert!(nodes[0].node.list_channels().is_empty());
6551         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6552         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6553         check_added_monitors!(nodes[0], 1);
6554         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6555 }
6556
6557 #[test]
6558 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6559         //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.
6560
6561         let chanmon_cfgs = create_chanmon_cfgs(2);
6562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565         create_announced_chan_between_nodes(&nodes, 0, 1);
6566
6567         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6568
6569         nodes[1].node.claim_funds(our_payment_preimage);
6570         check_added_monitors!(nodes[1], 1);
6571         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6572
6573         let events = nodes[1].node.get_and_clear_pending_msg_events();
6574         assert_eq!(events.len(), 1);
6575         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6576                 match events[0] {
6577                         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, .. } } => {
6578                                 assert!(update_add_htlcs.is_empty());
6579                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6580                                 assert!(update_fail_htlcs.is_empty());
6581                                 assert!(update_fail_malformed_htlcs.is_empty());
6582                                 assert!(update_fee.is_none());
6583                                 update_fulfill_htlcs[0].clone()
6584                         },
6585                         _ => panic!("Unexpected event"),
6586                 }
6587         };
6588
6589         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6590
6591         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6592
6593         assert!(nodes[0].node.list_channels().is_empty());
6594         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6595         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6596         check_added_monitors!(nodes[0], 1);
6597         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6598 }
6599
6600 #[test]
6601 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6602         //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.
6603
6604         let chanmon_cfgs = create_chanmon_cfgs(2);
6605         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6606         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6607         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6608         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6609
6610         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6611         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6612                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6613         check_added_monitors!(nodes[0], 1);
6614
6615         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6616         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6617
6618         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6619         check_added_monitors!(nodes[1], 0);
6620         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6621
6622         let events = nodes[1].node.get_and_clear_pending_msg_events();
6623
6624         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6625                 match events[0] {
6626                         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, .. } } => {
6627                                 assert!(update_add_htlcs.is_empty());
6628                                 assert!(update_fulfill_htlcs.is_empty());
6629                                 assert!(update_fail_htlcs.is_empty());
6630                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6631                                 assert!(update_fee.is_none());
6632                                 update_fail_malformed_htlcs[0].clone()
6633                         },
6634                         _ => panic!("Unexpected event"),
6635                 }
6636         };
6637         update_msg.failure_code &= !0x8000;
6638         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6639
6640         assert!(nodes[0].node.list_channels().is_empty());
6641         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6642         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6643         check_added_monitors!(nodes[0], 1);
6644         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6645 }
6646
6647 #[test]
6648 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6649         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6650         //    * 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.
6651
6652         let chanmon_cfgs = create_chanmon_cfgs(3);
6653         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6654         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6655         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6656         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6657         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6658
6659         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6660
6661         //First hop
6662         let mut payment_event = {
6663                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6664                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6665                 check_added_monitors!(nodes[0], 1);
6666                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6667                 assert_eq!(events.len(), 1);
6668                 SendEvent::from_event(events.remove(0))
6669         };
6670         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6671         check_added_monitors!(nodes[1], 0);
6672         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6673         expect_pending_htlcs_forwardable!(nodes[1]);
6674         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6675         assert_eq!(events_2.len(), 1);
6676         check_added_monitors!(nodes[1], 1);
6677         payment_event = SendEvent::from_event(events_2.remove(0));
6678         assert_eq!(payment_event.msgs.len(), 1);
6679
6680         //Second Hop
6681         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6682         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6683         check_added_monitors!(nodes[2], 0);
6684         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6685
6686         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6687         assert_eq!(events_3.len(), 1);
6688         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6689                 match events_3[0] {
6690                         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 } } => {
6691                                 assert!(update_add_htlcs.is_empty());
6692                                 assert!(update_fulfill_htlcs.is_empty());
6693                                 assert!(update_fail_htlcs.is_empty());
6694                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6695                                 assert!(update_fee.is_none());
6696                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6697                         },
6698                         _ => panic!("Unexpected event"),
6699                 }
6700         };
6701
6702         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6703
6704         check_added_monitors!(nodes[1], 0);
6705         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6706         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 }]);
6707         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6708         assert_eq!(events_4.len(), 1);
6709
6710         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6711         match events_4[0] {
6712                 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, .. } } => {
6713                         assert!(update_add_htlcs.is_empty());
6714                         assert!(update_fulfill_htlcs.is_empty());
6715                         assert_eq!(update_fail_htlcs.len(), 1);
6716                         assert!(update_fail_malformed_htlcs.is_empty());
6717                         assert!(update_fee.is_none());
6718                 },
6719                 _ => panic!("Unexpected event"),
6720         };
6721
6722         check_added_monitors!(nodes[1], 1);
6723 }
6724
6725 #[test]
6726 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6727         let chanmon_cfgs = create_chanmon_cfgs(3);
6728         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6729         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6730         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6731         create_announced_chan_between_nodes(&nodes, 0, 1);
6732         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6733
6734         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6735
6736         // First hop
6737         let mut payment_event = {
6738                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6739                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6740                 check_added_monitors!(nodes[0], 1);
6741                 SendEvent::from_node(&nodes[0])
6742         };
6743
6744         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6745         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6746         expect_pending_htlcs_forwardable!(nodes[1]);
6747         check_added_monitors!(nodes[1], 1);
6748         payment_event = SendEvent::from_node(&nodes[1]);
6749         assert_eq!(payment_event.msgs.len(), 1);
6750
6751         // Second Hop
6752         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6753         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6754         check_added_monitors!(nodes[2], 0);
6755         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6756
6757         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6758         assert_eq!(events_3.len(), 1);
6759         match events_3[0] {
6760                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6761                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6762                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6763                         update_msg.failure_code |= 0x2000;
6764
6765                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6766                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6767                 },
6768                 _ => panic!("Unexpected event"),
6769         }
6770
6771         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6772                 vec![HTLCDestination::NextHopChannel {
6773                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6774         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6775         assert_eq!(events_4.len(), 1);
6776         check_added_monitors!(nodes[1], 1);
6777
6778         match events_4[0] {
6779                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6780                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6781                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6782                 },
6783                 _ => panic!("Unexpected event"),
6784         }
6785
6786         let events_5 = nodes[0].node.get_and_clear_pending_events();
6787         assert_eq!(events_5.len(), 2);
6788
6789         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6790         // the node originating the error to its next hop.
6791         match events_5[0] {
6792                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6793                 } => {
6794                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6795                         assert!(is_permanent);
6796                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6797                 },
6798                 _ => panic!("Unexpected event"),
6799         }
6800         match events_5[1] {
6801                 Event::PaymentFailed { payment_hash, .. } => {
6802                         assert_eq!(payment_hash, our_payment_hash);
6803                 },
6804                 _ => panic!("Unexpected event"),
6805         }
6806
6807         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6808 }
6809
6810 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6811         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6812         // 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
6813         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6814
6815         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6816         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6820         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6821
6822         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6823                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6824
6825         // We route 2 dust-HTLCs between A and B
6826         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6827         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6828         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6829
6830         // Cache one local commitment tx as previous
6831         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6832
6833         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6834         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6835         check_added_monitors!(nodes[1], 0);
6836         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6837         check_added_monitors!(nodes[1], 1);
6838
6839         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6840         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6841         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6842         check_added_monitors!(nodes[0], 1);
6843
6844         // Cache one local commitment tx as lastest
6845         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6846
6847         let events = nodes[0].node.get_and_clear_pending_msg_events();
6848         match events[0] {
6849                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6850                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6851                 },
6852                 _ => panic!("Unexpected event"),
6853         }
6854         match events[1] {
6855                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6856                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6857                 },
6858                 _ => panic!("Unexpected event"),
6859         }
6860
6861         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6862         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6863         if announce_latest {
6864                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6865         } else {
6866                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6867         }
6868
6869         check_closed_broadcast!(nodes[0], true);
6870         check_added_monitors!(nodes[0], 1);
6871         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6872
6873         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6874         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6875         let events = nodes[0].node.get_and_clear_pending_events();
6876         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6877         assert_eq!(events.len(), 4);
6878         let mut first_failed = false;
6879         for event in events {
6880                 match event {
6881                         Event::PaymentPathFailed { payment_hash, .. } => {
6882                                 if payment_hash == payment_hash_1 {
6883                                         assert!(!first_failed);
6884                                         first_failed = true;
6885                                 } else {
6886                                         assert_eq!(payment_hash, payment_hash_2);
6887                                 }
6888                         },
6889                         Event::PaymentFailed { .. } => {}
6890                         _ => panic!("Unexpected event"),
6891                 }
6892         }
6893 }
6894
6895 #[test]
6896 fn test_failure_delay_dust_htlc_local_commitment() {
6897         do_test_failure_delay_dust_htlc_local_commitment(true);
6898         do_test_failure_delay_dust_htlc_local_commitment(false);
6899 }
6900
6901 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6902         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6903         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6904         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6905         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6906         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6907         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6908
6909         let chanmon_cfgs = create_chanmon_cfgs(3);
6910         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6911         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6912         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6913         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6914
6915         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6916                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6917
6918         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6919         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6920
6921         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6922         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6923
6924         // We revoked bs_commitment_tx
6925         if revoked {
6926                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6927                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6928         }
6929
6930         let mut timeout_tx = Vec::new();
6931         if local {
6932                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6933                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6934                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6935                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6936                 expect_payment_failed!(nodes[0], dust_hash, false);
6937
6938                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6939                 check_closed_broadcast!(nodes[0], true);
6940                 check_added_monitors!(nodes[0], 1);
6941                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6942                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6943                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6944                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6945                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6946                 mine_transaction(&nodes[0], &timeout_tx[0]);
6947                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6948                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6949         } else {
6950                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6951                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6952                 check_closed_broadcast!(nodes[0], true);
6953                 check_added_monitors!(nodes[0], 1);
6954                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6955                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6956
6957                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6958                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6959                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6960                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6961                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6962                 // dust HTLC should have been failed.
6963                 expect_payment_failed!(nodes[0], dust_hash, false);
6964
6965                 if !revoked {
6966                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6967                 } else {
6968                         assert_eq!(timeout_tx[0].lock_time.0, 11);
6969                 }
6970                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6971                 mine_transaction(&nodes[0], &timeout_tx[0]);
6972                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6973                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6974                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6975         }
6976 }
6977
6978 #[test]
6979 fn test_sweep_outbound_htlc_failure_update() {
6980         do_test_sweep_outbound_htlc_failure_update(false, true);
6981         do_test_sweep_outbound_htlc_failure_update(false, false);
6982         do_test_sweep_outbound_htlc_failure_update(true, false);
6983 }
6984
6985 #[test]
6986 fn test_user_configurable_csv_delay() {
6987         // We test our channel constructors yield errors when we pass them absurd csv delay
6988
6989         let mut low_our_to_self_config = UserConfig::default();
6990         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6991         let mut high_their_to_self_config = UserConfig::default();
6992         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6993         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6994         let chanmon_cfgs = create_chanmon_cfgs(2);
6995         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6996         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6997         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6998
6999         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7000         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7001                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7002                 &low_our_to_self_config, 0, 42)
7003         {
7004                 match error {
7005                         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())); },
7006                         _ => panic!("Unexpected event"),
7007                 }
7008         } else { assert!(false) }
7009
7010         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7011         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7012         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7013         open_channel.to_self_delay = 200;
7014         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7015                 &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,
7016                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7017         {
7018                 match error {
7019                         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()));  },
7020                         _ => panic!("Unexpected event"),
7021                 }
7022         } else { assert!(false); }
7023
7024         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7025         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7026         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()));
7027         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7028         accept_channel.to_self_delay = 200;
7029         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7030         let reason_msg;
7031         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7032                 match action {
7033                         &ErrorAction::SendErrorMessage { ref msg } => {
7034                                 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()));
7035                                 reason_msg = msg.data.clone();
7036                         },
7037                         _ => { panic!(); }
7038                 }
7039         } else { panic!(); }
7040         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7041
7042         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7043         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7044         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7045         open_channel.to_self_delay = 200;
7046         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7047                 &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,
7048                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7049         {
7050                 match error {
7051                         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())); },
7052                         _ => panic!("Unexpected event"),
7053                 }
7054         } else { assert!(false); }
7055 }
7056
7057 #[test]
7058 fn test_check_htlc_underpaying() {
7059         // Send payment through A -> B but A is maliciously
7060         // sending a probe payment (i.e less than expected value0
7061         // to B, B should refuse payment.
7062
7063         let chanmon_cfgs = create_chanmon_cfgs(2);
7064         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7065         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7066         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7067
7068         // Create some initial channels
7069         create_announced_chan_between_nodes(&nodes, 0, 1);
7070
7071         let scorer = test_utils::TestScorer::new();
7072         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7073         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();
7074         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();
7075         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7076         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7077         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7078                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7079         check_added_monitors!(nodes[0], 1);
7080
7081         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7082         assert_eq!(events.len(), 1);
7083         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7084         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7085         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7086
7087         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7088         // and then will wait a second random delay before failing the HTLC back:
7089         expect_pending_htlcs_forwardable!(nodes[1]);
7090         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7091
7092         // Node 3 is expecting payment of 100_000 but received 10_000,
7093         // it should fail htlc like we didn't know the preimage.
7094         nodes[1].node.process_pending_htlc_forwards();
7095
7096         let events = nodes[1].node.get_and_clear_pending_msg_events();
7097         assert_eq!(events.len(), 1);
7098         let (update_fail_htlc, commitment_signed) = match events[0] {
7099                 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 } } => {
7100                         assert!(update_add_htlcs.is_empty());
7101                         assert!(update_fulfill_htlcs.is_empty());
7102                         assert_eq!(update_fail_htlcs.len(), 1);
7103                         assert!(update_fail_malformed_htlcs.is_empty());
7104                         assert!(update_fee.is_none());
7105                         (update_fail_htlcs[0].clone(), commitment_signed)
7106                 },
7107                 _ => panic!("Unexpected event"),
7108         };
7109         check_added_monitors!(nodes[1], 1);
7110
7111         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7112         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7113
7114         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7115         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7116         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7117         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7118 }
7119
7120 #[test]
7121 fn test_announce_disable_channels() {
7122         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7123         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7124
7125         let chanmon_cfgs = create_chanmon_cfgs(2);
7126         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7127         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7128         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7129
7130         create_announced_chan_between_nodes(&nodes, 0, 1);
7131         create_announced_chan_between_nodes(&nodes, 1, 0);
7132         create_announced_chan_between_nodes(&nodes, 0, 1);
7133
7134         // Disconnect peers
7135         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7136         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7137
7138         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7139                 nodes[0].node.timer_tick_occurred();
7140         }
7141         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7142         assert_eq!(msg_events.len(), 3);
7143         let mut chans_disabled = HashMap::new();
7144         for e in msg_events {
7145                 match e {
7146                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7147                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7148                                 // Check that each channel gets updated exactly once
7149                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7150                                         panic!("Generated ChannelUpdate for wrong chan!");
7151                                 }
7152                         },
7153                         _ => panic!("Unexpected event"),
7154                 }
7155         }
7156         // Reconnect peers
7157         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7158                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7159         }, true).unwrap();
7160         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7161         assert_eq!(reestablish_1.len(), 3);
7162         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7163                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7164         }, false).unwrap();
7165         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7166         assert_eq!(reestablish_2.len(), 3);
7167
7168         // Reestablish chan_1
7169         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7170         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7171         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7172         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7173         // Reestablish chan_2
7174         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7175         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7176         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7177         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7178         // Reestablish chan_3
7179         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7180         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7181         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7182         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7183
7184         for _ in 0..ENABLE_GOSSIP_TICKS {
7185                 nodes[0].node.timer_tick_occurred();
7186         }
7187         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7188         nodes[0].node.timer_tick_occurred();
7189         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7190         assert_eq!(msg_events.len(), 3);
7191         for e in msg_events {
7192                 match e {
7193                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7194                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7195                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7196                                         // Each update should have a higher timestamp than the previous one, replacing
7197                                         // the old one.
7198                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7199                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7200                                 }
7201                         },
7202                         _ => panic!("Unexpected event"),
7203                 }
7204         }
7205         // Check that each channel gets updated exactly once
7206         assert!(chans_disabled.is_empty());
7207 }
7208
7209 #[test]
7210 fn test_bump_penalty_txn_on_revoked_commitment() {
7211         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7212         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7213
7214         let chanmon_cfgs = create_chanmon_cfgs(2);
7215         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7216         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7217         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7218
7219         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7220
7221         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7222         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7223                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7224         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7225         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7226
7227         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7228         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7229         assert_eq!(revoked_txn[0].output.len(), 4);
7230         assert_eq!(revoked_txn[0].input.len(), 1);
7231         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7232         let revoked_txid = revoked_txn[0].txid();
7233
7234         let mut penalty_sum = 0;
7235         for outp in revoked_txn[0].output.iter() {
7236                 if outp.script_pubkey.is_v0_p2wsh() {
7237                         penalty_sum += outp.value;
7238                 }
7239         }
7240
7241         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7242         let header_114 = connect_blocks(&nodes[1], 14);
7243
7244         // Actually revoke tx by claiming a HTLC
7245         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7246         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7247         check_added_monitors!(nodes[1], 1);
7248
7249         // One or more justice tx should have been broadcast, check it
7250         let penalty_1;
7251         let feerate_1;
7252         {
7253                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7254                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7255                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7256                 assert_eq!(node_txn[0].output.len(), 1);
7257                 check_spends!(node_txn[0], revoked_txn[0]);
7258                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7259                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7260                 penalty_1 = node_txn[0].txid();
7261                 node_txn.clear();
7262         };
7263
7264         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7265         connect_blocks(&nodes[1], 15);
7266         let mut penalty_2 = penalty_1;
7267         let mut feerate_2 = 0;
7268         {
7269                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7270                 assert_eq!(node_txn.len(), 1);
7271                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7272                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7273                         assert_eq!(node_txn[0].output.len(), 1);
7274                         check_spends!(node_txn[0], revoked_txn[0]);
7275                         penalty_2 = node_txn[0].txid();
7276                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7277                         assert_ne!(penalty_2, penalty_1);
7278                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7279                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7280                         // Verify 25% bump heuristic
7281                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7282                         node_txn.clear();
7283                 }
7284         }
7285         assert_ne!(feerate_2, 0);
7286
7287         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7288         connect_blocks(&nodes[1], 1);
7289         let penalty_3;
7290         let mut feerate_3 = 0;
7291         {
7292                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7293                 assert_eq!(node_txn.len(), 1);
7294                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7295                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7296                         assert_eq!(node_txn[0].output.len(), 1);
7297                         check_spends!(node_txn[0], revoked_txn[0]);
7298                         penalty_3 = node_txn[0].txid();
7299                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7300                         assert_ne!(penalty_3, penalty_2);
7301                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7302                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7303                         // Verify 25% bump heuristic
7304                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7305                         node_txn.clear();
7306                 }
7307         }
7308         assert_ne!(feerate_3, 0);
7309
7310         nodes[1].node.get_and_clear_pending_events();
7311         nodes[1].node.get_and_clear_pending_msg_events();
7312 }
7313
7314 #[test]
7315 fn test_bump_penalty_txn_on_revoked_htlcs() {
7316         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7317         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7318
7319         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7320         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7321         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7322         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7323         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7324
7325         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7326         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7327         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7328         let scorer = test_utils::TestScorer::new();
7329         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7330         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7331                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7332         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7333         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7334         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7335                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7336         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7337
7338         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7339         assert_eq!(revoked_local_txn[0].input.len(), 1);
7340         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7341
7342         // Revoke local commitment tx
7343         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7344
7345         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7346         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7347         check_closed_broadcast!(nodes[1], true);
7348         check_added_monitors!(nodes[1], 1);
7349         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7350         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7351
7352         let revoked_htlc_txn = {
7353                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7354                 assert_eq!(txn.len(), 2);
7355
7356                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7357                 assert_eq!(txn[0].input.len(), 1);
7358                 check_spends!(txn[0], revoked_local_txn[0]);
7359
7360                 assert_eq!(txn[1].input.len(), 1);
7361                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7362                 assert_eq!(txn[1].output.len(), 1);
7363                 check_spends!(txn[1], revoked_local_txn[0]);
7364
7365                 txn
7366         };
7367
7368         // Broadcast set of revoked txn on A
7369         let hash_128 = connect_blocks(&nodes[0], 40);
7370         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7371         connect_block(&nodes[0], &block_11);
7372         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7373         connect_block(&nodes[0], &block_129);
7374         let events = nodes[0].node.get_and_clear_pending_events();
7375         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7376         match events.last().unwrap() {
7377                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7378                 _ => panic!("Unexpected event"),
7379         }
7380         let first;
7381         let feerate_1;
7382         let penalty_txn;
7383         {
7384                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7385                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7386                 // Verify claim tx are spending revoked HTLC txn
7387
7388                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7389                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7390                 // which are included in the same block (they are broadcasted because we scan the
7391                 // transactions linearly and generate claims as we go, they likely should be removed in the
7392                 // future).
7393                 assert_eq!(node_txn[0].input.len(), 1);
7394                 check_spends!(node_txn[0], revoked_local_txn[0]);
7395                 assert_eq!(node_txn[1].input.len(), 1);
7396                 check_spends!(node_txn[1], revoked_local_txn[0]);
7397                 assert_eq!(node_txn[2].input.len(), 1);
7398                 check_spends!(node_txn[2], revoked_local_txn[0]);
7399
7400                 // Each of the three justice transactions claim a separate (single) output of the three
7401                 // available, which we check here:
7402                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7403                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7404                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7405
7406                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7407                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7408
7409                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7410                 // output, checked above).
7411                 assert_eq!(node_txn[3].input.len(), 2);
7412                 assert_eq!(node_txn[3].output.len(), 1);
7413                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7414
7415                 first = node_txn[3].txid();
7416                 // Store both feerates for later comparison
7417                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7418                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7419                 penalty_txn = vec![node_txn[2].clone()];
7420                 node_txn.clear();
7421         }
7422
7423         // Connect one more block to see if bumped penalty are issued for HTLC txn
7424         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7425         connect_block(&nodes[0], &block_130);
7426         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7427         connect_block(&nodes[0], &block_131);
7428
7429         // Few more blocks to confirm penalty txn
7430         connect_blocks(&nodes[0], 4);
7431         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7432         let header_144 = connect_blocks(&nodes[0], 9);
7433         let node_txn = {
7434                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7435                 assert_eq!(node_txn.len(), 1);
7436
7437                 assert_eq!(node_txn[0].input.len(), 2);
7438                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7439                 // Verify bumped tx is different and 25% bump heuristic
7440                 assert_ne!(first, node_txn[0].txid());
7441                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7442                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7443                 assert!(feerate_2 * 100 > feerate_1 * 125);
7444                 let txn = vec![node_txn[0].clone()];
7445                 node_txn.clear();
7446                 txn
7447         };
7448         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7449         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7450         connect_blocks(&nodes[0], 20);
7451         {
7452                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7453                 // We verify than no new transaction has been broadcast because previously
7454                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7455                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7456                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7457                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7458                 // up bumped justice generation.
7459                 assert_eq!(node_txn.len(), 0);
7460                 node_txn.clear();
7461         }
7462         check_closed_broadcast!(nodes[0], true);
7463         check_added_monitors!(nodes[0], 1);
7464 }
7465
7466 #[test]
7467 fn test_bump_penalty_txn_on_remote_commitment() {
7468         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7469         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7470
7471         // Create 2 HTLCs
7472         // Provide preimage for one
7473         // Check aggregation
7474
7475         let chanmon_cfgs = create_chanmon_cfgs(2);
7476         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7477         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7478         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7479
7480         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7481         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7482         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7483
7484         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7485         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7486         assert_eq!(remote_txn[0].output.len(), 4);
7487         assert_eq!(remote_txn[0].input.len(), 1);
7488         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7489
7490         // Claim a HTLC without revocation (provide B monitor with preimage)
7491         nodes[1].node.claim_funds(payment_preimage);
7492         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7493         mine_transaction(&nodes[1], &remote_txn[0]);
7494         check_added_monitors!(nodes[1], 2);
7495         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7496
7497         // One or more claim tx should have been broadcast, check it
7498         let timeout;
7499         let preimage;
7500         let preimage_bump;
7501         let feerate_timeout;
7502         let feerate_preimage;
7503         {
7504                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7505                 // 3 transactions including:
7506                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7507                 assert_eq!(node_txn.len(), 3);
7508                 assert_eq!(node_txn[0].input.len(), 1);
7509                 assert_eq!(node_txn[1].input.len(), 1);
7510                 assert_eq!(node_txn[2].input.len(), 1);
7511                 check_spends!(node_txn[0], remote_txn[0]);
7512                 check_spends!(node_txn[1], remote_txn[0]);
7513                 check_spends!(node_txn[2], remote_txn[0]);
7514
7515                 preimage = node_txn[0].txid();
7516                 let index = node_txn[0].input[0].previous_output.vout;
7517                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7518                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7519
7520                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7521                         (node_txn[2].clone(), node_txn[1].clone())
7522                 } else {
7523                         (node_txn[1].clone(), node_txn[2].clone())
7524                 };
7525
7526                 preimage_bump = preimage_bump_tx;
7527                 check_spends!(preimage_bump, remote_txn[0]);
7528                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7529
7530                 timeout = timeout_tx.txid();
7531                 let index = timeout_tx.input[0].previous_output.vout;
7532                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7533                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7534
7535                 node_txn.clear();
7536         };
7537         assert_ne!(feerate_timeout, 0);
7538         assert_ne!(feerate_preimage, 0);
7539
7540         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7541         connect_blocks(&nodes[1], 1);
7542         {
7543                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7544                 assert_eq!(node_txn.len(), 1);
7545                 assert_eq!(node_txn[0].input.len(), 1);
7546                 assert_eq!(preimage_bump.input.len(), 1);
7547                 check_spends!(node_txn[0], remote_txn[0]);
7548                 check_spends!(preimage_bump, remote_txn[0]);
7549
7550                 let index = preimage_bump.input[0].previous_output.vout;
7551                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7552                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7553                 assert!(new_feerate * 100 > feerate_timeout * 125);
7554                 assert_ne!(timeout, preimage_bump.txid());
7555
7556                 let index = node_txn[0].input[0].previous_output.vout;
7557                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7558                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7559                 assert!(new_feerate * 100 > feerate_preimage * 125);
7560                 assert_ne!(preimage, node_txn[0].txid());
7561
7562                 node_txn.clear();
7563         }
7564
7565         nodes[1].node.get_and_clear_pending_events();
7566         nodes[1].node.get_and_clear_pending_msg_events();
7567 }
7568
7569 #[test]
7570 fn test_counterparty_raa_skip_no_crash() {
7571         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7572         // commitment transaction, we would have happily carried on and provided them the next
7573         // commitment transaction based on one RAA forward. This would probably eventually have led to
7574         // channel closure, but it would not have resulted in funds loss. Still, our
7575         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7576         // check simply that the channel is closed in response to such an RAA, but don't check whether
7577         // we decide to punish our counterparty for revoking their funds (as we don't currently
7578         // implement that).
7579         let chanmon_cfgs = create_chanmon_cfgs(2);
7580         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7581         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7582         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7583         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7584
7585         let per_commitment_secret;
7586         let next_per_commitment_point;
7587         {
7588                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7589                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7590                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7591
7592                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7593
7594                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7595                 keys.get_enforcement_state().last_holder_commitment -= 1;
7596                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7597
7598                 // Must revoke without gaps
7599                 keys.get_enforcement_state().last_holder_commitment -= 1;
7600                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7601
7602                 keys.get_enforcement_state().last_holder_commitment -= 1;
7603                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7604                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7605         }
7606
7607         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7608                 &msgs::RevokeAndACK {
7609                         channel_id,
7610                         per_commitment_secret,
7611                         next_per_commitment_point,
7612                         #[cfg(taproot)]
7613                         next_local_nonce: None,
7614                 });
7615         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7616         check_added_monitors!(nodes[1], 1);
7617         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7618                 , [nodes[0].node.get_our_node_id()], 100000);
7619 }
7620
7621 #[test]
7622 fn test_bump_txn_sanitize_tracking_maps() {
7623         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7624         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7625
7626         let chanmon_cfgs = create_chanmon_cfgs(2);
7627         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7628         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7629         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7630
7631         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7632         // Lock HTLC in both directions
7633         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7634         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7635
7636         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7637         assert_eq!(revoked_local_txn[0].input.len(), 1);
7638         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7639
7640         // Revoke local commitment tx
7641         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7642
7643         // Broadcast set of revoked txn on A
7644         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7645         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7646         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7647
7648         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7649         check_closed_broadcast!(nodes[0], true);
7650         check_added_monitors!(nodes[0], 1);
7651         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7652         let penalty_txn = {
7653                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7654                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7655                 check_spends!(node_txn[0], revoked_local_txn[0]);
7656                 check_spends!(node_txn[1], revoked_local_txn[0]);
7657                 check_spends!(node_txn[2], revoked_local_txn[0]);
7658                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7659                 node_txn.clear();
7660                 penalty_txn
7661         };
7662         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7663         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7664         {
7665                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7666                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7667                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7668         }
7669 }
7670
7671 #[test]
7672 fn test_channel_conf_timeout() {
7673         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7674         // confirm within 2016 blocks, as recommended by BOLT 2.
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         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7681
7682         // The outbound node should wait forever for confirmation:
7683         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7684         // copied here instead of directly referencing the constant.
7685         connect_blocks(&nodes[0], 2016);
7686         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7687
7688         // The inbound node should fail the channel after exactly 2016 blocks
7689         connect_blocks(&nodes[1], 2015);
7690         check_added_monitors!(nodes[1], 0);
7691         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7692
7693         connect_blocks(&nodes[1], 1);
7694         check_added_monitors!(nodes[1], 1);
7695         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7696         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7697         assert_eq!(close_ev.len(), 1);
7698         match close_ev[0] {
7699                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7700                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7701                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7702                 },
7703                 _ => panic!("Unexpected event"),
7704         }
7705 }
7706
7707 #[test]
7708 fn test_override_channel_config() {
7709         let chanmon_cfgs = create_chanmon_cfgs(2);
7710         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7711         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7712         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7713
7714         // Node0 initiates a channel to node1 using the override config.
7715         let mut override_config = UserConfig::default();
7716         override_config.channel_handshake_config.our_to_self_delay = 200;
7717
7718         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7719
7720         // Assert the channel created by node0 is using the override config.
7721         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7722         assert_eq!(res.channel_flags, 0);
7723         assert_eq!(res.to_self_delay, 200);
7724 }
7725
7726 #[test]
7727 fn test_override_0msat_htlc_minimum() {
7728         let mut zero_config = UserConfig::default();
7729         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7730         let chanmon_cfgs = create_chanmon_cfgs(2);
7731         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7732         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7733         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7734
7735         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7736         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7737         assert_eq!(res.htlc_minimum_msat, 1);
7738
7739         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7740         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7741         assert_eq!(res.htlc_minimum_msat, 1);
7742 }
7743
7744 #[test]
7745 fn test_channel_update_has_correct_htlc_maximum_msat() {
7746         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7747         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7748         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7749         // 90% of the `channel_value`.
7750         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7751
7752         let mut config_30_percent = UserConfig::default();
7753         config_30_percent.channel_handshake_config.announced_channel = true;
7754         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7755         let mut config_50_percent = UserConfig::default();
7756         config_50_percent.channel_handshake_config.announced_channel = true;
7757         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7758         let mut config_95_percent = UserConfig::default();
7759         config_95_percent.channel_handshake_config.announced_channel = true;
7760         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7761         let mut config_100_percent = UserConfig::default();
7762         config_100_percent.channel_handshake_config.announced_channel = true;
7763         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7764
7765         let chanmon_cfgs = create_chanmon_cfgs(4);
7766         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7767         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)]);
7768         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7769
7770         let channel_value_satoshis = 100000;
7771         let channel_value_msat = channel_value_satoshis * 1000;
7772         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7773         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7774         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7775
7776         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7777         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7778
7779         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7780         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7781         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7782         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7783         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7784         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7785
7786         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7787         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7788         // `channel_value`.
7789         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7790         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7791         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7792         // `channel_value`.
7793         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7794 }
7795
7796 #[test]
7797 fn test_manually_accept_inbound_channel_request() {
7798         let mut manually_accept_conf = UserConfig::default();
7799         manually_accept_conf.manually_accept_inbound_channels = true;
7800         let chanmon_cfgs = create_chanmon_cfgs(2);
7801         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7802         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7803         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7804
7805         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7806         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7807
7808         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7809
7810         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7811         // accepting the inbound channel request.
7812         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7813
7814         let events = nodes[1].node.get_and_clear_pending_events();
7815         match events[0] {
7816                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7817                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7818                 }
7819                 _ => panic!("Unexpected event"),
7820         }
7821
7822         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7823         assert_eq!(accept_msg_ev.len(), 1);
7824
7825         match accept_msg_ev[0] {
7826                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7827                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7828                 }
7829                 _ => panic!("Unexpected event"),
7830         }
7831
7832         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7833
7834         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7835         assert_eq!(close_msg_ev.len(), 1);
7836
7837         let events = nodes[1].node.get_and_clear_pending_events();
7838         match events[0] {
7839                 Event::ChannelClosed { user_channel_id, .. } => {
7840                         assert_eq!(user_channel_id, 23);
7841                 }
7842                 _ => panic!("Unexpected event"),
7843         }
7844 }
7845
7846 #[test]
7847 fn test_manually_reject_inbound_channel_request() {
7848         let mut manually_accept_conf = UserConfig::default();
7849         manually_accept_conf.manually_accept_inbound_channels = true;
7850         let chanmon_cfgs = create_chanmon_cfgs(2);
7851         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7852         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7853         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7854
7855         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7856         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7857
7858         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7859
7860         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7861         // rejecting the inbound channel request.
7862         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7863
7864         let events = nodes[1].node.get_and_clear_pending_events();
7865         match events[0] {
7866                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7867                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7868                 }
7869                 _ => panic!("Unexpected event"),
7870         }
7871
7872         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7873         assert_eq!(close_msg_ev.len(), 1);
7874
7875         match close_msg_ev[0] {
7876                 MessageSendEvent::HandleError { ref node_id, .. } => {
7877                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7878                 }
7879                 _ => panic!("Unexpected event"),
7880         }
7881
7882         // There should be no more events to process, as the channel was never opened.
7883         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7884 }
7885
7886 #[test]
7887 fn test_can_not_accept_inbound_channel_twice() {
7888         let mut manually_accept_conf = UserConfig::default();
7889         manually_accept_conf.manually_accept_inbound_channels = true;
7890         let chanmon_cfgs = create_chanmon_cfgs(2);
7891         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7892         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7893         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7894
7895         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7896         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7897
7898         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7899
7900         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7901         // accepting the inbound channel request.
7902         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7903
7904         let events = nodes[1].node.get_and_clear_pending_events();
7905         match events[0] {
7906                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7907                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7908                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7909                         match api_res {
7910                                 Err(APIError::APIMisuseError { err }) => {
7911                                         assert_eq!(err, "No such channel awaiting to be accepted.");
7912                                 },
7913                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7914                                 Err(e) => panic!("Unexpected Error {:?}", e),
7915                         }
7916                 }
7917                 _ => panic!("Unexpected event"),
7918         }
7919
7920         // Ensure that the channel wasn't closed after attempting to accept it twice.
7921         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7922         assert_eq!(accept_msg_ev.len(), 1);
7923
7924         match accept_msg_ev[0] {
7925                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7926                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7927                 }
7928                 _ => panic!("Unexpected event"),
7929         }
7930 }
7931
7932 #[test]
7933 fn test_can_not_accept_unknown_inbound_channel() {
7934         let chanmon_cfg = create_chanmon_cfgs(2);
7935         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7936         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7937         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7938
7939         let unknown_channel_id = [0; 32];
7940         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7941         match api_res {
7942                 Err(APIError::APIMisuseError { err }) => {
7943                         assert_eq!(err, "No such channel awaiting to be accepted.");
7944                 },
7945                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7946                 Err(e) => panic!("Unexpected Error: {:?}", e),
7947         }
7948 }
7949
7950 #[test]
7951 fn test_onion_value_mpp_set_calculation() {
7952         // Test that we use the onion value `amt_to_forward` when
7953         // calculating whether we've reached the `total_msat` of an MPP
7954         // by having a routing node forward more than `amt_to_forward`
7955         // and checking that the receiving node doesn't generate
7956         // a PaymentClaimable event too early
7957         let node_count = 4;
7958         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7959         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7960         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7961         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7962
7963         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7964         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7965         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7966         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7967
7968         let total_msat = 100_000;
7969         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7970         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7971         let sample_path = route.paths.pop().unwrap();
7972
7973         let mut path_1 = sample_path.clone();
7974         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7975         path_1.hops[0].short_channel_id = chan_1_id;
7976         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7977         path_1.hops[1].short_channel_id = chan_3_id;
7978         path_1.hops[1].fee_msat = 100_000;
7979         route.paths.push(path_1);
7980
7981         let mut path_2 = sample_path.clone();
7982         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
7983         path_2.hops[0].short_channel_id = chan_2_id;
7984         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
7985         path_2.hops[1].short_channel_id = chan_4_id;
7986         path_2.hops[1].fee_msat = 1_000;
7987         route.paths.push(path_2);
7988
7989         // Send payment
7990         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7991         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
7992                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
7993         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
7994                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
7995         check_added_monitors!(nodes[0], expected_paths.len());
7996
7997         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7998         assert_eq!(events.len(), expected_paths.len());
7999
8000         // First path
8001         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8002         let mut payment_event = SendEvent::from_event(ev);
8003         let mut prev_node = &nodes[0];
8004
8005         for (idx, &node) in expected_paths[0].iter().enumerate() {
8006                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8007
8008                 if idx == 0 { // routing node
8009                         let session_priv = [3; 32];
8010                         let height = nodes[0].best_block_info().1;
8011                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8012                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8013                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8014                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8015                         // Edit amt_to_forward to simulate the sender having set
8016                         // the final amount and the routing node taking less fee
8017                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8018                                 *amt_msat = 99_000;
8019                         } else { panic!() }
8020                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8021                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8022                 }
8023
8024                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8025                 check_added_monitors!(node, 0);
8026                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8027                 expect_pending_htlcs_forwardable!(node);
8028
8029                 if idx == 0 {
8030                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8031                         assert_eq!(events_2.len(), 1);
8032                         check_added_monitors!(node, 1);
8033                         payment_event = SendEvent::from_event(events_2.remove(0));
8034                         assert_eq!(payment_event.msgs.len(), 1);
8035                 } else {
8036                         let events_2 = node.node.get_and_clear_pending_events();
8037                         assert!(events_2.is_empty());
8038                 }
8039
8040                 prev_node = node;
8041         }
8042
8043         // Second path
8044         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8045         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8046
8047         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8048 }
8049
8050 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8051
8052         let routing_node_count = msat_amounts.len();
8053         let node_count = routing_node_count + 2;
8054
8055         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8056         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8057         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8058         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8059
8060         let src_idx = 0;
8061         let dst_idx = 1;
8062
8063         // Create channels for each amount
8064         let mut expected_paths = Vec::with_capacity(routing_node_count);
8065         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8066         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8067         for i in 0..routing_node_count {
8068                 let routing_node = 2 + i;
8069                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8070                 src_chan_ids.push(src_chan_id);
8071                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8072                 dst_chan_ids.push(dst_chan_id);
8073                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8074                 expected_paths.push(path);
8075         }
8076         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8077
8078         // Create a route for each amount
8079         let example_amount = 100000;
8080         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);
8081         let sample_path = route.paths.pop().unwrap();
8082         for i in 0..routing_node_count {
8083                 let routing_node = 2 + i;
8084                 let mut path = sample_path.clone();
8085                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8086                 path.hops[0].short_channel_id = src_chan_ids[i];
8087                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8088                 path.hops[1].short_channel_id = dst_chan_ids[i];
8089                 path.hops[1].fee_msat = msat_amounts[i];
8090                 route.paths.push(path);
8091         }
8092
8093         // Send payment with manually set total_msat
8094         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8095         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8096                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8097         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8098                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8099         check_added_monitors!(nodes[src_idx], expected_paths.len());
8100
8101         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8102         assert_eq!(events.len(), expected_paths.len());
8103         let mut amount_received = 0;
8104         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8105                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8106
8107                 let current_path_amount = msat_amounts[path_idx];
8108                 amount_received += current_path_amount;
8109                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8110                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8111         }
8112
8113         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8114 }
8115
8116 #[test]
8117 fn test_overshoot_mpp() {
8118         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8119         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8120 }
8121
8122 #[test]
8123 fn test_simple_mpp() {
8124         // Simple test of sending a multi-path payment.
8125         let chanmon_cfgs = create_chanmon_cfgs(4);
8126         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8127         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8128         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8129
8130         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8131         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8132         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8133         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8134
8135         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8136         let path = route.paths[0].clone();
8137         route.paths.push(path);
8138         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8139         route.paths[0].hops[0].short_channel_id = chan_1_id;
8140         route.paths[0].hops[1].short_channel_id = chan_3_id;
8141         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8142         route.paths[1].hops[0].short_channel_id = chan_2_id;
8143         route.paths[1].hops[1].short_channel_id = chan_4_id;
8144         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8145         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8146 }
8147
8148 #[test]
8149 fn test_preimage_storage() {
8150         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8151         let chanmon_cfgs = create_chanmon_cfgs(2);
8152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8154         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8155
8156         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8157
8158         {
8159                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8160                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8161                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8162                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8163                 check_added_monitors!(nodes[0], 1);
8164                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8165                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8166                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8167                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8168         }
8169         // Note that after leaving the above scope we have no knowledge of any arguments or return
8170         // values from previous calls.
8171         expect_pending_htlcs_forwardable!(nodes[1]);
8172         let events = nodes[1].node.get_and_clear_pending_events();
8173         assert_eq!(events.len(), 1);
8174         match events[0] {
8175                 Event::PaymentClaimable { ref purpose, .. } => {
8176                         match &purpose {
8177                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8178                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8179                                 },
8180                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8181                         }
8182                 },
8183                 _ => panic!("Unexpected event"),
8184         }
8185 }
8186
8187 #[test]
8188 fn test_bad_secret_hash() {
8189         // Simple test of unregistered payment hash/invalid payment secret handling
8190         let chanmon_cfgs = create_chanmon_cfgs(2);
8191         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8192         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8193         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8194
8195         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8196
8197         let random_payment_hash = PaymentHash([42; 32]);
8198         let random_payment_secret = PaymentSecret([43; 32]);
8199         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8200         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8201
8202         // All the below cases should end up being handled exactly identically, so we macro the
8203         // resulting events.
8204         macro_rules! handle_unknown_invalid_payment_data {
8205                 ($payment_hash: expr) => {
8206                         check_added_monitors!(nodes[0], 1);
8207                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8208                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8209                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8210                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8211
8212                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8213                         // again to process the pending backwards-failure of the HTLC
8214                         expect_pending_htlcs_forwardable!(nodes[1]);
8215                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8216                         check_added_monitors!(nodes[1], 1);
8217
8218                         // We should fail the payment back
8219                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8220                         match events.pop().unwrap() {
8221                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8222                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8223                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8224                                 },
8225                                 _ => panic!("Unexpected event"),
8226                         }
8227                 }
8228         }
8229
8230         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8231         // Error data is the HTLC value (100,000) and current block height
8232         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8233
8234         // Send a payment with the right payment hash but the wrong payment secret
8235         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8236                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8237         handle_unknown_invalid_payment_data!(our_payment_hash);
8238         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8239
8240         // Send a payment with a random payment hash, but the right payment secret
8241         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8242                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8243         handle_unknown_invalid_payment_data!(random_payment_hash);
8244         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8245
8246         // Send a payment with a random payment hash and random payment secret
8247         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8248                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8249         handle_unknown_invalid_payment_data!(random_payment_hash);
8250         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8251 }
8252
8253 #[test]
8254 fn test_update_err_monitor_lockdown() {
8255         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8256         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8257         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8258         // error.
8259         //
8260         // This scenario may happen in a watchtower setup, where watchtower process a block height
8261         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8262         // commitment at same time.
8263
8264         let chanmon_cfgs = create_chanmon_cfgs(2);
8265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8267         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8268
8269         // Create some initial channel
8270         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8271         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8272
8273         // Rebalance the network to generate htlc in the two directions
8274         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8275
8276         // Route a HTLC from node 0 to node 1 (but don't settle)
8277         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8278
8279         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8280         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8281         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8282         let persister = test_utils::TestPersister::new();
8283         let watchtower = {
8284                 let new_monitor = {
8285                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8286                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8287                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8288                         assert!(new_monitor == *monitor);
8289                         new_monitor
8290                 };
8291                 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);
8292                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8293                 watchtower
8294         };
8295         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8296         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8297         // transaction lock time requirements here.
8298         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8299         watchtower.chain_monitor.block_connected(&block, 200);
8300
8301         // Try to update ChannelMonitor
8302         nodes[1].node.claim_funds(preimage);
8303         check_added_monitors!(nodes[1], 1);
8304         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8305
8306         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8307         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8308         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8309         {
8310                 let mut node_0_per_peer_lock;
8311                 let mut node_0_peer_state_lock;
8312                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8313                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8314                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8315                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8316                 } else { assert!(false); }
8317         }
8318         // Our local monitor is in-sync and hasn't processed yet timeout
8319         check_added_monitors!(nodes[0], 1);
8320         let events = nodes[0].node.get_and_clear_pending_events();
8321         assert_eq!(events.len(), 1);
8322 }
8323
8324 #[test]
8325 fn test_concurrent_monitor_claim() {
8326         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8327         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8328         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8329         // state N+1 confirms. Alice claims output from state N+1.
8330
8331         let chanmon_cfgs = create_chanmon_cfgs(2);
8332         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8333         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8334         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8335
8336         // Create some initial channel
8337         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8338         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8339
8340         // Rebalance the network to generate htlc in the two directions
8341         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8342
8343         // Route a HTLC from node 0 to node 1 (but don't settle)
8344         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8345
8346         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8347         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8348         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8349         let persister = test_utils::TestPersister::new();
8350         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8351                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8352         );
8353         let watchtower_alice = {
8354                 let new_monitor = {
8355                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8356                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8357                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8358                         assert!(new_monitor == *monitor);
8359                         new_monitor
8360                 };
8361                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8362                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8363                 watchtower
8364         };
8365         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8366         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8367         // requirements here.
8368         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8369         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8370         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8371
8372         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8373         let alice_state = {
8374                 let mut txn = alice_broadcaster.txn_broadcast();
8375                 assert_eq!(txn.len(), 2);
8376                 txn.remove(0)
8377         };
8378
8379         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8380         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8381         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8382         let persister = test_utils::TestPersister::new();
8383         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8384         let watchtower_bob = {
8385                 let new_monitor = {
8386                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8387                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8388                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8389                         assert!(new_monitor == *monitor);
8390                         new_monitor
8391                 };
8392                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8393                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8394                 watchtower
8395         };
8396         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8397
8398         // Route another payment to generate another update with still previous HTLC pending
8399         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8400         nodes[1].node.send_payment_with_route(&route, payment_hash,
8401                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8402         check_added_monitors!(nodes[1], 1);
8403
8404         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8405         assert_eq!(updates.update_add_htlcs.len(), 1);
8406         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8407         {
8408                 let mut node_0_per_peer_lock;
8409                 let mut node_0_peer_state_lock;
8410                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8411                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8412                         // Watchtower Alice should already have seen the block and reject the update
8413                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8414                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8415                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8416                 } else { assert!(false); }
8417         }
8418         // Our local monitor is in-sync and hasn't processed yet timeout
8419         check_added_monitors!(nodes[0], 1);
8420
8421         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8422         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8423
8424         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8425         let bob_state_y;
8426         {
8427                 let mut txn = bob_broadcaster.txn_broadcast();
8428                 assert_eq!(txn.len(), 2);
8429                 bob_state_y = txn.remove(0);
8430         };
8431
8432         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8433         let height = HTLC_TIMEOUT_BROADCAST + 1;
8434         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8435         check_closed_broadcast(&nodes[0], 1, true);
8436         check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8437                 [nodes[1].node.get_our_node_id()], 100000);
8438         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8439         check_added_monitors(&nodes[0], 1);
8440         {
8441                 let htlc_txn = alice_broadcaster.txn_broadcast();
8442                 assert_eq!(htlc_txn.len(), 2);
8443                 check_spends!(htlc_txn[0], bob_state_y);
8444                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8445                 // it. However, she should, because it now has an invalid parent.
8446                 check_spends!(htlc_txn[1], alice_state);
8447         }
8448 }
8449
8450 #[test]
8451 fn test_pre_lockin_no_chan_closed_update() {
8452         // Test that if a peer closes a channel in response to a funding_created message we don't
8453         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8454         // message).
8455         //
8456         // Doing so would imply a channel monitor update before the initial channel monitor
8457         // registration, violating our API guarantees.
8458         //
8459         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8460         // then opening a second channel with the same funding output as the first (which is not
8461         // rejected because the first channel does not exist in the ChannelManager) and closing it
8462         // before receiving funding_signed.
8463         let chanmon_cfgs = create_chanmon_cfgs(2);
8464         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8465         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8466         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8467
8468         // Create an initial channel
8469         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8470         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8471         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8472         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8473         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8474
8475         // Move the first channel through the funding flow...
8476         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8477
8478         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8479         check_added_monitors!(nodes[0], 0);
8480
8481         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8482         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8483         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8484         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8485         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8486                 [nodes[1].node.get_our_node_id(); 2], 100000);
8487 }
8488
8489 #[test]
8490 fn test_htlc_no_detection() {
8491         // This test is a mutation to underscore the detection logic bug we had
8492         // before #653. HTLC value routed is above the remaining balance, thus
8493         // inverting HTLC and `to_remote` output. HTLC will come second and
8494         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8495         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8496         // outputs order detection for correct spending children filtring.
8497
8498         let chanmon_cfgs = create_chanmon_cfgs(2);
8499         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8500         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8501         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8502
8503         // Create some initial channels
8504         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8505
8506         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8507         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8508         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8509         assert_eq!(local_txn[0].input.len(), 1);
8510         assert_eq!(local_txn[0].output.len(), 3);
8511         check_spends!(local_txn[0], chan_1.3);
8512
8513         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8514         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8515         connect_block(&nodes[0], &block);
8516         // We deliberately connect the local tx twice as this should provoke a failure calling
8517         // this test before #653 fix.
8518         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8519         check_closed_broadcast!(nodes[0], true);
8520         check_added_monitors!(nodes[0], 1);
8521         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8522         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8523
8524         let htlc_timeout = {
8525                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8526                 assert_eq!(node_txn.len(), 1);
8527                 assert_eq!(node_txn[0].input.len(), 1);
8528                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8529                 check_spends!(node_txn[0], local_txn[0]);
8530                 node_txn[0].clone()
8531         };
8532
8533         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8534         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8535         expect_payment_failed!(nodes[0], our_payment_hash, false);
8536 }
8537
8538 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8539         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8540         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8541         // Carol, Alice would be the upstream node, and Carol the downstream.)
8542         //
8543         // Steps of the test:
8544         // 1) Alice sends a HTLC to Carol through Bob.
8545         // 2) Carol doesn't settle the HTLC.
8546         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8547         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8548         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8549         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8550         // 5) Carol release the preimage to Bob off-chain.
8551         // 6) Bob claims the offered output on the broadcasted commitment.
8552         let chanmon_cfgs = create_chanmon_cfgs(3);
8553         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8554         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8555         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8556
8557         // Create some initial channels
8558         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8559         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8560
8561         // Steps (1) and (2):
8562         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8563         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8564
8565         // Check that Alice's commitment transaction now contains an output for this HTLC.
8566         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8567         check_spends!(alice_txn[0], chan_ab.3);
8568         assert_eq!(alice_txn[0].output.len(), 2);
8569         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8570         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8571         assert_eq!(alice_txn.len(), 2);
8572
8573         // Steps (3) and (4):
8574         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8575         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8576         let mut force_closing_node = 0; // Alice force-closes
8577         let mut counterparty_node = 1; // Bob if Alice force-closes
8578
8579         // Bob force-closes
8580         if !broadcast_alice {
8581                 force_closing_node = 1;
8582                 counterparty_node = 0;
8583         }
8584         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8585         check_closed_broadcast!(nodes[force_closing_node], true);
8586         check_added_monitors!(nodes[force_closing_node], 1);
8587         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8588         if go_onchain_before_fulfill {
8589                 let txn_to_broadcast = match broadcast_alice {
8590                         true => alice_txn.clone(),
8591                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8592                 };
8593                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8594                 if broadcast_alice {
8595                         check_closed_broadcast!(nodes[1], true);
8596                         check_added_monitors!(nodes[1], 1);
8597                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8598                 }
8599         }
8600
8601         // Step (5):
8602         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8603         // process of removing the HTLC from their commitment transactions.
8604         nodes[2].node.claim_funds(payment_preimage);
8605         check_added_monitors!(nodes[2], 1);
8606         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8607
8608         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8609         assert!(carol_updates.update_add_htlcs.is_empty());
8610         assert!(carol_updates.update_fail_htlcs.is_empty());
8611         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8612         assert!(carol_updates.update_fee.is_none());
8613         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8614
8615         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8616         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8617         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8618         if !go_onchain_before_fulfill && broadcast_alice {
8619                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8620                 assert_eq!(events.len(), 1);
8621                 match events[0] {
8622                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8623                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8624                         },
8625                         _ => panic!("Unexpected event"),
8626                 };
8627         }
8628         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8629         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8630         // Carol<->Bob's updated commitment transaction info.
8631         check_added_monitors!(nodes[1], 2);
8632
8633         let events = nodes[1].node.get_and_clear_pending_msg_events();
8634         assert_eq!(events.len(), 2);
8635         let bob_revocation = match events[0] {
8636                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8637                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8638                         (*msg).clone()
8639                 },
8640                 _ => panic!("Unexpected event"),
8641         };
8642         let bob_updates = match events[1] {
8643                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8644                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8645                         (*updates).clone()
8646                 },
8647                 _ => panic!("Unexpected event"),
8648         };
8649
8650         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8651         check_added_monitors!(nodes[2], 1);
8652         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8653         check_added_monitors!(nodes[2], 1);
8654
8655         let events = nodes[2].node.get_and_clear_pending_msg_events();
8656         assert_eq!(events.len(), 1);
8657         let carol_revocation = match events[0] {
8658                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8659                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8660                         (*msg).clone()
8661                 },
8662                 _ => panic!("Unexpected event"),
8663         };
8664         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8665         check_added_monitors!(nodes[1], 1);
8666
8667         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8668         // here's where we put said channel's commitment tx on-chain.
8669         let mut txn_to_broadcast = alice_txn.clone();
8670         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8671         if !go_onchain_before_fulfill {
8672                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8673                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8674                 if broadcast_alice {
8675                         check_closed_broadcast!(nodes[1], true);
8676                         check_added_monitors!(nodes[1], 1);
8677                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8678                 }
8679                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8680                 if broadcast_alice {
8681                         assert_eq!(bob_txn.len(), 1);
8682                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8683                 } else {
8684                         assert_eq!(bob_txn.len(), 2);
8685                         check_spends!(bob_txn[0], chan_ab.3);
8686                 }
8687         }
8688
8689         // Step (6):
8690         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8691         // broadcasted commitment transaction.
8692         {
8693                 let script_weight = match broadcast_alice {
8694                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8695                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8696                 };
8697                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8698                 // Bob force-closed and broadcasts the commitment transaction along with a
8699                 // HTLC-output-claiming transaction.
8700                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8701                 if broadcast_alice {
8702                         assert_eq!(bob_txn.len(), 1);
8703                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8704                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8705                 } else {
8706                         assert_eq!(bob_txn.len(), 2);
8707                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8708                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8709                 }
8710         }
8711 }
8712
8713 #[test]
8714 fn test_onchain_htlc_settlement_after_close() {
8715         do_test_onchain_htlc_settlement_after_close(true, true);
8716         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8717         do_test_onchain_htlc_settlement_after_close(true, false);
8718         do_test_onchain_htlc_settlement_after_close(false, false);
8719 }
8720
8721 #[test]
8722 fn test_duplicate_temporary_channel_id_from_different_peers() {
8723         // Tests that we can accept two different `OpenChannel` requests with the same
8724         // `temporary_channel_id`, as long as they are from different peers.
8725         let chanmon_cfgs = create_chanmon_cfgs(3);
8726         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8727         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8728         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8729
8730         // Create an first channel channel
8731         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8732         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8733
8734         // Create an second channel
8735         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8736         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8737
8738         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8739         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8740         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8741
8742         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8743         // `temporary_channel_id` as they are from different peers.
8744         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8745         {
8746                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8747                 assert_eq!(events.len(), 1);
8748                 match &events[0] {
8749                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8750                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8751                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8752                         },
8753                         _ => panic!("Unexpected event"),
8754                 }
8755         }
8756
8757         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8758         {
8759                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8760                 assert_eq!(events.len(), 1);
8761                 match &events[0] {
8762                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8763                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8764                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8765                         },
8766                         _ => panic!("Unexpected event"),
8767                 }
8768         }
8769 }
8770
8771 #[test]
8772 fn test_duplicate_chan_id() {
8773         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8774         // already open we reject it and keep the old channel.
8775         //
8776         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8777         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8778         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8779         // updating logic for the existing channel.
8780         let chanmon_cfgs = create_chanmon_cfgs(2);
8781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8783         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8784
8785         // Create an initial channel
8786         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8787         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8788         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8789         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()));
8790
8791         // Try to create a second channel with the same temporary_channel_id as the first and check
8792         // that it is rejected.
8793         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8794         {
8795                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8796                 assert_eq!(events.len(), 1);
8797                 match events[0] {
8798                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8799                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8800                                 // first (valid) and second (invalid) channels are closed, given they both have
8801                                 // the same non-temporary channel_id. However, currently we do not, so we just
8802                                 // move forward with it.
8803                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8804                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8805                         },
8806                         _ => panic!("Unexpected event"),
8807                 }
8808         }
8809
8810         // Move the first channel through the funding flow...
8811         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8812
8813         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8814         check_added_monitors!(nodes[0], 0);
8815
8816         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8817         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8818         {
8819                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8820                 assert_eq!(added_monitors.len(), 1);
8821                 assert_eq!(added_monitors[0].0, funding_output);
8822                 added_monitors.clear();
8823         }
8824         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8825
8826         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8827
8828         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8829         let channel_id = funding_outpoint.to_channel_id();
8830
8831         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8832         // temporary one).
8833
8834         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8835         // Technically this is allowed by the spec, but we don't support it and there's little reason
8836         // to. Still, it shouldn't cause any other issues.
8837         open_chan_msg.temporary_channel_id = channel_id;
8838         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8839         {
8840                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8841                 assert_eq!(events.len(), 1);
8842                 match events[0] {
8843                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8844                                 // Technically, at this point, nodes[1] would be justified in thinking both
8845                                 // channels are closed, but currently we do not, so we just move forward with it.
8846                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8847                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8848                         },
8849                         _ => panic!("Unexpected event"),
8850                 }
8851         }
8852
8853         // Now try to create a second channel which has a duplicate funding output.
8854         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8855         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8856         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8857         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()));
8858         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8859
8860         let (_, funding_created) = {
8861                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8862                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8863                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8864                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8865                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8866                 // channelmanager in a possibly nonsense state instead).
8867                 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8868                 let logger = test_utils::TestLogger::new();
8869                 as_chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8870         };
8871         check_added_monitors!(nodes[0], 0);
8872         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8873         // At this point we'll look up if the channel_id is present and immediately fail the channel
8874         // without trying to persist the `ChannelMonitor`.
8875         check_added_monitors!(nodes[1], 0);
8876
8877         // ...still, nodes[1] will reject the duplicate channel.
8878         {
8879                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8880                 assert_eq!(events.len(), 1);
8881                 match events[0] {
8882                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8883                                 // Technically, at this point, nodes[1] would be justified in thinking both
8884                                 // channels are closed, but currently we do not, so we just move forward with it.
8885                                 assert_eq!(msg.channel_id, channel_id);
8886                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8887                         },
8888                         _ => panic!("Unexpected event"),
8889                 }
8890         }
8891
8892         // finally, finish creating the original channel and send a payment over it to make sure
8893         // everything is functional.
8894         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8895         {
8896                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8897                 assert_eq!(added_monitors.len(), 1);
8898                 assert_eq!(added_monitors[0].0, funding_output);
8899                 added_monitors.clear();
8900         }
8901         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8902
8903         let events_4 = nodes[0].node.get_and_clear_pending_events();
8904         assert_eq!(events_4.len(), 0);
8905         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8906         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8907
8908         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8909         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8910         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8911
8912         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8913 }
8914
8915 #[test]
8916 fn test_error_chans_closed() {
8917         // Test that we properly handle error messages, closing appropriate channels.
8918         //
8919         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8920         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8921         // we can test various edge cases around it to ensure we don't regress.
8922         let chanmon_cfgs = create_chanmon_cfgs(3);
8923         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8924         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8925         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8926
8927         // Create some initial channels
8928         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8929         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8930         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8931
8932         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8933         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8934         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8935
8936         // Closing a channel from a different peer has no effect
8937         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8938         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8939
8940         // Closing one channel doesn't impact others
8941         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8942         check_added_monitors!(nodes[0], 1);
8943         check_closed_broadcast!(nodes[0], false);
8944         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
8945                 [nodes[1].node.get_our_node_id()], 100000);
8946         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8947         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8948         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);
8949         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);
8950
8951         // A null channel ID should close all channels
8952         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8953         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8954         check_added_monitors!(nodes[0], 2);
8955         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
8956                 [nodes[1].node.get_our_node_id(); 2], 100000);
8957         let events = nodes[0].node.get_and_clear_pending_msg_events();
8958         assert_eq!(events.len(), 2);
8959         match events[0] {
8960                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8961                         assert_eq!(msg.contents.flags & 2, 2);
8962                 },
8963                 _ => panic!("Unexpected event"),
8964         }
8965         match events[1] {
8966                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8967                         assert_eq!(msg.contents.flags & 2, 2);
8968                 },
8969                 _ => panic!("Unexpected event"),
8970         }
8971         // Note that at this point users of a standard PeerHandler will end up calling
8972         // peer_disconnected.
8973         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8974         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8975
8976         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8977         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8978         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8979 }
8980
8981 #[test]
8982 fn test_invalid_funding_tx() {
8983         // Test that we properly handle invalid funding transactions sent to us from a peer.
8984         //
8985         // Previously, all other major lightning implementations had failed to properly sanitize
8986         // funding transactions from their counterparties, leading to a multi-implementation critical
8987         // security vulnerability (though we always sanitized properly, we've previously had
8988         // un-released crashes in the sanitization process).
8989         //
8990         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8991         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8992         // gave up on it. We test this here by generating such a transaction.
8993         let chanmon_cfgs = create_chanmon_cfgs(2);
8994         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8995         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8996         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8997
8998         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8999         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()));
9000         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()));
9001
9002         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9003
9004         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9005         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9006         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9007         // its length.
9008         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9009         let wit_program_script: Script = wit_program.into();
9010         for output in tx.output.iter_mut() {
9011                 // Make the confirmed funding transaction have a bogus script_pubkey
9012                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9013         }
9014
9015         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9016         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()));
9017         check_added_monitors!(nodes[1], 1);
9018         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9019
9020         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()));
9021         check_added_monitors!(nodes[0], 1);
9022         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9023
9024         let events_1 = nodes[0].node.get_and_clear_pending_events();
9025         assert_eq!(events_1.len(), 0);
9026
9027         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9028         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9029         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9030
9031         let expected_err = "funding tx had wrong script/value or output index";
9032         confirm_transaction_at(&nodes[1], &tx, 1);
9033         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9034                 [nodes[0].node.get_our_node_id()], 100000);
9035         check_added_monitors!(nodes[1], 1);
9036         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9037         assert_eq!(events_2.len(), 1);
9038         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9039                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9040                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9041                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9042                 } else { panic!(); }
9043         } else { panic!(); }
9044         assert_eq!(nodes[1].node.list_channels().len(), 0);
9045
9046         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9047         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9048         // as its not 32 bytes long.
9049         let mut spend_tx = Transaction {
9050                 version: 2i32, lock_time: PackedLockTime::ZERO,
9051                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9052                         previous_output: BitcoinOutPoint {
9053                                 txid: tx.txid(),
9054                                 vout: idx as u32,
9055                         },
9056                         script_sig: Script::new(),
9057                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9058                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9059                 }).collect(),
9060                 output: vec![TxOut {
9061                         value: 1000,
9062                         script_pubkey: Script::new(),
9063                 }]
9064         };
9065         check_spends!(spend_tx, tx);
9066         mine_transaction(&nodes[1], &spend_tx);
9067 }
9068
9069 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9070         // In the first version of the chain::Confirm interface, after a refactor was made to not
9071         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9072         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9073         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9074         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9075         // spending transaction until height N+1 (or greater). This was due to the way
9076         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9077         // spending transaction at the height the input transaction was confirmed at, not whether we
9078         // should broadcast a spending transaction at the current height.
9079         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9080         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9081         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9082         // until we learned about an additional block.
9083         //
9084         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9085         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9086         let chanmon_cfgs = create_chanmon_cfgs(3);
9087         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9088         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9089         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9090         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9091
9092         create_announced_chan_between_nodes(&nodes, 0, 1);
9093         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9094         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9095         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9096         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9097
9098         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9099         check_closed_broadcast!(nodes[1], true);
9100         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9101         check_added_monitors!(nodes[1], 1);
9102         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9103         assert_eq!(node_txn.len(), 1);
9104
9105         let conf_height = nodes[1].best_block_info().1;
9106         if !test_height_before_timelock {
9107                 connect_blocks(&nodes[1], 24 * 6);
9108         }
9109         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9110                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9111         if test_height_before_timelock {
9112                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9113                 // generate any events or broadcast any transactions
9114                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9115                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9116         } else {
9117                 // We should broadcast an HTLC transaction spending our funding transaction first
9118                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9119                 assert_eq!(spending_txn.len(), 2);
9120                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9121                 check_spends!(spending_txn[1], node_txn[0]);
9122                 // We should also generate a SpendableOutputs event with the to_self output (as its
9123                 // timelock is up).
9124                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9125                 assert_eq!(descriptor_spend_txn.len(), 1);
9126
9127                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9128                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9129                 // additional block built on top of the current chain.
9130                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9131                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9132                 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 }]);
9133                 check_added_monitors!(nodes[1], 1);
9134
9135                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9136                 assert!(updates.update_add_htlcs.is_empty());
9137                 assert!(updates.update_fulfill_htlcs.is_empty());
9138                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9139                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9140                 assert!(updates.update_fee.is_none());
9141                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9142                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9143                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9144         }
9145 }
9146
9147 #[test]
9148 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9149         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9150         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9151 }
9152
9153 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9154         let chanmon_cfgs = create_chanmon_cfgs(2);
9155         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9156         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9157         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9158
9159         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9160
9161         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9162                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9163         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9164
9165         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9166
9167         {
9168                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9169                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9170                 check_added_monitors!(nodes[0], 1);
9171                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9172                 assert_eq!(events.len(), 1);
9173                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9174                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9175                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9176         }
9177         expect_pending_htlcs_forwardable!(nodes[1]);
9178         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9179
9180         {
9181                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9182                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9183                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9184                 check_added_monitors!(nodes[0], 1);
9185                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9186                 assert_eq!(events.len(), 1);
9187                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9188                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9189                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9190                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9191                 // assume the second is a privacy attack (no longer particularly relevant
9192                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9193                 // the first HTLC delivered above.
9194         }
9195
9196         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9197         nodes[1].node.process_pending_htlc_forwards();
9198
9199         if test_for_second_fail_panic {
9200                 // Now we go fail back the first HTLC from the user end.
9201                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9202
9203                 let expected_destinations = vec![
9204                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9205                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9206                 ];
9207                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9208                 nodes[1].node.process_pending_htlc_forwards();
9209
9210                 check_added_monitors!(nodes[1], 1);
9211                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9212                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9213
9214                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9215                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9216                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9217
9218                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9219                 assert_eq!(failure_events.len(), 4);
9220                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9221                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9222                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9223                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9224         } else {
9225                 // Let the second HTLC fail and claim the first
9226                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9227                 nodes[1].node.process_pending_htlc_forwards();
9228
9229                 check_added_monitors!(nodes[1], 1);
9230                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9231                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9232                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9233
9234                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9235
9236                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9237         }
9238 }
9239
9240 #[test]
9241 fn test_dup_htlc_second_fail_panic() {
9242         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9243         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9244         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9245         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9246         do_test_dup_htlc_second_rejected(true);
9247 }
9248
9249 #[test]
9250 fn test_dup_htlc_second_rejected() {
9251         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9252         // simply reject the second HTLC but are still able to claim the first HTLC.
9253         do_test_dup_htlc_second_rejected(false);
9254 }
9255
9256 #[test]
9257 fn test_inconsistent_mpp_params() {
9258         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9259         // such HTLC and allow the second to stay.
9260         let chanmon_cfgs = create_chanmon_cfgs(4);
9261         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9262         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9263         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9264
9265         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9266         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9267         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9268         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9269
9270         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9271                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9272         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9273         assert_eq!(route.paths.len(), 2);
9274         route.paths.sort_by(|path_a, _| {
9275                 // Sort the path so that the path through nodes[1] comes first
9276                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9277                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9278         });
9279
9280         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9281
9282         let cur_height = nodes[0].best_block_info().1;
9283         let payment_id = PaymentId([42; 32]);
9284
9285         let session_privs = {
9286                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9287                 // ultimately have, just not right away.
9288                 let mut dup_route = route.clone();
9289                 dup_route.paths.push(route.paths[1].clone());
9290                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9291                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9292         };
9293         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9294                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9295                 &None, session_privs[0]).unwrap();
9296         check_added_monitors!(nodes[0], 1);
9297
9298         {
9299                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9300                 assert_eq!(events.len(), 1);
9301                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9302         }
9303         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9304
9305         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9306                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9307         check_added_monitors!(nodes[0], 1);
9308
9309         {
9310                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9311                 assert_eq!(events.len(), 1);
9312                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9313
9314                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9315                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9316
9317                 expect_pending_htlcs_forwardable!(nodes[2]);
9318                 check_added_monitors!(nodes[2], 1);
9319
9320                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9321                 assert_eq!(events.len(), 1);
9322                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9323
9324                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9325                 check_added_monitors!(nodes[3], 0);
9326                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9327
9328                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9329                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9330                 // post-payment_secrets) and fail back the new HTLC.
9331         }
9332         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9333         nodes[3].node.process_pending_htlc_forwards();
9334         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9335         nodes[3].node.process_pending_htlc_forwards();
9336
9337         check_added_monitors!(nodes[3], 1);
9338
9339         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9340         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9341         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9342
9343         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 }]);
9344         check_added_monitors!(nodes[2], 1);
9345
9346         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9347         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9348         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9349
9350         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9351
9352         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9353                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9354                 &None, session_privs[2]).unwrap();
9355         check_added_monitors!(nodes[0], 1);
9356
9357         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9358         assert_eq!(events.len(), 1);
9359         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9360
9361         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9362         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9363 }
9364
9365 #[test]
9366 fn test_double_partial_claim() {
9367         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9368         // time out, the sender resends only some of the MPP parts, then the user processes the
9369         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9370         // amount.
9371         let chanmon_cfgs = create_chanmon_cfgs(4);
9372         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9373         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9374         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9375
9376         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9377         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9378         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9379         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9380
9381         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9382         assert_eq!(route.paths.len(), 2);
9383         route.paths.sort_by(|path_a, _| {
9384                 // Sort the path so that the path through nodes[1] comes first
9385                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9386                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9387         });
9388
9389         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9390         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9391         // amount of time to respond to.
9392
9393         // Connect some blocks to time out the payment
9394         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9395         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9396
9397         let failed_destinations = vec![
9398                 HTLCDestination::FailedPayment { payment_hash },
9399                 HTLCDestination::FailedPayment { payment_hash },
9400         ];
9401         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9402
9403         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9404
9405         // nodes[1] now retries one of the two paths...
9406         nodes[0].node.send_payment_with_route(&route, payment_hash,
9407                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9408         check_added_monitors!(nodes[0], 2);
9409
9410         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9411         assert_eq!(events.len(), 2);
9412         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9413         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9414
9415         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9416         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9417         nodes[3].node.claim_funds(payment_preimage);
9418         check_added_monitors!(nodes[3], 0);
9419         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9420 }
9421
9422 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9423 #[derive(Clone, Copy, PartialEq)]
9424 enum ExposureEvent {
9425         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9426         AtHTLCForward,
9427         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9428         AtHTLCReception,
9429         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9430         AtUpdateFeeOutbound,
9431 }
9432
9433 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9434         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9435         // policy.
9436         //
9437         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9438         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9439         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9440         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9441         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9442         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9443         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9444         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9445
9446         let chanmon_cfgs = create_chanmon_cfgs(2);
9447         let mut config = test_default_channel_config();
9448         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9449                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9450                 // to get roughly the same initial value as the default setting when this test was
9451                 // originally written.
9452                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9453         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9456         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9457
9458         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9459         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9460         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9461         open_channel.max_accepted_htlcs = 60;
9462         if on_holder_tx {
9463                 open_channel.dust_limit_satoshis = 546;
9464         }
9465         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9466         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9467         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9468
9469         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9470
9471         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9472
9473         if on_holder_tx {
9474                 let mut node_0_per_peer_lock;
9475                 let mut node_0_peer_state_lock;
9476                 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);
9477                 chan.context.holder_dust_limit_satoshis = 546;
9478         }
9479
9480         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9481         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()));
9482         check_added_monitors!(nodes[1], 1);
9483         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9484
9485         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()));
9486         check_added_monitors!(nodes[0], 1);
9487         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9488
9489         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9490         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9491         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9492
9493         // Fetch a route in advance as we will be unable to once we're unable to send.
9494         let (mut route, payment_hash, _, payment_secret) =
9495                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9496
9497         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9498                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9499                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9500                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9501                 (chan.context.get_dust_buffer_feerate(None) as u64,
9502                 chan.context.get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9503         };
9504         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;
9505         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9506
9507         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;
9508         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9509
9510         let dust_htlc_on_counterparty_tx: u64 = 4;
9511         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9512
9513         if on_holder_tx {
9514                 if dust_outbound_balance {
9515                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9516                         // Outbound dust balance: 4372 sats
9517                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9518                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9519                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9520                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9521                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9522                         }
9523                 } else {
9524                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9525                         // Inbound dust balance: 4372 sats
9526                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9527                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9528                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9529                         }
9530                 }
9531         } else {
9532                 if dust_outbound_balance {
9533                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9534                         // Outbound dust balance: 5000 sats
9535                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9536                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9537                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9538                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9539                         }
9540                 } else {
9541                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9542                         // Inbound dust balance: 5000 sats
9543                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9544                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9545                         }
9546                 }
9547         }
9548
9549         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9550                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9551                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9552                 // With default dust exposure: 5000 sats
9553                 if on_holder_tx {
9554                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9555                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9556                                 ), true, APIError::ChannelUnavailable { .. }, {});
9557                 } else {
9558                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9559                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9560                                 ), true, APIError::ChannelUnavailable { .. }, {});
9561                 }
9562         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9563                 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 });
9564                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9565                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9566                 check_added_monitors!(nodes[1], 1);
9567                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9568                 assert_eq!(events.len(), 1);
9569                 let payment_event = SendEvent::from_event(events.remove(0));
9570                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9571                 // With default dust exposure: 5000 sats
9572                 if on_holder_tx {
9573                         // Outbound dust balance: 6399 sats
9574                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9575                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9576                         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);
9577                 } else {
9578                         // Outbound dust balance: 5200 sats
9579                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9580                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9581                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9582                                         max_dust_htlc_exposure_msat), 1);
9583                 }
9584         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9585                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9586                 // For the multiplier dust exposure limit, since it scales with feerate,
9587                 // we need to add a lot of HTLCs that will become dust at the new feerate
9588                 // to cross the threshold.
9589                 for _ in 0..20 {
9590                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9591                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9592                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9593                 }
9594                 {
9595                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9596                         *feerate_lock = *feerate_lock * 10;
9597                 }
9598                 nodes[0].node.timer_tick_occurred();
9599                 check_added_monitors!(nodes[0], 1);
9600                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9601         }
9602
9603         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9604         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9605         added_monitors.clear();
9606 }
9607
9608 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9609         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9610         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9611         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9612         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9613         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9614         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9615         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9616         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9617         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9618         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9619         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9620         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9621 }
9622
9623 #[test]
9624 fn test_max_dust_htlc_exposure() {
9625         do_test_max_dust_htlc_exposure_by_threshold_type(false);
9626         do_test_max_dust_htlc_exposure_by_threshold_type(true);
9627 }
9628
9629 #[test]
9630 fn test_non_final_funding_tx() {
9631         let chanmon_cfgs = create_chanmon_cfgs(2);
9632         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9633         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9634         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9635
9636         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9637         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9638         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9639         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9640         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9641
9642         let best_height = nodes[0].node.best_block.read().unwrap().height();
9643
9644         let chan_id = *nodes[0].network_chan_count.borrow();
9645         let events = nodes[0].node.get_and_clear_pending_events();
9646         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9647         assert_eq!(events.len(), 1);
9648         let mut tx = match events[0] {
9649                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9650                         // Timelock the transaction _beyond_ the best client height + 1.
9651                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9652                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9653                         }]}
9654                 },
9655                 _ => panic!("Unexpected event"),
9656         };
9657         // Transaction should fail as it's evaluated as non-final for propagation.
9658         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9659                 Err(APIError::APIMisuseError { err }) => {
9660                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9661                 },
9662                 _ => panic!()
9663         }
9664
9665         // However, transaction should be accepted if it's in a +1 headroom from best block.
9666         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9667         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9668         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9669 }
9670
9671 #[test]
9672 fn accept_busted_but_better_fee() {
9673         // If a peer sends us a fee update that is too low, but higher than our previous channel
9674         // feerate, we should accept it. In the future we may want to consider closing the channel
9675         // later, but for now we only accept the update.
9676         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9679         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9680
9681         create_chan_between_nodes(&nodes[0], &nodes[1]);
9682
9683         // Set nodes[1] to expect 5,000 sat/kW.
9684         {
9685                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9686                 *feerate_lock = 5000;
9687         }
9688
9689         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9690         {
9691                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9692                 *feerate_lock = 1000;
9693         }
9694         nodes[0].node.timer_tick_occurred();
9695         check_added_monitors!(nodes[0], 1);
9696
9697         let events = nodes[0].node.get_and_clear_pending_msg_events();
9698         assert_eq!(events.len(), 1);
9699         match events[0] {
9700                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9701                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9702                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9703                 },
9704                 _ => panic!("Unexpected event"),
9705         };
9706
9707         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9708         // it.
9709         {
9710                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9711                 *feerate_lock = 2000;
9712         }
9713         nodes[0].node.timer_tick_occurred();
9714         check_added_monitors!(nodes[0], 1);
9715
9716         let events = nodes[0].node.get_and_clear_pending_msg_events();
9717         assert_eq!(events.len(), 1);
9718         match events[0] {
9719                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9720                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9721                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9722                 },
9723                 _ => panic!("Unexpected event"),
9724         };
9725
9726         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9727         // channel.
9728         {
9729                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9730                 *feerate_lock = 1000;
9731         }
9732         nodes[0].node.timer_tick_occurred();
9733         check_added_monitors!(nodes[0], 1);
9734
9735         let events = nodes[0].node.get_and_clear_pending_msg_events();
9736         assert_eq!(events.len(), 1);
9737         match events[0] {
9738                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9739                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9740                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9741                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9742                                 [nodes[0].node.get_our_node_id()], 100000);
9743                         check_closed_broadcast!(nodes[1], true);
9744                         check_added_monitors!(nodes[1], 1);
9745                 },
9746                 _ => panic!("Unexpected event"),
9747         };
9748 }
9749
9750 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9751         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9754         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9755         let min_final_cltv_expiry_delta = 120;
9756         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9757                 min_final_cltv_expiry_delta - 2 };
9758         let recv_value = 100_000;
9759
9760         create_chan_between_nodes(&nodes[0], &nodes[1]);
9761
9762         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9763         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9764                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9765                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9766                 (payment_hash, payment_preimage, payment_secret)
9767         } else {
9768                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9769                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9770         };
9771         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9772         nodes[0].node.send_payment_with_route(&route, payment_hash,
9773                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9774         check_added_monitors!(nodes[0], 1);
9775         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9776         assert_eq!(events.len(), 1);
9777         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9778         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9779         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9780         expect_pending_htlcs_forwardable!(nodes[1]);
9781
9782         if valid_delta {
9783                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9784                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9785
9786                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9787         } else {
9788                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9789
9790                 check_added_monitors!(nodes[1], 1);
9791
9792                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9793                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9794                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9795
9796                 expect_payment_failed!(nodes[0], payment_hash, true);
9797         }
9798 }
9799
9800 #[test]
9801 fn test_payment_with_custom_min_cltv_expiry_delta() {
9802         do_payment_with_custom_min_final_cltv_expiry(false, false);
9803         do_payment_with_custom_min_final_cltv_expiry(false, true);
9804         do_payment_with_custom_min_final_cltv_expiry(true, false);
9805         do_payment_with_custom_min_final_cltv_expiry(true, true);
9806 }
9807
9808 #[test]
9809 fn test_disconnects_peer_awaiting_response_ticks() {
9810         // Tests that nodes which are awaiting on a response critical for channel responsiveness
9811         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9812         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9813         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9814         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9815         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9816
9817         // Asserts a disconnect event is queued to the user.
9818         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9819                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9820                         if let MessageSendEvent::HandleError { action, .. } = event {
9821                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9822                                         Some(())
9823                                 } else {
9824                                         None
9825                                 }
9826                         } else {
9827                                 None
9828                         }
9829                 );
9830                 assert_eq!(disconnect_event.is_some(), should_disconnect);
9831         };
9832
9833         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9834         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9835         let check_disconnect = |node: &Node| {
9836                 // No disconnect without any timer ticks.
9837                 check_disconnect_event(node, false);
9838
9839                 // No disconnect with 1 timer tick less than required.
9840                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9841                         node.node.timer_tick_occurred();
9842                         check_disconnect_event(node, false);
9843                 }
9844
9845                 // Disconnect after reaching the required ticks.
9846                 node.node.timer_tick_occurred();
9847                 check_disconnect_event(node, true);
9848
9849                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9850                 node.node.timer_tick_occurred();
9851                 check_disconnect_event(node, true);
9852         };
9853
9854         create_chan_between_nodes(&nodes[0], &nodes[1]);
9855
9856         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9857         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9858         nodes[0].node.timer_tick_occurred();
9859         check_added_monitors!(&nodes[0], 1);
9860         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9861         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9862         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9863         check_added_monitors!(&nodes[1], 1);
9864
9865         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9866         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9867         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9868         check_added_monitors!(&nodes[0], 1);
9869         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9870         check_added_monitors(&nodes[0], 1);
9871
9872         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9873         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9874         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9875         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9876         check_disconnect(&nodes[1]);
9877
9878         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
9879         //
9880         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
9881         // final `RevokeAndACK` to Bob to complete it.
9882         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9883         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9884         let bob_init = msgs::Init {
9885                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
9886         };
9887         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
9888         let alice_init = msgs::Init {
9889                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9890         };
9891         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
9892
9893         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
9894         // received Bob's yet, so she should disconnect him after reaching
9895         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9896         let alice_channel_reestablish = get_event_msg!(
9897                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
9898         );
9899         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
9900         check_disconnect(&nodes[0]);
9901
9902         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
9903         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
9904                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
9905                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9906                         Some(msg.clone())
9907                 } else {
9908                         None
9909                 }
9910         ).unwrap();
9911         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
9912
9913         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
9914         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9915                 nodes[0].node.timer_tick_occurred();
9916                 check_disconnect_event(&nodes[0], false);
9917         }
9918
9919         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
9920         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9921         check_disconnect(&nodes[1]);
9922
9923         // Finally, have Bob process the last message.
9924         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
9925         check_added_monitors(&nodes[1], 1);
9926
9927         // At this point, neither node should attempt to disconnect each other, since they aren't
9928         // waiting on any messages.
9929         for node in &nodes {
9930                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9931                         node.node.timer_tick_occurred();
9932                         check_disconnect_event(node, false);
9933                 }
9934         }
9935 }
9936
9937 #[test]
9938 fn test_remove_expired_outbound_unfunded_channels() {
9939         let chanmon_cfgs = create_chanmon_cfgs(2);
9940         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9941         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9942         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9943
9944         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9945         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9946         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9947         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9948         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9949
9950         let events = nodes[0].node.get_and_clear_pending_events();
9951         assert_eq!(events.len(), 1);
9952         match events[0] {
9953                 Event::FundingGenerationReady { .. } => (),
9954                 _ => panic!("Unexpected event"),
9955         };
9956
9957         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
9958         let check_outbound_channel_existence = |should_exist: bool| {
9959                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9960                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9961                 assert_eq!(chan_lock.outbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
9962         };
9963
9964         // Channel should exist without any timer ticks.
9965         check_outbound_channel_existence(true);
9966
9967         // Channel should exist with 1 timer tick less than required.
9968         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
9969                 nodes[0].node.timer_tick_occurred();
9970                 check_outbound_channel_existence(true)
9971         }
9972
9973         // Remove channel after reaching the required ticks.
9974         nodes[0].node.timer_tick_occurred();
9975         check_outbound_channel_existence(false);
9976
9977         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
9978         assert_eq!(msg_events.len(), 1);
9979         match msg_events[0] {
9980                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
9981                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
9982                 },
9983                 _ => panic!("Unexpected event"),
9984         }
9985         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
9986 }
9987
9988 #[test]
9989 fn test_remove_expired_inbound_unfunded_channels() {
9990         let chanmon_cfgs = create_chanmon_cfgs(2);
9991         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9992         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9993         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9994
9995         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9996         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9997         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9998         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9999         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10000
10001         let events = nodes[0].node.get_and_clear_pending_events();
10002         assert_eq!(events.len(), 1);
10003         match events[0] {
10004                 Event::FundingGenerationReady { .. } => (),
10005                 _ => panic!("Unexpected event"),
10006         };
10007
10008         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10009         let check_inbound_channel_existence = |should_exist: bool| {
10010                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10011                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10012                 assert_eq!(chan_lock.inbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10013         };
10014
10015         // Channel should exist without any timer ticks.
10016         check_inbound_channel_existence(true);
10017
10018         // Channel should exist with 1 timer tick less than required.
10019         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10020                 nodes[1].node.timer_tick_occurred();
10021                 check_inbound_channel_existence(true)
10022         }
10023
10024         // Remove channel after reaching the required ticks.
10025         nodes[1].node.timer_tick_occurred();
10026         check_inbound_channel_existence(false);
10027
10028         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10029         assert_eq!(msg_events.len(), 1);
10030         match msg_events[0] {
10031                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10032                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10033                 },
10034                 _ => panic!("Unexpected event"),
10035         }
10036         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10037 }