Replace `send_htlc` amount checking with available balances
[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};
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::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, 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;
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 #[test]
65 fn test_insane_channel_opens() {
66         // Stand up a network of 2 nodes
67         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68         let mut cfg = UserConfig::default();
69         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70         let chanmon_cfgs = create_chanmon_cfgs(2);
71         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74
75         // Instantiate channel parameters where we push the maximum msats given our
76         // funding satoshis
77         let channel_value_sat = 31337; // same as funding satoshis
78         let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80
81         // Have node0 initiate a channel to node1 with aforementioned parameters
82         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83
84         // Extract the channel open message from node0 to node1
85         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86
87         // Test helper that asserts we get the correct error string given a mutator
88         // that supposedly makes the channel open message insane
89         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92                 assert_eq!(msg_events.len(), 1);
93                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95                         match action {
96                                 &ErrorAction::SendErrorMessage { .. } => {
97                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
98                                 },
99                                 _ => panic!("unexpected event!"),
100                         }
101                 } else { assert!(false); }
102         };
103
104         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105
106         // Test all mutations that would make the channel open message insane
107         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 });
108         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 });
109
110         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111
112         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 });
113
114         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115
116         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 });
117
118         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 });
119
120         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121
122         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 }
124
125 #[test]
126 fn test_funding_exceeds_no_wumbo_limit() {
127         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128         // them.
129         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130         let chanmon_cfgs = create_chanmon_cfgs(2);
131         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135
136         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137                 Err(APIError::APIMisuseError { err }) => {
138                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139                 },
140                 _ => panic!()
141         }
142 }
143
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148         // in normal testing, we test it explicitly here.
149         let chanmon_cfgs = create_chanmon_cfgs(2);
150         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153         let default_config = UserConfig::default();
154
155         // Have node0 initiate a channel to node1 with aforementioned parameters
156         let mut push_amt = 100_000_000;
157         let feerate_per_kw = 253;
158         let opt_anchors = false;
159         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
161
162         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();
163         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164         if !send_from_initiator {
165                 open_channel_message.channel_reserve_satoshis = 0;
166                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
167         }
168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
169
170         // Extract the channel accept message from node1 to node0
171         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172         if send_from_initiator {
173                 accept_channel_message.channel_reserve_satoshis = 0;
174                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
175         }
176         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
177         {
178                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180                 let mut sender_node_per_peer_lock;
181                 let mut sender_node_peer_state_lock;
182                 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183                 chan.holder_selected_channel_reserve_satoshis = 0;
184                 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
185         }
186
187         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
190
191         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193         if send_from_initiator {
194                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195                         // Note that for outbound channels we have to consider the commitment tx fee and the
196                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197                         // well as an additional HTLC.
198                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
199         } else {
200                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
201         }
202 }
203
204 #[test]
205 fn test_counterparty_no_reserve() {
206         do_test_counterparty_no_reserve(true);
207         do_test_counterparty_no_reserve(false);
208 }
209
210 #[test]
211 fn test_async_inbound_update_fee() {
212         let chanmon_cfgs = create_chanmon_cfgs(2);
213         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216         create_announced_chan_between_nodes(&nodes, 0, 1);
217
218         // balancing
219         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220
221         // A                                        B
222         // update_fee                            ->
223         // send (1) commitment_signed            -.
224         //                                       <- update_add_htlc/commitment_signed
225         // send (2) RAA (awaiting remote revoke) -.
226         // (1) commitment_signed is delivered    ->
227         //                                       .- send (3) RAA (awaiting remote revoke)
228         // (2) RAA is delivered                  ->
229         //                                       .- send (4) commitment_signed
230         //                                       <- (3) RAA is delivered
231         // send (5) commitment_signed            -.
232         //                                       <- (4) commitment_signed is delivered
233         // send (6) RAA                          -.
234         // (5) commitment_signed is delivered    ->
235         //                                       <- RAA
236         // (6) RAA is delivered                  ->
237
238         // First nodes[0] generates an update_fee
239         {
240                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
241                 *feerate_lock += 20;
242         }
243         nodes[0].node.timer_tick_occurred();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let (update_msg, commitment_signed) = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250                         (update_fee.as_ref(), commitment_signed)
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         // deliver(1), generate (3):
279         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282         check_added_monitors!(nodes[1], 1);
283
284         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290         assert!(bs_update.update_fee.is_none()); // (4)
291         check_added_monitors!(nodes[1], 1);
292
293         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295         assert!(as_update.update_add_htlcs.is_empty()); // (5)
296         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299         assert!(as_update.update_fee.is_none()); // (5)
300         check_added_monitors!(nodes[0], 1);
301
302         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304         // only (6) so get_event_msg's assert(len == 1) passes
305         check_added_monitors!(nodes[0], 1);
306
307         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309         check_added_monitors!(nodes[1], 1);
310
311         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312         check_added_monitors!(nodes[0], 1);
313
314         let events_2 = nodes[0].node.get_and_clear_pending_events();
315         assert_eq!(events_2.len(), 1);
316         match events_2[0] {
317                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318                 _ => panic!("Unexpected event"),
319         }
320
321         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322         check_added_monitors!(nodes[1], 1);
323 }
324
325 #[test]
326 fn test_update_fee_unordered_raa() {
327         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328         // crash in an earlier version of the update_fee patch)
329         let chanmon_cfgs = create_chanmon_cfgs(2);
330         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333         create_announced_chan_between_nodes(&nodes, 0, 1);
334
335         // balancing
336         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
337
338         // First nodes[0] generates an update_fee
339         {
340                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
341                 *feerate_lock += 20;
342         }
343         nodes[0].node.timer_tick_occurred();
344         check_added_monitors!(nodes[0], 1);
345
346         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347         assert_eq!(events_0.len(), 1);
348         let update_msg = match events_0[0] { // (1)
349                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
350                         update_fee.as_ref()
351                 },
352                 _ => panic!("Unexpected event"),
353         };
354
355         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
356
357         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
360                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361         check_added_monitors!(nodes[1], 1);
362
363         let payment_event = {
364                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365                 assert_eq!(events_1.len(), 1);
366                 SendEvent::from_event(events_1.remove(0))
367         };
368         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369         assert_eq!(payment_event.msgs.len(), 1);
370
371         // ...now when the messages get delivered everyone should be happy
372         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376         check_added_monitors!(nodes[0], 1);
377
378         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379         check_added_monitors!(nodes[1], 1);
380
381         // We can't continue, sadly, because our (1) now has a bogus signature
382 }
383
384 #[test]
385 fn test_multi_flight_update_fee() {
386         let chanmon_cfgs = create_chanmon_cfgs(2);
387         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390         create_announced_chan_between_nodes(&nodes, 0, 1);
391
392         // A                                        B
393         // update_fee/commitment_signed          ->
394         //                                       .- send (1) RAA and (2) commitment_signed
395         // update_fee (never committed)          ->
396         // (3) update_fee                        ->
397         // We have to manually generate the above update_fee, it is allowed by the protocol but we
398         // don't track which updates correspond to which revoke_and_ack responses so we're in
399         // AwaitingRAA mode and will not generate the update_fee yet.
400         //                                       <- (1) RAA delivered
401         // (3) is generated and send (4) CS      -.
402         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403         // know the per_commitment_point to use for it.
404         //                                       <- (2) commitment_signed delivered
405         // revoke_and_ack                        ->
406         //                                          B should send no response here
407         // (4) commitment_signed delivered       ->
408         //                                       <- RAA/commitment_signed delivered
409         // revoke_and_ack                        ->
410
411         // First nodes[0] generates an update_fee
412         let initial_feerate;
413         {
414                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415                 initial_feerate = *feerate_lock;
416                 *feerate_lock = initial_feerate + 20;
417         }
418         nodes[0].node.timer_tick_occurred();
419         check_added_monitors!(nodes[0], 1);
420
421         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422         assert_eq!(events_0.len(), 1);
423         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425                         (update_fee.as_ref().unwrap(), commitment_signed)
426                 },
427                 _ => panic!("Unexpected event"),
428         };
429
430         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434         check_added_monitors!(nodes[1], 1);
435
436         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
437         // transaction:
438         {
439                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440                 *feerate_lock = initial_feerate + 40;
441         }
442         nodes[0].node.timer_tick_occurred();
443         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
445
446         // Create the (3) update_fee message that nodes[0] will generate before it does...
447         let mut update_msg_2 = msgs::UpdateFee {
448                 channel_id: update_msg_1.channel_id.clone(),
449                 feerate_per_kw: (initial_feerate + 30) as u32,
450         };
451
452         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
453
454         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
455         // Deliver (3)
456         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
457
458         // Deliver (1), generating (3) and (4)
459         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461         check_added_monitors!(nodes[0], 1);
462         assert!(as_second_update.update_add_htlcs.is_empty());
463         assert!(as_second_update.update_fulfill_htlcs.is_empty());
464         assert!(as_second_update.update_fail_htlcs.is_empty());
465         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466         // Check that the update_fee newly generated matches what we delivered:
467         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
469
470         // Deliver (2) commitment_signed
471         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473         check_added_monitors!(nodes[0], 1);
474         // No commitment_signed so get_event_msg's assert(len == 1) passes
475
476         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478         check_added_monitors!(nodes[1], 1);
479
480         // Delever (4)
481         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483         check_added_monitors!(nodes[1], 1);
484
485         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487         check_added_monitors!(nodes[0], 1);
488
489         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491         // No commitment_signed so get_event_msg's assert(len == 1) passes
492         check_added_monitors!(nodes[0], 1);
493
494         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496         check_added_monitors!(nodes[1], 1);
497 }
498
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500         // Previously, we had issues deserializing channels when we hadn't connected the first block
501         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502         // serialization round-trips and simply do steps towards opening a channel and then drop the
503         // Node objects.
504
505         let chanmon_cfgs = create_chanmon_cfgs(2);
506         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
509
510         if steps & 0b1000_0000 != 0{
511                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512                 connect_block(&nodes[0], &block);
513                 connect_block(&nodes[1], &block);
514         }
515
516         if steps & 0x0f == 0 { return; }
517         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
519
520         if steps & 0x0f == 1 { return; }
521         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
523
524         if steps & 0x0f == 2 { return; }
525         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
526
527         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
528
529         if steps & 0x0f == 3 { return; }
530         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531         check_added_monitors!(nodes[0], 0);
532         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
533
534         if steps & 0x0f == 4 { return; }
535         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
536         {
537                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538                 assert_eq!(added_monitors.len(), 1);
539                 assert_eq!(added_monitors[0].0, funding_output);
540                 added_monitors.clear();
541         }
542         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
543
544         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
545
546         if steps & 0x0f == 5 { return; }
547         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
548         {
549                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550                 assert_eq!(added_monitors.len(), 1);
551                 assert_eq!(added_monitors[0].0, funding_output);
552                 added_monitors.clear();
553         }
554
555         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556         let events_4 = nodes[0].node.get_and_clear_pending_events();
557         assert_eq!(events_4.len(), 0);
558
559         if steps & 0x0f == 6 { return; }
560         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
561
562         if steps & 0x0f == 7 { return; }
563         confirm_transaction_at(&nodes[0], &tx, 2);
564         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
567 }
568
569 #[test]
570 fn test_sanity_on_in_flight_opens() {
571         do_test_sanity_on_in_flight_opens(0);
572         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573         do_test_sanity_on_in_flight_opens(1);
574         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575         do_test_sanity_on_in_flight_opens(2);
576         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577         do_test_sanity_on_in_flight_opens(3);
578         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579         do_test_sanity_on_in_flight_opens(4);
580         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581         do_test_sanity_on_in_flight_opens(5);
582         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(6);
584         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(7);
586         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(8);
588         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
589 }
590
591 #[test]
592 fn test_update_fee_vanilla() {
593         let chanmon_cfgs = create_chanmon_cfgs(2);
594         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597         create_announced_chan_between_nodes(&nodes, 0, 1);
598
599         {
600                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
601                 *feerate_lock += 25;
602         }
603         nodes[0].node.timer_tick_occurred();
604         check_added_monitors!(nodes[0], 1);
605
606         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607         assert_eq!(events_0.len(), 1);
608         let (update_msg, commitment_signed) = match events_0[0] {
609                         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 } } => {
610                         (update_fee.as_ref(), commitment_signed)
611                 },
612                 _ => panic!("Unexpected event"),
613         };
614         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
615
616         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618         check_added_monitors!(nodes[1], 1);
619
620         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622         check_added_monitors!(nodes[0], 1);
623
624         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626         // No commitment_signed so get_event_msg's assert(len == 1) passes
627         check_added_monitors!(nodes[0], 1);
628
629         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631         check_added_monitors!(nodes[1], 1);
632 }
633
634 #[test]
635 fn test_update_fee_that_funder_cannot_afford() {
636         let chanmon_cfgs = create_chanmon_cfgs(2);
637         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640         let channel_value = 5000;
641         let push_sats = 700;
642         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643         let channel_id = chan.2;
644         let secp_ctx = Secp256k1::new();
645         let default_config = UserConfig::default();
646         let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
647
648         let opt_anchors = false;
649
650         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652         // calculate two different feerates here - the expected local limit as well as the expected
653         // remote limit.
654         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
655         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
656         {
657                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658                 *feerate_lock = feerate;
659         }
660         nodes[0].node.timer_tick_occurred();
661         check_added_monitors!(nodes[0], 1);
662         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
663
664         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
665
666         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
667
668         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
669         {
670                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
671
672                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673                 assert_eq!(commitment_tx.output.len(), 2);
674                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676                 actual_fee = channel_value - actual_fee;
677                 assert_eq!(total_fee, actual_fee);
678         }
679
680         {
681                 // Increment the feerate by a small constant, accounting for rounding errors
682                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
683                 *feerate_lock += 4;
684         }
685         nodes[0].node.timer_tick_occurred();
686         nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687         check_added_monitors!(nodes[0], 0);
688
689         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
690
691         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692         // needed to sign the new commitment tx and (2) sign the new commitment tx.
693         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697                 let chan_signer = local_chan.get_signer();
698                 let pubkeys = chan_signer.pubkeys();
699                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700                  pubkeys.funding_pubkey)
701         };
702         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706                 let chan_signer = remote_chan.get_signer();
707                 let pubkeys = chan_signer.pubkeys();
708                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710                  pubkeys.funding_pubkey)
711         };
712
713         // Assemble the set of keys we can use for signatures for our commitment_signed message.
714         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
716
717         let res = {
718                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721                 let local_chan_signer = local_chan.get_signer();
722                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724                         INITIAL_COMMITMENT_NUMBER - 1,
725                         push_sats,
726                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727                         opt_anchors, local_funding, remote_funding,
728                         commit_tx_keys.clone(),
729                         non_buffer_feerate + 4,
730                         &mut htlcs,
731                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
732                 );
733                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
734         };
735
736         let commit_signed_msg = msgs::CommitmentSigned {
737                 channel_id: chan.2,
738                 signature: res.0,
739                 htlc_signatures: res.1,
740                 #[cfg(taproot)]
741                 partial_signature_with_nonce: None,
742         };
743
744         let update_fee = msgs::UpdateFee {
745                 channel_id: chan.2,
746                 feerate_per_kw: non_buffer_feerate + 4,
747         };
748
749         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
750
751         //While producing the commitment_signed response after handling a received update_fee request the
752         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753         //Should produce and error.
754         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756         check_added_monitors!(nodes[1], 1);
757         check_closed_broadcast!(nodes[1], true);
758         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
759 }
760
761 #[test]
762 fn test_update_fee_with_fundee_update_add_htlc() {
763         let chanmon_cfgs = create_chanmon_cfgs(2);
764         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
768
769         // balancing
770         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
771
772         {
773                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
774                 *feerate_lock += 20;
775         }
776         nodes[0].node.timer_tick_occurred();
777         check_added_monitors!(nodes[0], 1);
778
779         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780         assert_eq!(events_0.len(), 1);
781         let (update_msg, commitment_signed) = match events_0[0] {
782                         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 } } => {
783                         (update_fee.as_ref(), commitment_signed)
784                 },
785                 _ => panic!("Unexpected event"),
786         };
787         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790         check_added_monitors!(nodes[1], 1);
791
792         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
793
794         // nothing happens since node[1] is in AwaitingRemoteRevoke
795         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
797         {
798                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799                 assert_eq!(added_monitors.len(), 0);
800                 added_monitors.clear();
801         }
802         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804         // node[1] has nothing to do
805
806         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808         check_added_monitors!(nodes[0], 1);
809
810         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812         // No commitment_signed so get_event_msg's assert(len == 1) passes
813         check_added_monitors!(nodes[0], 1);
814         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815         check_added_monitors!(nodes[1], 1);
816         // AwaitingRemoteRevoke ends here
817
818         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823         assert_eq!(commitment_update.update_fee.is_none(), true);
824
825         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827         check_added_monitors!(nodes[0], 1);
828         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
829
830         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831         check_added_monitors!(nodes[1], 1);
832         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
833
834         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835         check_added_monitors!(nodes[1], 1);
836         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837         // No commitment_signed so get_event_msg's assert(len == 1) passes
838
839         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840         check_added_monitors!(nodes[0], 1);
841         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
842
843         expect_pending_htlcs_forwardable!(nodes[0]);
844
845         let events = nodes[0].node.get_and_clear_pending_events();
846         assert_eq!(events.len(), 1);
847         match events[0] {
848                 Event::PaymentClaimable { .. } => { },
849                 _ => panic!("Unexpected event"),
850         };
851
852         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
853
854         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
859 }
860
861 #[test]
862 fn test_update_fee() {
863         let chanmon_cfgs = create_chanmon_cfgs(2);
864         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868         let channel_id = chan.2;
869
870         // A                                        B
871         // (1) update_fee/commitment_signed      ->
872         //                                       <- (2) revoke_and_ack
873         //                                       .- send (3) commitment_signed
874         // (4) update_fee/commitment_signed      ->
875         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876         //                                       <- (3) commitment_signed delivered
877         // send (6) revoke_and_ack               -.
878         //                                       <- (5) deliver revoke_and_ack
879         // (6) deliver revoke_and_ack            ->
880         //                                       .- send (7) commitment_signed in response to (4)
881         //                                       <- (7) deliver commitment_signed
882         // revoke_and_ack                        ->
883
884         // Create and deliver (1)...
885         let feerate;
886         {
887                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888                 feerate = *feerate_lock;
889                 *feerate_lock = feerate + 20;
890         }
891         nodes[0].node.timer_tick_occurred();
892         check_added_monitors!(nodes[0], 1);
893
894         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895         assert_eq!(events_0.len(), 1);
896         let (update_msg, commitment_signed) = match events_0[0] {
897                         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 } } => {
898                         (update_fee.as_ref(), commitment_signed)
899                 },
900                 _ => panic!("Unexpected event"),
901         };
902         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
903
904         // Generate (2) and (3):
905         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907         check_added_monitors!(nodes[1], 1);
908
909         // Deliver (2):
910         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912         check_added_monitors!(nodes[0], 1);
913
914         // Create and deliver (4)...
915         {
916                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917                 *feerate_lock = feerate + 30;
918         }
919         nodes[0].node.timer_tick_occurred();
920         check_added_monitors!(nodes[0], 1);
921         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922         assert_eq!(events_0.len(), 1);
923         let (update_msg, commitment_signed) = match events_0[0] {
924                         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 } } => {
925                         (update_fee.as_ref(), commitment_signed)
926                 },
927                 _ => panic!("Unexpected event"),
928         };
929
930         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932         check_added_monitors!(nodes[1], 1);
933         // ... creating (5)
934         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935         // No commitment_signed so get_event_msg's assert(len == 1) passes
936
937         // Handle (3), creating (6):
938         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939         check_added_monitors!(nodes[0], 1);
940         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941         // No commitment_signed so get_event_msg's assert(len == 1) passes
942
943         // Deliver (5):
944         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946         check_added_monitors!(nodes[0], 1);
947
948         // Deliver (6), creating (7):
949         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951         assert!(commitment_update.update_add_htlcs.is_empty());
952         assert!(commitment_update.update_fulfill_htlcs.is_empty());
953         assert!(commitment_update.update_fail_htlcs.is_empty());
954         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955         assert!(commitment_update.update_fee.is_none());
956         check_added_monitors!(nodes[1], 1);
957
958         // Deliver (7)
959         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960         check_added_monitors!(nodes[0], 1);
961         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962         // No commitment_signed so get_event_msg's assert(len == 1) passes
963
964         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965         check_added_monitors!(nodes[1], 1);
966         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
967
968         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
973 }
974
975 #[test]
976 fn fake_network_test() {
977         // Simple test which builds a network of ChannelManagers, connects them to each other, and
978         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979         let chanmon_cfgs = create_chanmon_cfgs(4);
980         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
983
984         // Create some initial channels
985         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
988
989         // Rebalance the network a bit by relaying one payment through all the channels...
990         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
994
995         // Send some more payments
996         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
999
1000         // Test failure packets
1001         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1003
1004         // Add a new channel that skips 3
1005         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1006
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1014
1015         // Do some rebalance loop payments, simultaneously
1016         let mut hops = Vec::with_capacity(3);
1017         hops.push(RouteHop {
1018                 pubkey: nodes[2].node.get_our_node_id(),
1019                 node_features: NodeFeatures::empty(),
1020                 short_channel_id: chan_2.0.contents.short_channel_id,
1021                 channel_features: ChannelFeatures::empty(),
1022                 fee_msat: 0,
1023                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1024         });
1025         hops.push(RouteHop {
1026                 pubkey: nodes[3].node.get_our_node_id(),
1027                 node_features: NodeFeatures::empty(),
1028                 short_channel_id: chan_3.0.contents.short_channel_id,
1029                 channel_features: ChannelFeatures::empty(),
1030                 fee_msat: 0,
1031                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1032         });
1033         hops.push(RouteHop {
1034                 pubkey: nodes[1].node.get_our_node_id(),
1035                 node_features: nodes[1].node.node_features(),
1036                 short_channel_id: chan_4.0.contents.short_channel_id,
1037                 channel_features: nodes[1].node.channel_features(),
1038                 fee_msat: 1000000,
1039                 cltv_expiry_delta: TEST_FINAL_CLTV,
1040         });
1041         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;
1042         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;
1043         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;
1044
1045         let mut hops = Vec::with_capacity(3);
1046         hops.push(RouteHop {
1047                 pubkey: nodes[3].node.get_our_node_id(),
1048                 node_features: NodeFeatures::empty(),
1049                 short_channel_id: chan_4.0.contents.short_channel_id,
1050                 channel_features: ChannelFeatures::empty(),
1051                 fee_msat: 0,
1052                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1053         });
1054         hops.push(RouteHop {
1055                 pubkey: nodes[2].node.get_our_node_id(),
1056                 node_features: NodeFeatures::empty(),
1057                 short_channel_id: chan_3.0.contents.short_channel_id,
1058                 channel_features: ChannelFeatures::empty(),
1059                 fee_msat: 0,
1060                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1061         });
1062         hops.push(RouteHop {
1063                 pubkey: nodes[1].node.get_our_node_id(),
1064                 node_features: nodes[1].node.node_features(),
1065                 short_channel_id: chan_2.0.contents.short_channel_id,
1066                 channel_features: nodes[1].node.channel_features(),
1067                 fee_msat: 1000000,
1068                 cltv_expiry_delta: TEST_FINAL_CLTV,
1069         });
1070         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;
1071         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;
1072         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;
1073
1074         // Claim the rebalances...
1075         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1077
1078         // Close down the channels...
1079         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091 }
1092
1093 #[test]
1094 fn holding_cell_htlc_counting() {
1095         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097         // commitment dance rounds.
1098         let chanmon_cfgs = create_chanmon_cfgs(3);
1099         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102         create_announced_chan_between_nodes(&nodes, 0, 1);
1103         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1104
1105         // Fetch a route in advance as we will be unable to once we're unable to send.
1106         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1107
1108         let mut payments = Vec::new();
1109         for _ in 0..50 {
1110                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1112                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1113                 payments.push((payment_preimage, payment_hash));
1114         }
1115         check_added_monitors!(nodes[1], 1);
1116
1117         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1118         assert_eq!(events.len(), 1);
1119         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1120         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1121
1122         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1123         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1124         // another HTLC.
1125         {
1126                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1127                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1128                         ), true, APIError::ChannelUnavailable { .. }, {});
1129                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1130         }
1131
1132         // This should also be true if we try to forward a payment.
1133         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1134         {
1135                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137                 check_added_monitors!(nodes[0], 1);
1138         }
1139
1140         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141         assert_eq!(events.len(), 1);
1142         let payment_event = SendEvent::from_event(events.pop().unwrap());
1143         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1144
1145         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148         // fails), the second will process the resulting failure and fail the HTLC backward.
1149         expect_pending_htlcs_forwardable!(nodes[1]);
1150         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 }]);
1151         check_added_monitors!(nodes[1], 1);
1152
1153         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1156
1157         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1158
1159         // Now forward all the pending HTLCs and claim them back
1160         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162         check_added_monitors!(nodes[2], 1);
1163
1164         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166         check_added_monitors!(nodes[1], 1);
1167         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1168
1169         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170         check_added_monitors!(nodes[1], 1);
1171         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172
1173         for ref update in as_updates.update_add_htlcs.iter() {
1174                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1175         }
1176         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177         check_added_monitors!(nodes[2], 1);
1178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179         check_added_monitors!(nodes[2], 1);
1180         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1181
1182         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183         check_added_monitors!(nodes[1], 1);
1184         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185         check_added_monitors!(nodes[1], 1);
1186         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1187
1188         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189         check_added_monitors!(nodes[2], 1);
1190
1191         expect_pending_htlcs_forwardable!(nodes[2]);
1192
1193         let events = nodes[2].node.get_and_clear_pending_events();
1194         assert_eq!(events.len(), payments.len());
1195         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1196                 match event {
1197                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1198                                 assert_eq!(*payment_hash, *hash);
1199                         },
1200                         _ => panic!("Unexpected event"),
1201                 };
1202         }
1203
1204         for (preimage, _) in payments.drain(..) {
1205                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1206         }
1207
1208         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1209 }
1210
1211 #[test]
1212 fn duplicate_htlc_test() {
1213         // Test that we accept duplicate payment_hash HTLCs across the network and that
1214         // claiming/failing them are all separate and don't affect each other
1215         let chanmon_cfgs = create_chanmon_cfgs(6);
1216         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1219
1220         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221         create_announced_chan_between_nodes(&nodes, 0, 3);
1222         create_announced_chan_between_nodes(&nodes, 1, 3);
1223         create_announced_chan_between_nodes(&nodes, 2, 3);
1224         create_announced_chan_between_nodes(&nodes, 3, 4);
1225         create_announced_chan_between_nodes(&nodes, 3, 5);
1226
1227         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1228
1229         *nodes[0].network_payment_count.borrow_mut() -= 1;
1230         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1231
1232         *nodes[0].network_payment_count.borrow_mut() -= 1;
1233         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1234
1235         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1238 }
1239
1240 #[test]
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242         // Test that ChannelMonitor doesn't generate 2 preimage txn
1243         // when we have 2 HTLCs with same preimage that go across a node
1244         // in opposite directions, even with the same payment secret.
1245         let chanmon_cfgs = create_chanmon_cfgs(2);
1246         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1249
1250         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1251
1252         // balancing
1253         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1254
1255         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1256
1257         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1260
1261         // Provide preimage to node 0 by claiming payment
1262         nodes[0].node.claim_funds(payment_preimage);
1263         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264         check_added_monitors!(nodes[0], 1);
1265
1266         // Broadcast node 1 commitment txn
1267         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1268
1269         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270         let mut has_both_htlcs = 0; // check htlcs match ones committed
1271         for outp in remote_txn[0].output.iter() {
1272                 if outp.value == 800_000 / 1000 {
1273                         has_both_htlcs += 1;
1274                 } else if outp.value == 900_000 / 1000 {
1275                         has_both_htlcs += 1;
1276                 }
1277         }
1278         assert_eq!(has_both_htlcs, 2);
1279
1280         mine_transaction(&nodes[0], &remote_txn[0]);
1281         check_added_monitors!(nodes[0], 1);
1282         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1284
1285         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286         assert_eq!(claim_txn.len(), 3);
1287
1288         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289         check_spends!(claim_txn[1], remote_txn[0]);
1290         check_spends!(claim_txn[2], remote_txn[0]);
1291         let preimage_tx = &claim_txn[0];
1292         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293                 (&claim_txn[1], &claim_txn[2])
1294         } else {
1295                 (&claim_txn[2], &claim_txn[1])
1296         };
1297
1298         assert_eq!(preimage_tx.input.len(), 1);
1299         assert_eq!(preimage_bump_tx.input.len(), 1);
1300
1301         assert_eq!(preimage_tx.input.len(), 1);
1302         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1304
1305         assert_eq!(timeout_tx.input.len(), 1);
1306         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307         check_spends!(timeout_tx, remote_txn[0]);
1308         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1309
1310         let events = nodes[0].node.get_and_clear_pending_msg_events();
1311         assert_eq!(events.len(), 3);
1312         for e in events {
1313                 match e {
1314                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317                                 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1318                         },
1319                         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, .. } } => {
1320                                 assert!(update_add_htlcs.is_empty());
1321                                 assert!(update_fail_htlcs.is_empty());
1322                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1323                                 assert!(update_fail_malformed_htlcs.is_empty());
1324                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1325                         },
1326                         _ => panic!("Unexpected event"),
1327                 }
1328         }
1329 }
1330
1331 #[test]
1332 fn test_basic_channel_reserve() {
1333         let chanmon_cfgs = create_chanmon_cfgs(2);
1334         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1338
1339         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340         let channel_reserve = chan_stat.channel_reserve_msat;
1341
1342         // The 2* and +1 are for the fee spike reserve.
1343         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1344         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345         let (mut route, our_payment_hash, _, our_payment_secret) =
1346                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1347         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1348         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1349                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1350         match err {
1351                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1352                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1353                         else { panic!("Unexpected error variant"); }
1354                 },
1355                 _ => panic!("Unexpected error variant"),
1356         }
1357         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1358
1359         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1360 }
1361
1362 #[test]
1363 fn test_fee_spike_violation_fails_htlc() {
1364         let chanmon_cfgs = create_chanmon_cfgs(2);
1365         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1366         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1367         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1368         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1369
1370         let (mut route, payment_hash, _, payment_secret) =
1371                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1372         route.paths[0].hops[0].fee_msat += 1;
1373         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1374         let secp_ctx = Secp256k1::new();
1375         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1376
1377         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1378
1379         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1380         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1381                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1382         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1383         let msg = msgs::UpdateAddHTLC {
1384                 channel_id: chan.2,
1385                 htlc_id: 0,
1386                 amount_msat: htlc_msat,
1387                 payment_hash: payment_hash,
1388                 cltv_expiry: htlc_cltv,
1389                 onion_routing_packet: onion_packet,
1390         };
1391
1392         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1393
1394         // Now manually create the commitment_signed message corresponding to the update_add
1395         // nodes[0] just sent. In the code for construction of this message, "local" refers
1396         // to the sender of the message, and "remote" refers to the receiver.
1397
1398         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1399
1400         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1401
1402         // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1403         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1404         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1405                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1406                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1407                 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1408                 let chan_signer = local_chan.get_signer();
1409                 // Make the signer believe we validated another commitment, so we can release the secret
1410                 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1411
1412                 let pubkeys = chan_signer.pubkeys();
1413                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1414                  chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1415                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1416                  chan_signer.pubkeys().funding_pubkey)
1417         };
1418         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1419                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1420                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1421                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422                 let chan_signer = remote_chan.get_signer();
1423                 let pubkeys = chan_signer.pubkeys();
1424                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1425                  chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1426                  chan_signer.pubkeys().funding_pubkey)
1427         };
1428
1429         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1430         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1431                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1432
1433         // Build the remote commitment transaction so we can sign it, and then later use the
1434         // signature for the commitment_signed message.
1435         let local_chan_balance = 1313;
1436
1437         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1438                 offered: false,
1439                 amount_msat: 3460001,
1440                 cltv_expiry: htlc_cltv,
1441                 payment_hash,
1442                 transaction_output_index: Some(1),
1443         };
1444
1445         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1446
1447         let res = {
1448                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1449                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1450                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1451                 let local_chan_signer = local_chan.get_signer();
1452                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1453                         commitment_number,
1454                         95000,
1455                         local_chan_balance,
1456                         local_chan.opt_anchors(), local_funding, remote_funding,
1457                         commit_tx_keys.clone(),
1458                         feerate_per_kw,
1459                         &mut vec![(accepted_htlc_info, ())],
1460                         &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1461                 );
1462                 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1463         };
1464
1465         let commit_signed_msg = msgs::CommitmentSigned {
1466                 channel_id: chan.2,
1467                 signature: res.0,
1468                 htlc_signatures: res.1,
1469                 #[cfg(taproot)]
1470                 partial_signature_with_nonce: None,
1471         };
1472
1473         // Send the commitment_signed message to the nodes[1].
1474         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1475         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1476
1477         // Send the RAA to nodes[1].
1478         let raa_msg = msgs::RevokeAndACK {
1479                 channel_id: chan.2,
1480                 per_commitment_secret: local_secret,
1481                 next_per_commitment_point: next_local_point,
1482                 #[cfg(taproot)]
1483                 next_local_nonce: None,
1484         };
1485         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1486
1487         let events = nodes[1].node.get_and_clear_pending_msg_events();
1488         assert_eq!(events.len(), 1);
1489         // Make sure the HTLC failed in the way we expect.
1490         match events[0] {
1491                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1492                         assert_eq!(update_fail_htlcs.len(), 1);
1493                         update_fail_htlcs[0].clone()
1494                 },
1495                 _ => panic!("Unexpected event"),
1496         };
1497         nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1498                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1499
1500         check_added_monitors!(nodes[1], 2);
1501 }
1502
1503 #[test]
1504 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1505         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1506         // Set the fee rate for the channel very high, to the point where the fundee
1507         // sending any above-dust amount would result in a channel reserve violation.
1508         // In this test we check that we would be prevented from sending an HTLC in
1509         // this situation.
1510         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1511         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1512         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1513         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1514         let default_config = UserConfig::default();
1515         let opt_anchors = false;
1516
1517         let mut push_amt = 100_000_000;
1518         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1519
1520         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1521
1522         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1523
1524         // Fetch a route in advance as we will be unable to once we're unable to send.
1525         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1526         // Sending exactly enough to hit the reserve amount should be accepted
1527         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1528                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1529         }
1530
1531         // However one more HTLC should be significantly over the reserve amount and fail.
1532         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1533                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1534                 ), true, APIError::ChannelUnavailable { .. }, {});
1535         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1536 }
1537
1538 #[test]
1539 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1540         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1541         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1542         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1543         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1544         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1545         let default_config = UserConfig::default();
1546         let opt_anchors = false;
1547
1548         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1549         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1550         // transaction fee with 0 HTLCs (183 sats)).
1551         let mut push_amt = 100_000_000;
1552         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1553         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1554         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1555
1556         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1557         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1558                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1559         }
1560
1561         let (mut route, payment_hash, _, payment_secret) =
1562                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1563         route.paths[0].hops[0].fee_msat = 700_000;
1564         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1565         let secp_ctx = Secp256k1::new();
1566         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1567         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1568         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1569         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1570                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1571         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1572         let msg = msgs::UpdateAddHTLC {
1573                 channel_id: chan.2,
1574                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1575                 amount_msat: htlc_msat,
1576                 payment_hash: payment_hash,
1577                 cltv_expiry: htlc_cltv,
1578                 onion_routing_packet: onion_packet,
1579         };
1580
1581         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1582         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1583         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);
1584         assert_eq!(nodes[0].node.list_channels().len(), 0);
1585         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1586         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1587         check_added_monitors!(nodes[0], 1);
1588         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() });
1589 }
1590
1591 #[test]
1592 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1593         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1594         // calculating our commitment transaction fee (this was previously broken).
1595         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1596         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1597
1598         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1599         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1600         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1601         let default_config = UserConfig::default();
1602         let opt_anchors = false;
1603
1604         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1605         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1606         // transaction fee with 0 HTLCs (183 sats)).
1607         let mut push_amt = 100_000_000;
1608         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1609         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1610         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1611
1612         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1613                 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1614         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1615         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1616         // commitment transaction fee.
1617         let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1618
1619         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1620         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1621                 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1622         }
1623
1624         // One more than the dust amt should fail, however.
1625         let (mut route, our_payment_hash, _, our_payment_secret) =
1626                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1627         route.paths[0].hops[0].fee_msat += 1;
1628         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1629                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1630                 ), true, APIError::ChannelUnavailable { .. }, {});
1631 }
1632
1633 #[test]
1634 fn test_chan_init_feerate_unaffordability() {
1635         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1636         // channel reserve and feerate requirements.
1637         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1638         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1641         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1642         let default_config = UserConfig::default();
1643         let opt_anchors = false;
1644
1645         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1646         // HTLC.
1647         let mut push_amt = 100_000_000;
1648         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1649         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1650                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1651
1652         // During open, we don't have a "counterparty channel reserve" to check against, so that
1653         // requirement only comes into play on the open_channel handling side.
1654         push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1655         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1656         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1657         open_channel_msg.push_msat += 1;
1658         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1659
1660         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1661         assert_eq!(msg_events.len(), 1);
1662         match msg_events[0] {
1663                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1664                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1665                 },
1666                 _ => panic!("Unexpected event"),
1667         }
1668 }
1669
1670 #[test]
1671 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1672         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1673         // calculating our counterparty's commitment transaction fee (this was previously broken).
1674         let chanmon_cfgs = create_chanmon_cfgs(2);
1675         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1676         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1677         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1678         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1679
1680         let payment_amt = 46000; // Dust amount
1681         // In the previous code, these first four payments would succeed.
1682         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686
1687         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1688         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693
1694         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1695         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1696         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1697         let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698 }
1699
1700 #[test]
1701 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1702         let chanmon_cfgs = create_chanmon_cfgs(3);
1703         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1704         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1705         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1707         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1708
1709         let feemsat = 239;
1710         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1712         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1713         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1714
1715         // Add a 2* and +1 for the fee spike reserve.
1716         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1717         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;
1718         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1719
1720         // Add a pending HTLC.
1721         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1722         let payment_event_1 = {
1723                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1724                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1725                 check_added_monitors!(nodes[0], 1);
1726
1727                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1728                 assert_eq!(events.len(), 1);
1729                 SendEvent::from_event(events.remove(0))
1730         };
1731         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1732
1733         // Attempt to trigger a channel reserve violation --> payment failure.
1734         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1735         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;
1736         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1737         let mut route_2 = route_1.clone();
1738         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1739
1740         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1741         let secp_ctx = Secp256k1::new();
1742         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1743         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1744         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1745         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1746                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1747         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1748         let msg = msgs::UpdateAddHTLC {
1749                 channel_id: chan.2,
1750                 htlc_id: 1,
1751                 amount_msat: htlc_msat + 1,
1752                 payment_hash: our_payment_hash_1,
1753                 cltv_expiry: htlc_cltv,
1754                 onion_routing_packet: onion_packet,
1755         };
1756
1757         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1758         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1759         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1760         assert_eq!(nodes[1].node.list_channels().len(), 1);
1761         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1762         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1763         check_added_monitors!(nodes[1], 1);
1764         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1765 }
1766
1767 #[test]
1768 fn test_inbound_outbound_capacity_is_not_zero() {
1769         let chanmon_cfgs = create_chanmon_cfgs(2);
1770         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1772         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1773         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1774         let channels0 = node_chanmgrs[0].list_channels();
1775         let channels1 = node_chanmgrs[1].list_channels();
1776         let default_config = UserConfig::default();
1777         assert_eq!(channels0.len(), 1);
1778         assert_eq!(channels1.len(), 1);
1779
1780         let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1781         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1782         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1783
1784         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1785         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1786 }
1787
1788 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1789         (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1790 }
1791
1792 #[test]
1793 fn test_channel_reserve_holding_cell_htlcs() {
1794         let chanmon_cfgs = create_chanmon_cfgs(3);
1795         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1796         // When this test was written, the default base fee floated based on the HTLC count.
1797         // It is now fixed, so we simply set the fee to the expected value here.
1798         let mut config = test_default_channel_config();
1799         config.channel_config.forwarding_fee_base_msat = 239;
1800         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1801         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1802         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1803         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1804
1805         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1806         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1807
1808         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1809         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1810
1811         macro_rules! expect_forward {
1812                 ($node: expr) => {{
1813                         let mut events = $node.node.get_and_clear_pending_msg_events();
1814                         assert_eq!(events.len(), 1);
1815                         check_added_monitors!($node, 1);
1816                         let payment_event = SendEvent::from_event(events.remove(0));
1817                         payment_event
1818                 }}
1819         }
1820
1821         let feemsat = 239; // set above
1822         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1823         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1824         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1825
1826         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1827
1828         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1829         {
1830                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1831                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1832                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1833                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1834                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1835
1836                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1837                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1838                         ), true, APIError::ChannelUnavailable { .. }, {});
1839                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1840         }
1841
1842         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1843         // nodes[0]'s wealth
1844         loop {
1845                 let amt_msat = recv_value_0 + total_fee_msat;
1846                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1847                 // Also, ensure that each payment has enough to be over the dust limit to
1848                 // ensure it'll be included in each commit tx fee calculation.
1849                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1850                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1851                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1852                         break;
1853                 }
1854
1855                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1856                         .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1857                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1858                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1859                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1860
1861                 let (stat01_, stat11_, stat12_, stat22_) = (
1862                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1863                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1864                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1865                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1866                 );
1867
1868                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1869                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1870                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1871                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1872                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1873         }
1874
1875         // adding pending output.
1876         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1877         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1878         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1879         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1880         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1881         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1882         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1883         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1884         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1885         // policy.
1886         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1887         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1888         let amt_msat_1 = recv_value_1 + total_fee_msat;
1889
1890         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);
1891         let payment_event_1 = {
1892                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1893                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1894                 check_added_monitors!(nodes[0], 1);
1895
1896                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1897                 assert_eq!(events.len(), 1);
1898                 SendEvent::from_event(events.remove(0))
1899         };
1900         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1901
1902         // channel reserve test with htlc pending output > 0
1903         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1904         {
1905                 let mut route = route_1.clone();
1906                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1907                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1908                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1909                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1910                         ), true, APIError::ChannelUnavailable { .. }, {});
1911                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1912         }
1913
1914         // split the rest to test holding cell
1915         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1916         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1917         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1918         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1919         {
1920                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1921                 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);
1922         }
1923
1924         // now see if they go through on both sides
1925         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);
1926         // but this will stuck in the holding cell
1927         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1928                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1929         check_added_monitors!(nodes[0], 0);
1930         let events = nodes[0].node.get_and_clear_pending_events();
1931         assert_eq!(events.len(), 0);
1932
1933         // test with outbound holding cell amount > 0
1934         {
1935                 let (mut route, our_payment_hash, _, our_payment_secret) =
1936                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1937                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1938                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1939                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1940                         ), true, APIError::ChannelUnavailable { .. }, {});
1941                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1942         }
1943
1944         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);
1945         // this will also stuck in the holding cell
1946         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1947                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1948         check_added_monitors!(nodes[0], 0);
1949         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1950         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1951
1952         // flush the pending htlc
1953         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1954         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1955         check_added_monitors!(nodes[1], 1);
1956
1957         // the pending htlc should be promoted to committed
1958         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1959         check_added_monitors!(nodes[0], 1);
1960         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1961
1962         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1963         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1964         // No commitment_signed so get_event_msg's assert(len == 1) passes
1965         check_added_monitors!(nodes[0], 1);
1966
1967         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1968         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1969         check_added_monitors!(nodes[1], 1);
1970
1971         expect_pending_htlcs_forwardable!(nodes[1]);
1972
1973         let ref payment_event_11 = expect_forward!(nodes[1]);
1974         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1975         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1976
1977         expect_pending_htlcs_forwardable!(nodes[2]);
1978         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1979
1980         // flush the htlcs in the holding cell
1981         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1982         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1983         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1984         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1985         expect_pending_htlcs_forwardable!(nodes[1]);
1986
1987         let ref payment_event_3 = expect_forward!(nodes[1]);
1988         assert_eq!(payment_event_3.msgs.len(), 2);
1989         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1990         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1991
1992         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1993         expect_pending_htlcs_forwardable!(nodes[2]);
1994
1995         let events = nodes[2].node.get_and_clear_pending_events();
1996         assert_eq!(events.len(), 2);
1997         match events[0] {
1998                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1999                         assert_eq!(our_payment_hash_21, *payment_hash);
2000                         assert_eq!(recv_value_21, amount_msat);
2001                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2002                         assert_eq!(via_channel_id, Some(chan_2.2));
2003                         match &purpose {
2004                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2005                                         assert!(payment_preimage.is_none());
2006                                         assert_eq!(our_payment_secret_21, *payment_secret);
2007                                 },
2008                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2009                         }
2010                 },
2011                 _ => panic!("Unexpected event"),
2012         }
2013         match events[1] {
2014                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2015                         assert_eq!(our_payment_hash_22, *payment_hash);
2016                         assert_eq!(recv_value_22, amount_msat);
2017                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2018                         assert_eq!(via_channel_id, Some(chan_2.2));
2019                         match &purpose {
2020                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2021                                         assert!(payment_preimage.is_none());
2022                                         assert_eq!(our_payment_secret_22, *payment_secret);
2023                                 },
2024                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2025                         }
2026                 },
2027                 _ => panic!("Unexpected event"),
2028         }
2029
2030         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2031         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2032         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2033
2034         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2035         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2036         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2037
2038         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2039         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);
2040         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2041         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2042         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2043
2044         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2045         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2046 }
2047
2048 #[test]
2049 fn channel_reserve_in_flight_removes() {
2050         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2051         // can send to its counterparty, but due to update ordering, the other side may not yet have
2052         // considered those HTLCs fully removed.
2053         // This tests that we don't count HTLCs which will not be included in the next remote
2054         // commitment transaction towards the reserve value (as it implies no commitment transaction
2055         // will be generated which violates the remote reserve value).
2056         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2057         // To test this we:
2058         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2059         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2060         //    you only consider the value of the first HTLC, it may not),
2061         //  * start routing a third HTLC from A to B,
2062         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2063         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2064         //  * deliver the first fulfill from B
2065         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2066         //    claim,
2067         //  * deliver A's response CS and RAA.
2068         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2069         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2070         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2071         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2072         let chanmon_cfgs = create_chanmon_cfgs(2);
2073         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2074         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2075         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2076         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2077
2078         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2079         // Route the first two HTLCs.
2080         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2081         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2082         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2083
2084         // Start routing the third HTLC (this is just used to get everyone in the right state).
2085         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2086         let send_1 = {
2087                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2088                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2089                 check_added_monitors!(nodes[0], 1);
2090                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2091                 assert_eq!(events.len(), 1);
2092                 SendEvent::from_event(events.remove(0))
2093         };
2094
2095         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2096         // initial fulfill/CS.
2097         nodes[1].node.claim_funds(payment_preimage_1);
2098         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2099         check_added_monitors!(nodes[1], 1);
2100         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2101
2102         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2103         // remove the second HTLC when we send the HTLC back from B to A.
2104         nodes[1].node.claim_funds(payment_preimage_2);
2105         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2106         check_added_monitors!(nodes[1], 1);
2107         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2108
2109         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2110         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2111         check_added_monitors!(nodes[0], 1);
2112         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2113         expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2114
2115         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2116         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2117         check_added_monitors!(nodes[1], 1);
2118         // B is already AwaitingRAA, so cant generate a CS here
2119         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2120
2121         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2122         check_added_monitors!(nodes[1], 1);
2123         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2124
2125         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2126         check_added_monitors!(nodes[0], 1);
2127         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2128
2129         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2130         check_added_monitors!(nodes[1], 1);
2131         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2132
2133         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2134         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2135         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2136         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2137         // on-chain as necessary).
2138         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2139         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2140         check_added_monitors!(nodes[0], 1);
2141         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2142         expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2143
2144         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2145         check_added_monitors!(nodes[1], 1);
2146         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2147
2148         expect_pending_htlcs_forwardable!(nodes[1]);
2149         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2150
2151         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2152         // resolve the second HTLC from A's point of view.
2153         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2154         check_added_monitors!(nodes[0], 1);
2155         expect_payment_path_successful!(nodes[0]);
2156         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2157
2158         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2159         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2160         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2161         let send_2 = {
2162                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2163                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2164                 check_added_monitors!(nodes[1], 1);
2165                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2166                 assert_eq!(events.len(), 1);
2167                 SendEvent::from_event(events.remove(0))
2168         };
2169
2170         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2171         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2172         check_added_monitors!(nodes[0], 1);
2173         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2174
2175         // Now just resolve all the outstanding messages/HTLCs for completeness...
2176
2177         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2178         check_added_monitors!(nodes[1], 1);
2179         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2180
2181         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2182         check_added_monitors!(nodes[1], 1);
2183
2184         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2185         check_added_monitors!(nodes[0], 1);
2186         expect_payment_path_successful!(nodes[0]);
2187         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2188
2189         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2190         check_added_monitors!(nodes[1], 1);
2191         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2192
2193         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2194         check_added_monitors!(nodes[0], 1);
2195
2196         expect_pending_htlcs_forwardable!(nodes[0]);
2197         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2198
2199         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2200         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2201 }
2202
2203 #[test]
2204 fn channel_monitor_network_test() {
2205         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2206         // tests that ChannelMonitor is able to recover from various states.
2207         let chanmon_cfgs = create_chanmon_cfgs(5);
2208         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2209         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2210         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2211
2212         // Create some initial channels
2213         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2214         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2215         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2216         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2217
2218         // Make sure all nodes are at the same starting height
2219         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2220         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2221         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2222         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2223         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2224
2225         // Rebalance the network a bit by relaying one payment through all the channels...
2226         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2227         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2228         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2229         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2230
2231         // Simple case with no pending HTLCs:
2232         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2233         check_added_monitors!(nodes[1], 1);
2234         check_closed_broadcast!(nodes[1], true);
2235         {
2236                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2237                 assert_eq!(node_txn.len(), 1);
2238                 mine_transaction(&nodes[0], &node_txn[0]);
2239                 check_added_monitors!(nodes[0], 1);
2240                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2241         }
2242         check_closed_broadcast!(nodes[0], true);
2243         assert_eq!(nodes[0].node.list_channels().len(), 0);
2244         assert_eq!(nodes[1].node.list_channels().len(), 1);
2245         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2246         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2247
2248         // One pending HTLC is discarded by the force-close:
2249         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2250
2251         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2252         // broadcasted until we reach the timelock time).
2253         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2254         check_closed_broadcast!(nodes[1], true);
2255         check_added_monitors!(nodes[1], 1);
2256         {
2257                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2258                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2259                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2260                 mine_transaction(&nodes[2], &node_txn[0]);
2261                 check_added_monitors!(nodes[2], 1);
2262                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2263         }
2264         check_closed_broadcast!(nodes[2], true);
2265         assert_eq!(nodes[1].node.list_channels().len(), 0);
2266         assert_eq!(nodes[2].node.list_channels().len(), 1);
2267         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2268         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2269
2270         macro_rules! claim_funds {
2271                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2272                         {
2273                                 $node.node.claim_funds($preimage);
2274                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2275                                 check_added_monitors!($node, 1);
2276
2277                                 let events = $node.node.get_and_clear_pending_msg_events();
2278                                 assert_eq!(events.len(), 1);
2279                                 match events[0] {
2280                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2281                                                 assert!(update_add_htlcs.is_empty());
2282                                                 assert!(update_fail_htlcs.is_empty());
2283                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2284                                         },
2285                                         _ => panic!("Unexpected event"),
2286                                 };
2287                         }
2288                 }
2289         }
2290
2291         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2292         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2293         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2294         check_added_monitors!(nodes[2], 1);
2295         check_closed_broadcast!(nodes[2], true);
2296         let node2_commitment_txid;
2297         {
2298                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2299                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2300                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2301                 node2_commitment_txid = node_txn[0].txid();
2302
2303                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2304                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2305                 mine_transaction(&nodes[3], &node_txn[0]);
2306                 check_added_monitors!(nodes[3], 1);
2307                 check_preimage_claim(&nodes[3], &node_txn);
2308         }
2309         check_closed_broadcast!(nodes[3], true);
2310         assert_eq!(nodes[2].node.list_channels().len(), 0);
2311         assert_eq!(nodes[3].node.list_channels().len(), 1);
2312         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2313         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2314
2315         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2316         // confusing us in the following tests.
2317         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2318
2319         // One pending HTLC to time out:
2320         let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2321         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2322         // buffer space).
2323
2324         let (close_chan_update_1, close_chan_update_2) = {
2325                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2326                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2327                 assert_eq!(events.len(), 2);
2328                 let close_chan_update_1 = match events[0] {
2329                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2330                                 msg.clone()
2331                         },
2332                         _ => panic!("Unexpected event"),
2333                 };
2334                 match events[1] {
2335                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2336                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2337                         },
2338                         _ => panic!("Unexpected event"),
2339                 }
2340                 check_added_monitors!(nodes[3], 1);
2341
2342                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2343                 {
2344                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2345                         node_txn.retain(|tx| {
2346                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2347                                         false
2348                                 } else { true }
2349                         });
2350                 }
2351
2352                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2353
2354                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2355                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2356
2357                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2358                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2359                 assert_eq!(events.len(), 2);
2360                 let close_chan_update_2 = match events[0] {
2361                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2362                                 msg.clone()
2363                         },
2364                         _ => panic!("Unexpected event"),
2365                 };
2366                 match events[1] {
2367                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2368                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2369                         },
2370                         _ => panic!("Unexpected event"),
2371                 }
2372                 check_added_monitors!(nodes[4], 1);
2373                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2374
2375                 mine_transaction(&nodes[4], &node_txn[0]);
2376                 check_preimage_claim(&nodes[4], &node_txn);
2377                 (close_chan_update_1, close_chan_update_2)
2378         };
2379         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2380         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2381         assert_eq!(nodes[3].node.list_channels().len(), 0);
2382         assert_eq!(nodes[4].node.list_channels().len(), 0);
2383
2384         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2385                 ChannelMonitorUpdateStatus::Completed);
2386         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2387         check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2388 }
2389
2390 #[test]
2391 fn test_justice_tx_htlc_timeout() {
2392         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2393         let mut alice_config = UserConfig::default();
2394         alice_config.channel_handshake_config.announced_channel = true;
2395         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2396         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2397         let mut bob_config = UserConfig::default();
2398         bob_config.channel_handshake_config.announced_channel = true;
2399         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2400         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2401         let user_cfgs = [Some(alice_config), Some(bob_config)];
2402         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2403         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2404         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2405         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2406         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2407         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2408         // Create some new channels:
2409         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2410
2411         // A pending HTLC which will be revoked:
2412         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2413         // Get the will-be-revoked local txn from nodes[0]
2414         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2415         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2416         assert_eq!(revoked_local_txn[0].input.len(), 1);
2417         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2418         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2419         assert_eq!(revoked_local_txn[1].input.len(), 1);
2420         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2421         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2422         // Revoke the old state
2423         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2424
2425         {
2426                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2427                 {
2428                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2430                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2431                         check_spends!(node_txn[0], revoked_local_txn[0]);
2432                         node_txn.swap_remove(0);
2433                 }
2434                 check_added_monitors!(nodes[1], 1);
2435                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2436                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2437
2438                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2439                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2440                 // Verify broadcast of revoked HTLC-timeout
2441                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2442                 check_added_monitors!(nodes[0], 1);
2443                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2444                 // Broadcast revoked HTLC-timeout on node 1
2445                 mine_transaction(&nodes[1], &node_txn[1]);
2446                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2447         }
2448         get_announce_close_broadcast_events(&nodes, 0, 1);
2449         assert_eq!(nodes[0].node.list_channels().len(), 0);
2450         assert_eq!(nodes[1].node.list_channels().len(), 0);
2451 }
2452
2453 #[test]
2454 fn test_justice_tx_htlc_success() {
2455         // Test justice txn built on revoked HTLC-Success tx, against both sides
2456         let mut alice_config = UserConfig::default();
2457         alice_config.channel_handshake_config.announced_channel = true;
2458         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2459         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2460         let mut bob_config = UserConfig::default();
2461         bob_config.channel_handshake_config.announced_channel = true;
2462         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2463         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2464         let user_cfgs = [Some(alice_config), Some(bob_config)];
2465         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2466         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2467         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2468         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2469         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2470         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2471         // Create some new channels:
2472         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2473
2474         // A pending HTLC which will be revoked:
2475         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2476         // Get the will-be-revoked local txn from B
2477         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2478         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2479         assert_eq!(revoked_local_txn[0].input.len(), 1);
2480         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2481         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2482         // Revoke the old state
2483         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2484         {
2485                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2486                 {
2487                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2488                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2489                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2490
2491                         check_spends!(node_txn[0], revoked_local_txn[0]);
2492                         node_txn.swap_remove(0);
2493                 }
2494                 check_added_monitors!(nodes[0], 1);
2495                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2496
2497                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2498                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2499                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2500                 check_added_monitors!(nodes[1], 1);
2501                 mine_transaction(&nodes[0], &node_txn[1]);
2502                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2503                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2504         }
2505         get_announce_close_broadcast_events(&nodes, 0, 1);
2506         assert_eq!(nodes[0].node.list_channels().len(), 0);
2507         assert_eq!(nodes[1].node.list_channels().len(), 0);
2508 }
2509
2510 #[test]
2511 fn revoked_output_claim() {
2512         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2513         // transaction is broadcast by its counterparty
2514         let chanmon_cfgs = create_chanmon_cfgs(2);
2515         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2516         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2517         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2518         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2519         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2520         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2521         assert_eq!(revoked_local_txn.len(), 1);
2522         // Only output is the full channel value back to nodes[0]:
2523         assert_eq!(revoked_local_txn[0].output.len(), 1);
2524         // Send a payment through, updating everyone's latest commitment txn
2525         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2526
2527         // Inform nodes[1] that nodes[0] broadcast a stale tx
2528         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2529         check_added_monitors!(nodes[1], 1);
2530         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2531         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2532         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2533
2534         check_spends!(node_txn[0], revoked_local_txn[0]);
2535
2536         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2537         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2538         get_announce_close_broadcast_events(&nodes, 0, 1);
2539         check_added_monitors!(nodes[0], 1);
2540         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2541 }
2542
2543 #[test]
2544 fn claim_htlc_outputs_shared_tx() {
2545         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2546         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2547         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2548         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2549         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2550         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2551
2552         // Create some new channel:
2553         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2554
2555         // Rebalance the network to generate htlc in the two directions
2556         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2557         // 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
2558         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2559         let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2560
2561         // Get the will-be-revoked local txn from node[0]
2562         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2563         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2564         assert_eq!(revoked_local_txn[0].input.len(), 1);
2565         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2566         assert_eq!(revoked_local_txn[1].input.len(), 1);
2567         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2568         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2569         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2570
2571         //Revoke the old state
2572         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2573
2574         {
2575                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2576                 check_added_monitors!(nodes[0], 1);
2577                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2578                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2579                 check_added_monitors!(nodes[1], 1);
2580                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2581                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2582                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2583
2584                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2585                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2586
2587                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2588                 check_spends!(node_txn[0], revoked_local_txn[0]);
2589
2590                 let mut witness_lens = BTreeSet::new();
2591                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2592                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2593                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2594                 assert_eq!(witness_lens.len(), 3);
2595                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2596                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2597                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2598
2599                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2600                 // ANTI_REORG_DELAY confirmations.
2601                 mine_transaction(&nodes[1], &node_txn[0]);
2602                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2603                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2604         }
2605         get_announce_close_broadcast_events(&nodes, 0, 1);
2606         assert_eq!(nodes[0].node.list_channels().len(), 0);
2607         assert_eq!(nodes[1].node.list_channels().len(), 0);
2608 }
2609
2610 #[test]
2611 fn claim_htlc_outputs_single_tx() {
2612         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2613         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2614         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2617         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2618
2619         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2620
2621         // Rebalance the network to generate htlc in the two directions
2622         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2623         // 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
2624         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2625         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2626         let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2627
2628         // Get the will-be-revoked local txn from node[0]
2629         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2630
2631         //Revoke the old state
2632         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2633
2634         {
2635                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2636                 check_added_monitors!(nodes[0], 1);
2637                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2638                 check_added_monitors!(nodes[1], 1);
2639                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2640                 let mut events = nodes[0].node.get_and_clear_pending_events();
2641                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2642                 match events.last().unwrap() {
2643                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2644                         _ => panic!("Unexpected event"),
2645                 }
2646
2647                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2648                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2649
2650                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2651
2652                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2653                 assert_eq!(node_txn[0].input.len(), 1);
2654                 check_spends!(node_txn[0], chan_1.3);
2655                 assert_eq!(node_txn[1].input.len(), 1);
2656                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2657                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2658                 check_spends!(node_txn[1], node_txn[0]);
2659
2660                 // Filter out any non justice transactions.
2661                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2662                 assert!(node_txn.len() > 3);
2663
2664                 assert_eq!(node_txn[0].input.len(), 1);
2665                 assert_eq!(node_txn[1].input.len(), 1);
2666                 assert_eq!(node_txn[2].input.len(), 1);
2667
2668                 check_spends!(node_txn[0], revoked_local_txn[0]);
2669                 check_spends!(node_txn[1], revoked_local_txn[0]);
2670                 check_spends!(node_txn[2], revoked_local_txn[0]);
2671
2672                 let mut witness_lens = BTreeSet::new();
2673                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2674                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2675                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2676                 assert_eq!(witness_lens.len(), 3);
2677                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2678                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2679                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2680
2681                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2682                 // ANTI_REORG_DELAY confirmations.
2683                 mine_transaction(&nodes[1], &node_txn[0]);
2684                 mine_transaction(&nodes[1], &node_txn[1]);
2685                 mine_transaction(&nodes[1], &node_txn[2]);
2686                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2687                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2688         }
2689         get_announce_close_broadcast_events(&nodes, 0, 1);
2690         assert_eq!(nodes[0].node.list_channels().len(), 0);
2691         assert_eq!(nodes[1].node.list_channels().len(), 0);
2692 }
2693
2694 #[test]
2695 fn test_htlc_on_chain_success() {
2696         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2697         // the preimage backward accordingly. So here we test that ChannelManager is
2698         // broadcasting the right event to other nodes in payment path.
2699         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2700         // A --------------------> B ----------------------> C (preimage)
2701         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2702         // commitment transaction was broadcast.
2703         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2704         // towards B.
2705         // B should be able to claim via preimage if A then broadcasts its local tx.
2706         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2707         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2708         // PaymentSent event).
2709
2710         let chanmon_cfgs = create_chanmon_cfgs(3);
2711         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2712         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2713         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2714
2715         // Create some initial channels
2716         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2717         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2718
2719         // Ensure all nodes are at the same height
2720         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2721         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2722         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2723         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2724
2725         // Rebalance the network a bit by relaying one payment through all the channels...
2726         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2727         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2728
2729         let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2730         let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2731
2732         // Broadcast legit commitment tx from C on B's chain
2733         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2734         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2735         assert_eq!(commitment_tx.len(), 1);
2736         check_spends!(commitment_tx[0], chan_2.3);
2737         nodes[2].node.claim_funds(our_payment_preimage);
2738         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2739         nodes[2].node.claim_funds(our_payment_preimage_2);
2740         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2741         check_added_monitors!(nodes[2], 2);
2742         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2743         assert!(updates.update_add_htlcs.is_empty());
2744         assert!(updates.update_fail_htlcs.is_empty());
2745         assert!(updates.update_fail_malformed_htlcs.is_empty());
2746         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2747
2748         mine_transaction(&nodes[2], &commitment_tx[0]);
2749         check_closed_broadcast!(nodes[2], true);
2750         check_added_monitors!(nodes[2], 1);
2751         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2752         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2753         assert_eq!(node_txn.len(), 2);
2754         check_spends!(node_txn[0], commitment_tx[0]);
2755         check_spends!(node_txn[1], commitment_tx[0]);
2756         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2757         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2758         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2759         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2760         assert_eq!(node_txn[0].lock_time.0, 0);
2761         assert_eq!(node_txn[1].lock_time.0, 0);
2762
2763         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2764         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()]));
2765         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2766         {
2767                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2768                 assert_eq!(added_monitors.len(), 1);
2769                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2770                 added_monitors.clear();
2771         }
2772         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2773         assert_eq!(forwarded_events.len(), 3);
2774         match forwarded_events[0] {
2775                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2776                 _ => panic!("Unexpected event"),
2777         }
2778         let chan_id = Some(chan_1.2);
2779         match forwarded_events[1] {
2780                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2781                         assert_eq!(fee_earned_msat, Some(1000));
2782                         assert_eq!(prev_channel_id, chan_id);
2783                         assert_eq!(claim_from_onchain_tx, true);
2784                         assert_eq!(next_channel_id, Some(chan_2.2));
2785                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2786                 },
2787                 _ => panic!()
2788         }
2789         match forwarded_events[2] {
2790                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2791                         assert_eq!(fee_earned_msat, Some(1000));
2792                         assert_eq!(prev_channel_id, chan_id);
2793                         assert_eq!(claim_from_onchain_tx, true);
2794                         assert_eq!(next_channel_id, Some(chan_2.2));
2795                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2796                 },
2797                 _ => panic!()
2798         }
2799         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2800         {
2801                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2802                 assert_eq!(added_monitors.len(), 2);
2803                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2804                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2805                 added_monitors.clear();
2806         }
2807         assert_eq!(events.len(), 3);
2808
2809         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2810         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2811
2812         match nodes_2_event {
2813                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2814                 _ => panic!("Unexpected event"),
2815         }
2816
2817         match nodes_0_event {
2818                 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, .. } } => {
2819                         assert!(update_add_htlcs.is_empty());
2820                         assert!(update_fail_htlcs.is_empty());
2821                         assert_eq!(update_fulfill_htlcs.len(), 1);
2822                         assert!(update_fail_malformed_htlcs.is_empty());
2823                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2824                 },
2825                 _ => panic!("Unexpected event"),
2826         };
2827
2828         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2829         match events[0] {
2830                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2831                 _ => panic!("Unexpected event"),
2832         }
2833
2834         macro_rules! check_tx_local_broadcast {
2835                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2836                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2837                         assert_eq!(node_txn.len(), 2);
2838                         // Node[1]: 2 * HTLC-timeout tx
2839                         // Node[0]: 2 * HTLC-timeout tx
2840                         check_spends!(node_txn[0], $commitment_tx);
2841                         check_spends!(node_txn[1], $commitment_tx);
2842                         assert_ne!(node_txn[0].lock_time.0, 0);
2843                         assert_ne!(node_txn[1].lock_time.0, 0);
2844                         if $htlc_offered {
2845                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2846                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2847                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2848                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2849                         } else {
2850                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2851                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2852                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2853                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2854                         }
2855                         node_txn.clear();
2856                 } }
2857         }
2858         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2859         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2860
2861         // Broadcast legit commitment tx from A on B's chain
2862         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2863         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2864         check_spends!(node_a_commitment_tx[0], chan_1.3);
2865         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2866         check_closed_broadcast!(nodes[1], true);
2867         check_added_monitors!(nodes[1], 1);
2868         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2869         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2870         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2871         let commitment_spend =
2872                 if node_txn.len() == 1 {
2873                         &node_txn[0]
2874                 } else {
2875                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2876                         // FullBlockViaListen
2877                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2878                                 check_spends!(node_txn[1], commitment_tx[0]);
2879                                 check_spends!(node_txn[2], commitment_tx[0]);
2880                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2881                                 &node_txn[0]
2882                         } else {
2883                                 check_spends!(node_txn[0], commitment_tx[0]);
2884                                 check_spends!(node_txn[1], commitment_tx[0]);
2885                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2886                                 &node_txn[2]
2887                         }
2888                 };
2889
2890         check_spends!(commitment_spend, node_a_commitment_tx[0]);
2891         assert_eq!(commitment_spend.input.len(), 2);
2892         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2893         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2894         assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2895         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2896         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2897         // we already checked the same situation with A.
2898
2899         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2900         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2901         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2902         check_closed_broadcast!(nodes[0], true);
2903         check_added_monitors!(nodes[0], 1);
2904         let events = nodes[0].node.get_and_clear_pending_events();
2905         assert_eq!(events.len(), 5);
2906         let mut first_claimed = false;
2907         for event in events {
2908                 match event {
2909                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2910                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2911                                         assert!(!first_claimed);
2912                                         first_claimed = true;
2913                                 } else {
2914                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2915                                         assert_eq!(payment_hash, payment_hash_2);
2916                                 }
2917                         },
2918                         Event::PaymentPathSuccessful { .. } => {},
2919                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2920                         _ => panic!("Unexpected event"),
2921                 }
2922         }
2923         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2924 }
2925
2926 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2927         // Test that in case of a unilateral close onchain, we detect the state of output and
2928         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2929         // broadcasting the right event to other nodes in payment path.
2930         // A ------------------> B ----------------------> C (timeout)
2931         //    B's commitment tx                 C's commitment tx
2932         //            \                                  \
2933         //         B's HTLC timeout tx               B's timeout tx
2934
2935         let chanmon_cfgs = create_chanmon_cfgs(3);
2936         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2937         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2938         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2939         *nodes[0].connect_style.borrow_mut() = connect_style;
2940         *nodes[1].connect_style.borrow_mut() = connect_style;
2941         *nodes[2].connect_style.borrow_mut() = connect_style;
2942
2943         // Create some intial channels
2944         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2945         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2946
2947         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2948         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2949         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2950
2951         let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2952
2953         // Broadcast legit commitment tx from C on B's chain
2954         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2955         check_spends!(commitment_tx[0], chan_2.3);
2956         nodes[2].node.fail_htlc_backwards(&payment_hash);
2957         check_added_monitors!(nodes[2], 0);
2958         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2959         check_added_monitors!(nodes[2], 1);
2960
2961         let events = nodes[2].node.get_and_clear_pending_msg_events();
2962         assert_eq!(events.len(), 1);
2963         match events[0] {
2964                 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, .. } } => {
2965                         assert!(update_add_htlcs.is_empty());
2966                         assert!(!update_fail_htlcs.is_empty());
2967                         assert!(update_fulfill_htlcs.is_empty());
2968                         assert!(update_fail_malformed_htlcs.is_empty());
2969                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2970                 },
2971                 _ => panic!("Unexpected event"),
2972         };
2973         mine_transaction(&nodes[2], &commitment_tx[0]);
2974         check_closed_broadcast!(nodes[2], true);
2975         check_added_monitors!(nodes[2], 1);
2976         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2977         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2978         assert_eq!(node_txn.len(), 0);
2979
2980         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2981         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2982         mine_transaction(&nodes[1], &commitment_tx[0]);
2983         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2984         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2985         let timeout_tx = {
2986                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2987                 if nodes[1].connect_style.borrow().skips_blocks() {
2988                         assert_eq!(txn.len(), 1);
2989                 } else {
2990                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2991                 }
2992                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2993                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2994                 txn.remove(0)
2995         };
2996
2997         mine_transaction(&nodes[1], &timeout_tx);
2998         check_added_monitors!(nodes[1], 1);
2999         check_closed_broadcast!(nodes[1], true);
3000
3001         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3002
3003         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 }]);
3004         check_added_monitors!(nodes[1], 1);
3005         let events = nodes[1].node.get_and_clear_pending_msg_events();
3006         assert_eq!(events.len(), 1);
3007         match events[0] {
3008                 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, .. } } => {
3009                         assert!(update_add_htlcs.is_empty());
3010                         assert!(!update_fail_htlcs.is_empty());
3011                         assert!(update_fulfill_htlcs.is_empty());
3012                         assert!(update_fail_malformed_htlcs.is_empty());
3013                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3014                 },
3015                 _ => panic!("Unexpected event"),
3016         };
3017
3018         // Broadcast legit commitment tx from B on A's chain
3019         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3020         check_spends!(commitment_tx[0], chan_1.3);
3021
3022         mine_transaction(&nodes[0], &commitment_tx[0]);
3023         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3024
3025         check_closed_broadcast!(nodes[0], true);
3026         check_added_monitors!(nodes[0], 1);
3027         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3028         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3029         assert_eq!(node_txn.len(), 1);
3030         check_spends!(node_txn[0], commitment_tx[0]);
3031         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3032 }
3033
3034 #[test]
3035 fn test_htlc_on_chain_timeout() {
3036         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3037         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3038         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3039 }
3040
3041 #[test]
3042 fn test_simple_commitment_revoked_fail_backward() {
3043         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3044         // and fail backward accordingly.
3045
3046         let chanmon_cfgs = create_chanmon_cfgs(3);
3047         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3048         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3049         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3050
3051         // Create some initial channels
3052         create_announced_chan_between_nodes(&nodes, 0, 1);
3053         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3054
3055         let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3056         // Get the will-be-revoked local txn from nodes[2]
3057         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3058         // Revoke the old state
3059         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3060
3061         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3062
3063         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3064         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3065         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3066         check_added_monitors!(nodes[1], 1);
3067         check_closed_broadcast!(nodes[1], true);
3068
3069         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 }]);
3070         check_added_monitors!(nodes[1], 1);
3071         let events = nodes[1].node.get_and_clear_pending_msg_events();
3072         assert_eq!(events.len(), 1);
3073         match events[0] {
3074                 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, .. } } => {
3075                         assert!(update_add_htlcs.is_empty());
3076                         assert_eq!(update_fail_htlcs.len(), 1);
3077                         assert!(update_fulfill_htlcs.is_empty());
3078                         assert!(update_fail_malformed_htlcs.is_empty());
3079                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3080
3081                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3082                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3083                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3084                 },
3085                 _ => panic!("Unexpected event"),
3086         }
3087 }
3088
3089 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3090         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3091         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3092         // commitment transaction anymore.
3093         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3094         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3095         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3096         // technically disallowed and we should probably handle it reasonably.
3097         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3098         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3099         // transactions:
3100         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3101         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3102         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3103         //   and once they revoke the previous commitment transaction (allowing us to send a new
3104         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3105         let chanmon_cfgs = create_chanmon_cfgs(3);
3106         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3107         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3108         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3109
3110         // Create some initial channels
3111         create_announced_chan_between_nodes(&nodes, 0, 1);
3112         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3113
3114         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 });
3115         // Get the will-be-revoked local txn from nodes[2]
3116         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3117         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3118         // Revoke the old state
3119         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3120
3121         let value = if use_dust {
3122                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3123                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3124                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3125                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3126         } else { 3000000 };
3127
3128         let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3129         let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130         let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3131
3132         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3133         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3134         check_added_monitors!(nodes[2], 1);
3135         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3136         assert!(updates.update_add_htlcs.is_empty());
3137         assert!(updates.update_fulfill_htlcs.is_empty());
3138         assert!(updates.update_fail_malformed_htlcs.is_empty());
3139         assert_eq!(updates.update_fail_htlcs.len(), 1);
3140         assert!(updates.update_fee.is_none());
3141         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3142         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3143         // Drop the last RAA from 3 -> 2
3144
3145         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3146         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3147         check_added_monitors!(nodes[2], 1);
3148         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3149         assert!(updates.update_add_htlcs.is_empty());
3150         assert!(updates.update_fulfill_htlcs.is_empty());
3151         assert!(updates.update_fail_malformed_htlcs.is_empty());
3152         assert_eq!(updates.update_fail_htlcs.len(), 1);
3153         assert!(updates.update_fee.is_none());
3154         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3155         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3156         check_added_monitors!(nodes[1], 1);
3157         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3158         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3159         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3160         check_added_monitors!(nodes[2], 1);
3161
3162         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3163         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3164         check_added_monitors!(nodes[2], 1);
3165         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3166         assert!(updates.update_add_htlcs.is_empty());
3167         assert!(updates.update_fulfill_htlcs.is_empty());
3168         assert!(updates.update_fail_malformed_htlcs.is_empty());
3169         assert_eq!(updates.update_fail_htlcs.len(), 1);
3170         assert!(updates.update_fee.is_none());
3171         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3172         // At this point first_payment_hash has dropped out of the latest two commitment
3173         // transactions that nodes[1] is tracking...
3174         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3175         check_added_monitors!(nodes[1], 1);
3176         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3177         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3178         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3179         check_added_monitors!(nodes[2], 1);
3180
3181         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3182         // on nodes[2]'s RAA.
3183         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3184         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3185                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3186         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3187         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3188         check_added_monitors!(nodes[1], 0);
3189
3190         if deliver_bs_raa {
3191                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3192                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3193                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3194                 check_added_monitors!(nodes[1], 1);
3195                 let events = nodes[1].node.get_and_clear_pending_events();
3196                 assert_eq!(events.len(), 2);
3197                 match events[0] {
3198                         Event::PendingHTLCsForwardable { .. } => { },
3199                         _ => panic!("Unexpected event"),
3200                 };
3201                 match events[1] {
3202                         Event::HTLCHandlingFailed { .. } => { },
3203                         _ => panic!("Unexpected event"),
3204                 }
3205                 // Deliberately don't process the pending fail-back so they all fail back at once after
3206                 // block connection just like the !deliver_bs_raa case
3207         }
3208
3209         let mut failed_htlcs = HashSet::new();
3210         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3211
3212         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3213         check_added_monitors!(nodes[1], 1);
3214         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3215
3216         let events = nodes[1].node.get_and_clear_pending_events();
3217         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3218         match events[0] {
3219                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3220                 _ => panic!("Unexepected event"),
3221         }
3222         match events[1] {
3223                 Event::PaymentPathFailed { ref payment_hash, .. } => {
3224                         assert_eq!(*payment_hash, fourth_payment_hash);
3225                 },
3226                 _ => panic!("Unexpected event"),
3227         }
3228         match events[2] {
3229                 Event::PaymentFailed { ref payment_hash, .. } => {
3230                         assert_eq!(*payment_hash, fourth_payment_hash);
3231                 },
3232                 _ => panic!("Unexpected event"),
3233         }
3234
3235         nodes[1].node.process_pending_htlc_forwards();
3236         check_added_monitors!(nodes[1], 1);
3237
3238         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3239         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3240
3241         if deliver_bs_raa {
3242                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3243                 match nodes_2_event {
3244                         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, .. } } => {
3245                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3246                                 assert_eq!(update_add_htlcs.len(), 1);
3247                                 assert!(update_fulfill_htlcs.is_empty());
3248                                 assert!(update_fail_htlcs.is_empty());
3249                                 assert!(update_fail_malformed_htlcs.is_empty());
3250                         },
3251                         _ => panic!("Unexpected event"),
3252                 }
3253         }
3254
3255         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3256         match nodes_2_event {
3257                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3258                         assert_eq!(channel_id, chan_2.2);
3259                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3260                 },
3261                 _ => panic!("Unexpected event"),
3262         }
3263
3264         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3265         match nodes_0_event {
3266                 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, .. } } => {
3267                         assert!(update_add_htlcs.is_empty());
3268                         assert_eq!(update_fail_htlcs.len(), 3);
3269                         assert!(update_fulfill_htlcs.is_empty());
3270                         assert!(update_fail_malformed_htlcs.is_empty());
3271                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3272
3273                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3274                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3275                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3276
3277                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3278
3279                         let events = nodes[0].node.get_and_clear_pending_events();
3280                         assert_eq!(events.len(), 6);
3281                         match events[0] {
3282                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3283                                         assert!(failed_htlcs.insert(payment_hash.0));
3284                                         // If we delivered B's RAA we got an unknown preimage error, not something
3285                                         // that we should update our routing table for.
3286                                         if !deliver_bs_raa {
3287                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3288                                         }
3289                                 },
3290                                 _ => panic!("Unexpected event"),
3291                         }
3292                         match events[1] {
3293                                 Event::PaymentFailed { ref payment_hash, .. } => {
3294                                         assert_eq!(*payment_hash, first_payment_hash);
3295                                 },
3296                                 _ => panic!("Unexpected event"),
3297                         }
3298                         match events[2] {
3299                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3300                                         assert!(failed_htlcs.insert(payment_hash.0));
3301                                 },
3302                                 _ => panic!("Unexpected event"),
3303                         }
3304                         match events[3] {
3305                                 Event::PaymentFailed { ref payment_hash, .. } => {
3306                                         assert_eq!(*payment_hash, second_payment_hash);
3307                                 },
3308                                 _ => panic!("Unexpected event"),
3309                         }
3310                         match events[4] {
3311                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3312                                         assert!(failed_htlcs.insert(payment_hash.0));
3313                                 },
3314                                 _ => panic!("Unexpected event"),
3315                         }
3316                         match events[5] {
3317                                 Event::PaymentFailed { ref payment_hash, .. } => {
3318                                         assert_eq!(*payment_hash, third_payment_hash);
3319                                 },
3320                                 _ => panic!("Unexpected event"),
3321                         }
3322                 },
3323                 _ => panic!("Unexpected event"),
3324         }
3325
3326         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3327         match events[0] {
3328                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3329                 _ => panic!("Unexpected event"),
3330         }
3331
3332         assert!(failed_htlcs.contains(&first_payment_hash.0));
3333         assert!(failed_htlcs.contains(&second_payment_hash.0));
3334         assert!(failed_htlcs.contains(&third_payment_hash.0));
3335 }
3336
3337 #[test]
3338 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3339         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3340         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3341         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3342         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3343 }
3344
3345 #[test]
3346 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3347         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3348         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3349         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3350         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3351 }
3352
3353 #[test]
3354 fn fail_backward_pending_htlc_upon_channel_failure() {
3355         let chanmon_cfgs = create_chanmon_cfgs(2);
3356         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3357         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3358         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3359         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3360
3361         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3362         {
3363                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3364                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3365                         PaymentId(payment_hash.0)).unwrap();
3366                 check_added_monitors!(nodes[0], 1);
3367
3368                 let payment_event = {
3369                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3370                         assert_eq!(events.len(), 1);
3371                         SendEvent::from_event(events.remove(0))
3372                 };
3373                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3374                 assert_eq!(payment_event.msgs.len(), 1);
3375         }
3376
3377         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3378         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3379         {
3380                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3381                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3382                 check_added_monitors!(nodes[0], 0);
3383
3384                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3385         }
3386
3387         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3388         {
3389                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3390
3391                 let secp_ctx = Secp256k1::new();
3392                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3393                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3394                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3395                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3396                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3397                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3398
3399                 // Send a 0-msat update_add_htlc to fail the channel.
3400                 let update_add_htlc = msgs::UpdateAddHTLC {
3401                         channel_id: chan.2,
3402                         htlc_id: 0,
3403                         amount_msat: 0,
3404                         payment_hash,
3405                         cltv_expiry,
3406                         onion_routing_packet,
3407                 };
3408                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3409         }
3410         let events = nodes[0].node.get_and_clear_pending_events();
3411         assert_eq!(events.len(), 3);
3412         // Check that Alice fails backward the pending HTLC from the second payment.
3413         match events[0] {
3414                 Event::PaymentPathFailed { payment_hash, .. } => {
3415                         assert_eq!(payment_hash, failed_payment_hash);
3416                 },
3417                 _ => panic!("Unexpected event"),
3418         }
3419         match events[1] {
3420                 Event::PaymentFailed { payment_hash, .. } => {
3421                         assert_eq!(payment_hash, failed_payment_hash);
3422                 },
3423                 _ => panic!("Unexpected event"),
3424         }
3425         match events[2] {
3426                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3427                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3428                 },
3429                 _ => panic!("Unexpected event {:?}", events[1]),
3430         }
3431         check_closed_broadcast!(nodes[0], true);
3432         check_added_monitors!(nodes[0], 1);
3433 }
3434
3435 #[test]
3436 fn test_htlc_ignore_latest_remote_commitment() {
3437         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3438         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3439         let chanmon_cfgs = create_chanmon_cfgs(2);
3440         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3441         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3442         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3443         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3444                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3445                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3446                 // connect_style.
3447                 return;
3448         }
3449         create_announced_chan_between_nodes(&nodes, 0, 1);
3450
3451         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3452         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3453         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3454         check_closed_broadcast!(nodes[0], true);
3455         check_added_monitors!(nodes[0], 1);
3456         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3457
3458         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3459         assert_eq!(node_txn.len(), 3);
3460         assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3461
3462         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3463         connect_block(&nodes[1], &block);
3464         check_closed_broadcast!(nodes[1], true);
3465         check_added_monitors!(nodes[1], 1);
3466         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3467
3468         // Duplicate the connect_block call since this may happen due to other listeners
3469         // registering new transactions
3470         connect_block(&nodes[1], &block);
3471 }
3472
3473 #[test]
3474 fn test_force_close_fail_back() {
3475         // Check which HTLCs are failed-backwards on channel force-closure
3476         let chanmon_cfgs = create_chanmon_cfgs(3);
3477         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3478         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3479         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3480         create_announced_chan_between_nodes(&nodes, 0, 1);
3481         create_announced_chan_between_nodes(&nodes, 1, 2);
3482
3483         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3484
3485         let mut payment_event = {
3486                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3487                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3488                 check_added_monitors!(nodes[0], 1);
3489
3490                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3491                 assert_eq!(events.len(), 1);
3492                 SendEvent::from_event(events.remove(0))
3493         };
3494
3495         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3496         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3497
3498         expect_pending_htlcs_forwardable!(nodes[1]);
3499
3500         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3501         assert_eq!(events_2.len(), 1);
3502         payment_event = SendEvent::from_event(events_2.remove(0));
3503         assert_eq!(payment_event.msgs.len(), 1);
3504
3505         check_added_monitors!(nodes[1], 1);
3506         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3507         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3508         check_added_monitors!(nodes[2], 1);
3509         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3510
3511         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3512         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3513         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3514
3515         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3516         check_closed_broadcast!(nodes[2], true);
3517         check_added_monitors!(nodes[2], 1);
3518         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3519         let tx = {
3520                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3521                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3522                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3523                 // back to nodes[1] upon timeout otherwise.
3524                 assert_eq!(node_txn.len(), 1);
3525                 node_txn.remove(0)
3526         };
3527
3528         mine_transaction(&nodes[1], &tx);
3529
3530         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3531         check_closed_broadcast!(nodes[1], true);
3532         check_added_monitors!(nodes[1], 1);
3533         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3534
3535         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3536         {
3537                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3538                         .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);
3539         }
3540         mine_transaction(&nodes[2], &tx);
3541         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3542         assert_eq!(node_txn.len(), 1);
3543         assert_eq!(node_txn[0].input.len(), 1);
3544         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3545         assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3546         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3547
3548         check_spends!(node_txn[0], tx);
3549 }
3550
3551 #[test]
3552 fn test_dup_events_on_peer_disconnect() {
3553         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3554         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3555         // as we used to generate the event immediately upon receipt of the payment preimage in the
3556         // update_fulfill_htlc message.
3557
3558         let chanmon_cfgs = create_chanmon_cfgs(2);
3559         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3560         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3561         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3562         create_announced_chan_between_nodes(&nodes, 0, 1);
3563
3564         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3565
3566         nodes[1].node.claim_funds(payment_preimage);
3567         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3568         check_added_monitors!(nodes[1], 1);
3569         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3570         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3571         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3572
3573         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3574         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3575
3576         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3577         expect_payment_path_successful!(nodes[0]);
3578 }
3579
3580 #[test]
3581 fn test_peer_disconnected_before_funding_broadcasted() {
3582         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3583         // before the funding transaction has been broadcasted.
3584         let chanmon_cfgs = create_chanmon_cfgs(2);
3585         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3586         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3587         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3588
3589         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3590         // broadcasted, even though it's created by `nodes[0]`.
3591         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();
3592         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3593         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3594         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3595         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3596
3597         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3598         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3599
3600         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3601
3602         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3603         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3604
3605         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3606         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3607         // broadcasted.
3608         {
3609                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3610         }
3611
3612         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3613         // disconnected before the funding transaction was broadcasted.
3614         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3615         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3616
3617         check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3618         check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3619 }
3620
3621 #[test]
3622 fn test_simple_peer_disconnect() {
3623         // Test that we can reconnect when there are no lost messages
3624         let chanmon_cfgs = create_chanmon_cfgs(3);
3625         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3626         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3627         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3628         create_announced_chan_between_nodes(&nodes, 0, 1);
3629         create_announced_chan_between_nodes(&nodes, 1, 2);
3630
3631         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3632         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3633         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634
3635         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3636         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3637         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3638         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3639
3640         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3641         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3642         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3643
3644         let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3645         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3646         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3648
3649         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3650         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3651
3652         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3653         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3654
3655         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3656         {
3657                 let events = nodes[0].node.get_and_clear_pending_events();
3658                 assert_eq!(events.len(), 4);
3659                 match events[0] {
3660                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3661                                 assert_eq!(payment_preimage, payment_preimage_3);
3662                                 assert_eq!(payment_hash, payment_hash_3);
3663                         },
3664                         _ => panic!("Unexpected event"),
3665                 }
3666                 match events[1] {
3667                         Event::PaymentPathSuccessful { .. } => {},
3668                         _ => panic!("Unexpected event"),
3669                 }
3670                 match events[2] {
3671                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3672                                 assert_eq!(payment_hash, payment_hash_5);
3673                                 assert!(payment_failed_permanently);
3674                         },
3675                         _ => panic!("Unexpected event"),
3676                 }
3677                 match events[3] {
3678                         Event::PaymentFailed { payment_hash, .. } => {
3679                                 assert_eq!(payment_hash, payment_hash_5);
3680                         },
3681                         _ => panic!("Unexpected event"),
3682                 }
3683         }
3684
3685         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3686         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3687 }
3688
3689 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3690         // Test that we can reconnect when in-flight HTLC updates get dropped
3691         let chanmon_cfgs = create_chanmon_cfgs(2);
3692         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3693         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3694         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3695
3696         let mut as_channel_ready = None;
3697         let channel_id = if messages_delivered == 0 {
3698                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3699                 as_channel_ready = Some(channel_ready);
3700                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3701                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3702                 // it before the channel_reestablish message.
3703                 chan_id
3704         } else {
3705                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3706         };
3707
3708         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3709
3710         let payment_event = {
3711                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3712                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3713                 check_added_monitors!(nodes[0], 1);
3714
3715                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3716                 assert_eq!(events.len(), 1);
3717                 SendEvent::from_event(events.remove(0))
3718         };
3719         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3720
3721         if messages_delivered < 2 {
3722                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3723         } else {
3724                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3725                 if messages_delivered >= 3 {
3726                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3727                         check_added_monitors!(nodes[1], 1);
3728                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3729
3730                         if messages_delivered >= 4 {
3731                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3732                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3733                                 check_added_monitors!(nodes[0], 1);
3734
3735                                 if messages_delivered >= 5 {
3736                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3737                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3738                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3739                                         check_added_monitors!(nodes[0], 1);
3740
3741                                         if messages_delivered >= 6 {
3742                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3743                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3744                                                 check_added_monitors!(nodes[1], 1);
3745                                         }
3746                                 }
3747                         }
3748                 }
3749         }
3750
3751         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3752         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3753         if messages_delivered < 3 {
3754                 if simulate_broken_lnd {
3755                         // lnd has a long-standing bug where they send a channel_ready prior to a
3756                         // channel_reestablish if you reconnect prior to channel_ready time.
3757                         //
3758                         // Here we simulate that behavior, delivering a channel_ready immediately on
3759                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3760                         // in `reconnect_nodes` but we currently don't fail based on that.
3761                         //
3762                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3763                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3764                 }
3765                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3766                 // received on either side, both sides will need to resend them.
3767                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3768         } else if messages_delivered == 3 {
3769                 // nodes[0] still wants its RAA + commitment_signed
3770                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3771         } else if messages_delivered == 4 {
3772                 // nodes[0] still wants its commitment_signed
3773                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3774         } else if messages_delivered == 5 {
3775                 // nodes[1] still wants its final RAA
3776                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3777         } else if messages_delivered == 6 {
3778                 // Everything was delivered...
3779                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3780         }
3781
3782         let events_1 = nodes[1].node.get_and_clear_pending_events();
3783         if messages_delivered == 0 {
3784                 assert_eq!(events_1.len(), 2);
3785                 match events_1[0] {
3786                         Event::ChannelReady { .. } => { },
3787                         _ => panic!("Unexpected event"),
3788                 };
3789                 match events_1[1] {
3790                         Event::PendingHTLCsForwardable { .. } => { },
3791                         _ => panic!("Unexpected event"),
3792                 };
3793         } else {
3794                 assert_eq!(events_1.len(), 1);
3795                 match events_1[0] {
3796                         Event::PendingHTLCsForwardable { .. } => { },
3797                         _ => panic!("Unexpected event"),
3798                 };
3799         }
3800
3801         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3802         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3803         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3804
3805         nodes[1].node.process_pending_htlc_forwards();
3806
3807         let events_2 = nodes[1].node.get_and_clear_pending_events();
3808         assert_eq!(events_2.len(), 1);
3809         match events_2[0] {
3810                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3811                         assert_eq!(payment_hash_1, *payment_hash);
3812                         assert_eq!(amount_msat, 1_000_000);
3813                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3814                         assert_eq!(via_channel_id, Some(channel_id));
3815                         match &purpose {
3816                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3817                                         assert!(payment_preimage.is_none());
3818                                         assert_eq!(payment_secret_1, *payment_secret);
3819                                 },
3820                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3821                         }
3822                 },
3823                 _ => panic!("Unexpected event"),
3824         }
3825
3826         nodes[1].node.claim_funds(payment_preimage_1);
3827         check_added_monitors!(nodes[1], 1);
3828         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3829
3830         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3831         assert_eq!(events_3.len(), 1);
3832         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3833                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3834                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3835                         assert!(updates.update_add_htlcs.is_empty());
3836                         assert!(updates.update_fail_htlcs.is_empty());
3837                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3838                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3839                         assert!(updates.update_fee.is_none());
3840                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3841                 },
3842                 _ => panic!("Unexpected event"),
3843         };
3844
3845         if messages_delivered >= 1 {
3846                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3847
3848                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3849                 assert_eq!(events_4.len(), 1);
3850                 match events_4[0] {
3851                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3852                                 assert_eq!(payment_preimage_1, *payment_preimage);
3853                                 assert_eq!(payment_hash_1, *payment_hash);
3854                         },
3855                         _ => panic!("Unexpected event"),
3856                 }
3857
3858                 if messages_delivered >= 2 {
3859                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3860                         check_added_monitors!(nodes[0], 1);
3861                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3862
3863                         if messages_delivered >= 3 {
3864                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3865                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3866                                 check_added_monitors!(nodes[1], 1);
3867
3868                                 if messages_delivered >= 4 {
3869                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3870                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3871                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3872                                         check_added_monitors!(nodes[1], 1);
3873
3874                                         if messages_delivered >= 5 {
3875                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3876                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3877                                                 check_added_monitors!(nodes[0], 1);
3878                                         }
3879                                 }
3880                         }
3881                 }
3882         }
3883
3884         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3885         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3886         if messages_delivered < 2 {
3887                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3888                 if messages_delivered < 1 {
3889                         expect_payment_sent!(nodes[0], payment_preimage_1);
3890                 } else {
3891                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3892                 }
3893         } else if messages_delivered == 2 {
3894                 // nodes[0] still wants its RAA + commitment_signed
3895                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3896         } else if messages_delivered == 3 {
3897                 // nodes[0] still wants its commitment_signed
3898                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3899         } else if messages_delivered == 4 {
3900                 // nodes[1] still wants its final RAA
3901                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3902         } else if messages_delivered == 5 {
3903                 // Everything was delivered...
3904                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3905         }
3906
3907         if messages_delivered == 1 || messages_delivered == 2 {
3908                 expect_payment_path_successful!(nodes[0]);
3909         }
3910         if messages_delivered <= 5 {
3911                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3912                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3913         }
3914         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3915
3916         if messages_delivered > 2 {
3917                 expect_payment_path_successful!(nodes[0]);
3918         }
3919
3920         // Channel should still work fine...
3921         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3922         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3923         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3924 }
3925
3926 #[test]
3927 fn test_drop_messages_peer_disconnect_a() {
3928         do_test_drop_messages_peer_disconnect(0, true);
3929         do_test_drop_messages_peer_disconnect(0, false);
3930         do_test_drop_messages_peer_disconnect(1, false);
3931         do_test_drop_messages_peer_disconnect(2, false);
3932 }
3933
3934 #[test]
3935 fn test_drop_messages_peer_disconnect_b() {
3936         do_test_drop_messages_peer_disconnect(3, false);
3937         do_test_drop_messages_peer_disconnect(4, false);
3938         do_test_drop_messages_peer_disconnect(5, false);
3939         do_test_drop_messages_peer_disconnect(6, false);
3940 }
3941
3942 #[test]
3943 fn test_channel_ready_without_best_block_updated() {
3944         // Previously, if we were offline when a funding transaction was locked in, and then we came
3945         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3946         // generate a channel_ready until a later best_block_updated. This tests that we generate the
3947         // channel_ready immediately instead.
3948         let chanmon_cfgs = create_chanmon_cfgs(2);
3949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3951         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3952         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3953
3954         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3955
3956         let conf_height = nodes[0].best_block_info().1 + 1;
3957         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3958         let block_txn = [funding_tx];
3959         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3960         let conf_block_header = nodes[0].get_block_header(conf_height);
3961         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3962
3963         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3964         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3965         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3966 }
3967
3968 #[test]
3969 fn test_drop_messages_peer_disconnect_dual_htlc() {
3970         // Test that we can handle reconnecting when both sides of a channel have pending
3971         // commitment_updates when we disconnect.
3972         let chanmon_cfgs = create_chanmon_cfgs(2);
3973         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3974         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3975         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3976         create_announced_chan_between_nodes(&nodes, 0, 1);
3977
3978         let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3979
3980         // Now try to send a second payment which will fail to send
3981         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3982         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3983                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3984         check_added_monitors!(nodes[0], 1);
3985
3986         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3987         assert_eq!(events_1.len(), 1);
3988         match events_1[0] {
3989                 MessageSendEvent::UpdateHTLCs { .. } => {},
3990                 _ => panic!("Unexpected event"),
3991         }
3992
3993         nodes[1].node.claim_funds(payment_preimage_1);
3994         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3995         check_added_monitors!(nodes[1], 1);
3996
3997         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3998         assert_eq!(events_2.len(), 1);
3999         match events_2[0] {
4000                 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 } } => {
4001                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4002                         assert!(update_add_htlcs.is_empty());
4003                         assert_eq!(update_fulfill_htlcs.len(), 1);
4004                         assert!(update_fail_htlcs.is_empty());
4005                         assert!(update_fail_malformed_htlcs.is_empty());
4006                         assert!(update_fee.is_none());
4007
4008                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4009                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4010                         assert_eq!(events_3.len(), 1);
4011                         match events_3[0] {
4012                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4013                                         assert_eq!(*payment_preimage, payment_preimage_1);
4014                                         assert_eq!(*payment_hash, payment_hash_1);
4015                                 },
4016                                 _ => panic!("Unexpected event"),
4017                         }
4018
4019                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4020                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4021                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4022                         check_added_monitors!(nodes[0], 1);
4023                 },
4024                 _ => panic!("Unexpected event"),
4025         }
4026
4027         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4028         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4029
4030         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
4031         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4032         assert_eq!(reestablish_1.len(), 1);
4033         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
4034         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4035         assert_eq!(reestablish_2.len(), 1);
4036
4037         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4038         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4039         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4040         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4041
4042         assert!(as_resp.0.is_none());
4043         assert!(bs_resp.0.is_none());
4044
4045         assert!(bs_resp.1.is_none());
4046         assert!(bs_resp.2.is_none());
4047
4048         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4049
4050         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4051         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4052         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4053         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4054         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4055         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4056         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4057         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4058         // No commitment_signed so get_event_msg's assert(len == 1) passes
4059         check_added_monitors!(nodes[1], 1);
4060
4061         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4062         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4063         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4064         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4065         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4066         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4067         assert!(bs_second_commitment_signed.update_fee.is_none());
4068         check_added_monitors!(nodes[1], 1);
4069
4070         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4071         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4072         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4073         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4074         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4075         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4076         assert!(as_commitment_signed.update_fee.is_none());
4077         check_added_monitors!(nodes[0], 1);
4078
4079         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4080         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4081         // No commitment_signed so get_event_msg's assert(len == 1) passes
4082         check_added_monitors!(nodes[0], 1);
4083
4084         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4085         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4086         // No commitment_signed so get_event_msg's assert(len == 1) passes
4087         check_added_monitors!(nodes[1], 1);
4088
4089         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4090         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4091         check_added_monitors!(nodes[1], 1);
4092
4093         expect_pending_htlcs_forwardable!(nodes[1]);
4094
4095         let events_5 = nodes[1].node.get_and_clear_pending_events();
4096         assert_eq!(events_5.len(), 1);
4097         match events_5[0] {
4098                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4099                         assert_eq!(payment_hash_2, *payment_hash);
4100                         match &purpose {
4101                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4102                                         assert!(payment_preimage.is_none());
4103                                         assert_eq!(payment_secret_2, *payment_secret);
4104                                 },
4105                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4106                         }
4107                 },
4108                 _ => panic!("Unexpected event"),
4109         }
4110
4111         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4112         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4113         check_added_monitors!(nodes[0], 1);
4114
4115         expect_payment_path_successful!(nodes[0]);
4116         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4117 }
4118
4119 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4120         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4121         // to avoid our counterparty failing the channel.
4122         let chanmon_cfgs = create_chanmon_cfgs(2);
4123         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4124         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4125         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4126
4127         create_announced_chan_between_nodes(&nodes, 0, 1);
4128
4129         let our_payment_hash = if send_partial_mpp {
4130                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4131                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4132                 // indicates there are more HTLCs coming.
4133                 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.
4134                 let payment_id = PaymentId([42; 32]);
4135                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4136                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4137                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4138                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4139                         &None, session_privs[0]).unwrap();
4140                 check_added_monitors!(nodes[0], 1);
4141                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4142                 assert_eq!(events.len(), 1);
4143                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4144                 // hop should *not* yet generate any PaymentClaimable event(s).
4145                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4146                 our_payment_hash
4147         } else {
4148                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4149         };
4150
4151         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4152         connect_block(&nodes[0], &block);
4153         connect_block(&nodes[1], &block);
4154         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4155         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4156                 block.header.prev_blockhash = block.block_hash();
4157                 connect_block(&nodes[0], &block);
4158                 connect_block(&nodes[1], &block);
4159         }
4160
4161         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4162
4163         check_added_monitors!(nodes[1], 1);
4164         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4165         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4166         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4167         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4168         assert!(htlc_timeout_updates.update_fee.is_none());
4169
4170         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4171         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4172         // 100_000 msat as u64, followed by the height at which we failed back above
4173         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4174         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4175         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4176 }
4177
4178 #[test]
4179 fn test_htlc_timeout() {
4180         do_test_htlc_timeout(true);
4181         do_test_htlc_timeout(false);
4182 }
4183
4184 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4185         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4186         let chanmon_cfgs = create_chanmon_cfgs(3);
4187         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4188         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4189         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4190         create_announced_chan_between_nodes(&nodes, 0, 1);
4191         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4192
4193         // Make sure all nodes are at the same starting height
4194         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4195         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4196         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4197
4198         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4199         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4200         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4201                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4202         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4203         check_added_monitors!(nodes[1], 1);
4204
4205         // Now attempt to route a second payment, which should be placed in the holding cell
4206         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4207         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4208         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4209                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4210         if forwarded_htlc {
4211                 check_added_monitors!(nodes[0], 1);
4212                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4213                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4214                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4215                 expect_pending_htlcs_forwardable!(nodes[1]);
4216         }
4217         check_added_monitors!(nodes[1], 0);
4218
4219         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4220         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4221         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4222         connect_blocks(&nodes[1], 1);
4223
4224         if forwarded_htlc {
4225                 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 }]);
4226                 check_added_monitors!(nodes[1], 1);
4227                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4228                 assert_eq!(fail_commit.len(), 1);
4229                 match fail_commit[0] {
4230                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4231                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4232                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4233                         },
4234                         _ => unreachable!(),
4235                 }
4236                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4237         } else {
4238                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4239         }
4240 }
4241
4242 #[test]
4243 fn test_holding_cell_htlc_add_timeouts() {
4244         do_test_holding_cell_htlc_add_timeouts(false);
4245         do_test_holding_cell_htlc_add_timeouts(true);
4246 }
4247
4248 macro_rules! check_spendable_outputs {
4249         ($node: expr, $keysinterface: expr) => {
4250                 {
4251                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4252                         let mut txn = Vec::new();
4253                         let mut all_outputs = Vec::new();
4254                         let secp_ctx = Secp256k1::new();
4255                         for event in events.drain(..) {
4256                                 match event {
4257                                         Event::SpendableOutputs { mut outputs } => {
4258                                                 for outp in outputs.drain(..) {
4259                                                         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());
4260                                                         all_outputs.push(outp);
4261                                                 }
4262                                         },
4263                                         _ => panic!("Unexpected event"),
4264                                 };
4265                         }
4266                         if all_outputs.len() > 1 {
4267                                 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) {
4268                                         txn.push(tx);
4269                                 }
4270                         }
4271                         txn
4272                 }
4273         }
4274 }
4275
4276 #[test]
4277 fn test_claim_sizeable_push_msat() {
4278         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4279         let chanmon_cfgs = create_chanmon_cfgs(2);
4280         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4281         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4282         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4283
4284         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4285         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4286         check_closed_broadcast!(nodes[1], true);
4287         check_added_monitors!(nodes[1], 1);
4288         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4289         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4290         assert_eq!(node_txn.len(), 1);
4291         check_spends!(node_txn[0], chan.3);
4292         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
4293
4294         mine_transaction(&nodes[1], &node_txn[0]);
4295         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4296
4297         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4298         assert_eq!(spend_txn.len(), 1);
4299         assert_eq!(spend_txn[0].input.len(), 1);
4300         check_spends!(spend_txn[0], node_txn[0]);
4301         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4302 }
4303
4304 #[test]
4305 fn test_claim_on_remote_sizeable_push_msat() {
4306         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4307         // to_remote output is encumbered by a P2WPKH
4308         let chanmon_cfgs = create_chanmon_cfgs(2);
4309         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4310         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4311         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4312
4313         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4314         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4315         check_closed_broadcast!(nodes[0], true);
4316         check_added_monitors!(nodes[0], 1);
4317         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4318
4319         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4320         assert_eq!(node_txn.len(), 1);
4321         check_spends!(node_txn[0], chan.3);
4322         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
4323
4324         mine_transaction(&nodes[1], &node_txn[0]);
4325         check_closed_broadcast!(nodes[1], true);
4326         check_added_monitors!(nodes[1], 1);
4327         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4328         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4329
4330         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4331         assert_eq!(spend_txn.len(), 1);
4332         check_spends!(spend_txn[0], node_txn[0]);
4333 }
4334
4335 #[test]
4336 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4337         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4338         // to_remote output is encumbered by a P2WPKH
4339
4340         let chanmon_cfgs = create_chanmon_cfgs(2);
4341         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4342         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4343         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4344
4345         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4346         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4347         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4348         assert_eq!(revoked_local_txn[0].input.len(), 1);
4349         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4350
4351         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4352         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4353         check_closed_broadcast!(nodes[1], true);
4354         check_added_monitors!(nodes[1], 1);
4355         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4356
4357         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4358         mine_transaction(&nodes[1], &node_txn[0]);
4359         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4360
4361         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4362         assert_eq!(spend_txn.len(), 3);
4363         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4364         check_spends!(spend_txn[1], node_txn[0]);
4365         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4366 }
4367
4368 #[test]
4369 fn test_static_spendable_outputs_preimage_tx() {
4370         let chanmon_cfgs = create_chanmon_cfgs(2);
4371         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4372         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4373         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4374
4375         // Create some initial channels
4376         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4377
4378         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4379
4380         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4381         assert_eq!(commitment_tx[0].input.len(), 1);
4382         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4383
4384         // Settle A's commitment tx on B's chain
4385         nodes[1].node.claim_funds(payment_preimage);
4386         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4387         check_added_monitors!(nodes[1], 1);
4388         mine_transaction(&nodes[1], &commitment_tx[0]);
4389         check_added_monitors!(nodes[1], 1);
4390         let events = nodes[1].node.get_and_clear_pending_msg_events();
4391         match events[0] {
4392                 MessageSendEvent::UpdateHTLCs { .. } => {},
4393                 _ => panic!("Unexpected event"),
4394         }
4395         match events[1] {
4396                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4397                 _ => panic!("Unexepected event"),
4398         }
4399
4400         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4401         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4402         assert_eq!(node_txn.len(), 1);
4403         check_spends!(node_txn[0], commitment_tx[0]);
4404         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4405
4406         mine_transaction(&nodes[1], &node_txn[0]);
4407         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4408         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4409
4410         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4411         assert_eq!(spend_txn.len(), 1);
4412         check_spends!(spend_txn[0], node_txn[0]);
4413 }
4414
4415 #[test]
4416 fn test_static_spendable_outputs_timeout_tx() {
4417         let chanmon_cfgs = create_chanmon_cfgs(2);
4418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4420         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4421
4422         // Create some initial channels
4423         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4424
4425         // Rebalance the network a bit by relaying one payment through all the channels ...
4426         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4427
4428         let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4429
4430         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4431         assert_eq!(commitment_tx[0].input.len(), 1);
4432         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4433
4434         // Settle A's commitment tx on B' chain
4435         mine_transaction(&nodes[1], &commitment_tx[0]);
4436         check_added_monitors!(nodes[1], 1);
4437         let events = nodes[1].node.get_and_clear_pending_msg_events();
4438         match events[0] {
4439                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4440                 _ => panic!("Unexpected event"),
4441         }
4442         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4443
4444         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4445         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4446         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4447         check_spends!(node_txn[0],  commitment_tx[0].clone());
4448         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4449
4450         mine_transaction(&nodes[1], &node_txn[0]);
4451         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4452         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4453         expect_payment_failed!(nodes[1], our_payment_hash, false);
4454
4455         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4456         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4457         check_spends!(spend_txn[0], commitment_tx[0]);
4458         check_spends!(spend_txn[1], node_txn[0]);
4459         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4460 }
4461
4462 #[test]
4463 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4464         let chanmon_cfgs = create_chanmon_cfgs(2);
4465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4467         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4468
4469         // Create some initial channels
4470         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4471
4472         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4473         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4474         assert_eq!(revoked_local_txn[0].input.len(), 1);
4475         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4476
4477         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4478
4479         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4480         check_closed_broadcast!(nodes[1], true);
4481         check_added_monitors!(nodes[1], 1);
4482         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4483
4484         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4485         assert_eq!(node_txn.len(), 1);
4486         assert_eq!(node_txn[0].input.len(), 2);
4487         check_spends!(node_txn[0], revoked_local_txn[0]);
4488
4489         mine_transaction(&nodes[1], &node_txn[0]);
4490         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4491
4492         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4493         assert_eq!(spend_txn.len(), 1);
4494         check_spends!(spend_txn[0], node_txn[0]);
4495 }
4496
4497 #[test]
4498 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4499         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4500         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4504
4505         // Create some initial channels
4506         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4507
4508         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4509         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4510         assert_eq!(revoked_local_txn[0].input.len(), 1);
4511         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4512
4513         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4514
4515         // A will generate HTLC-Timeout from revoked commitment tx
4516         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4517         check_closed_broadcast!(nodes[0], true);
4518         check_added_monitors!(nodes[0], 1);
4519         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4520         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4521
4522         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4523         assert_eq!(revoked_htlc_txn.len(), 1);
4524         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4525         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4526         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4527         assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4528
4529         // B will generate justice tx from A's revoked commitment/HTLC tx
4530         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4531         check_closed_broadcast!(nodes[1], true);
4532         check_added_monitors!(nodes[1], 1);
4533         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4534
4535         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4536         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4537         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4538         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4539         // transactions next...
4540         assert_eq!(node_txn[0].input.len(), 3);
4541         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4542
4543         assert_eq!(node_txn[1].input.len(), 2);
4544         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4545         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4546                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4547         } else {
4548                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4549                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4550         }
4551
4552         mine_transaction(&nodes[1], &node_txn[1]);
4553         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4554
4555         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4556         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4557         assert_eq!(spend_txn.len(), 1);
4558         assert_eq!(spend_txn[0].input.len(), 1);
4559         check_spends!(spend_txn[0], node_txn[1]);
4560 }
4561
4562 #[test]
4563 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4564         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4565         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4566         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4567         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4568         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4569
4570         // Create some initial channels
4571         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4572
4573         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4574         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4575         assert_eq!(revoked_local_txn[0].input.len(), 1);
4576         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4577
4578         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4579         assert_eq!(revoked_local_txn[0].output.len(), 2);
4580
4581         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4582
4583         // B will generate HTLC-Success from revoked commitment tx
4584         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4585         check_closed_broadcast!(nodes[1], true);
4586         check_added_monitors!(nodes[1], 1);
4587         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4588         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4589
4590         assert_eq!(revoked_htlc_txn.len(), 1);
4591         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4592         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4593         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4594
4595         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4596         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4597         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4598
4599         // A will generate justice tx from B's revoked commitment/HTLC tx
4600         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4601         check_closed_broadcast!(nodes[0], true);
4602         check_added_monitors!(nodes[0], 1);
4603         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4604
4605         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4606         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4607
4608         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4609         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4610         // transactions next...
4611         assert_eq!(node_txn[0].input.len(), 2);
4612         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4613         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4614                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4615         } else {
4616                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4617                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4618         }
4619
4620         assert_eq!(node_txn[1].input.len(), 1);
4621         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4622
4623         mine_transaction(&nodes[0], &node_txn[1]);
4624         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4625
4626         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4627         // didn't try to generate any new transactions.
4628
4629         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4630         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4631         assert_eq!(spend_txn.len(), 3);
4632         assert_eq!(spend_txn[0].input.len(), 1);
4633         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4634         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4635         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4636         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4637 }
4638
4639 #[test]
4640 fn test_onchain_to_onchain_claim() {
4641         // Test that in case of channel closure, we detect the state of output and claim HTLC
4642         // on downstream peer's remote commitment tx.
4643         // First, have C claim an HTLC against its own latest commitment transaction.
4644         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4645         // channel.
4646         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4647         // gets broadcast.
4648
4649         let chanmon_cfgs = create_chanmon_cfgs(3);
4650         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4651         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4652         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4653
4654         // Create some initial channels
4655         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4656         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4657
4658         // Ensure all nodes are at the same height
4659         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4660         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4661         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4662         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4663
4664         // Rebalance the network a bit by relaying one payment through all the channels ...
4665         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4666         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4667
4668         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4669         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4670         check_spends!(commitment_tx[0], chan_2.3);
4671         nodes[2].node.claim_funds(payment_preimage);
4672         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4673         check_added_monitors!(nodes[2], 1);
4674         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4675         assert!(updates.update_add_htlcs.is_empty());
4676         assert!(updates.update_fail_htlcs.is_empty());
4677         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4678         assert!(updates.update_fail_malformed_htlcs.is_empty());
4679
4680         mine_transaction(&nodes[2], &commitment_tx[0]);
4681         check_closed_broadcast!(nodes[2], true);
4682         check_added_monitors!(nodes[2], 1);
4683         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4684
4685         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4686         assert_eq!(c_txn.len(), 1);
4687         check_spends!(c_txn[0], commitment_tx[0]);
4688         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4689         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4690         assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4691
4692         // 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
4693         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4694         check_added_monitors!(nodes[1], 1);
4695         let events = nodes[1].node.get_and_clear_pending_events();
4696         assert_eq!(events.len(), 2);
4697         match events[0] {
4698                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4699                 _ => panic!("Unexpected event"),
4700         }
4701         match events[1] {
4702                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4703                         assert_eq!(fee_earned_msat, Some(1000));
4704                         assert_eq!(prev_channel_id, Some(chan_1.2));
4705                         assert_eq!(claim_from_onchain_tx, true);
4706                         assert_eq!(next_channel_id, Some(chan_2.2));
4707                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4708                 },
4709                 _ => panic!("Unexpected event"),
4710         }
4711         check_added_monitors!(nodes[1], 1);
4712         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4713         assert_eq!(msg_events.len(), 3);
4714         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4715         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4716
4717         match nodes_2_event {
4718                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4719                 _ => panic!("Unexpected event"),
4720         }
4721
4722         match nodes_0_event {
4723                 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, .. } } => {
4724                         assert!(update_add_htlcs.is_empty());
4725                         assert!(update_fail_htlcs.is_empty());
4726                         assert_eq!(update_fulfill_htlcs.len(), 1);
4727                         assert!(update_fail_malformed_htlcs.is_empty());
4728                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4729                 },
4730                 _ => panic!("Unexpected event"),
4731         };
4732
4733         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4734         match msg_events[0] {
4735                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4736                 _ => panic!("Unexpected event"),
4737         }
4738
4739         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4740         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4741         mine_transaction(&nodes[1], &commitment_tx[0]);
4742         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4743         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4744         // ChannelMonitor: HTLC-Success tx
4745         assert_eq!(b_txn.len(), 1);
4746         check_spends!(b_txn[0], commitment_tx[0]);
4747         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4748         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4749         assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4750
4751         check_closed_broadcast!(nodes[1], true);
4752         check_added_monitors!(nodes[1], 1);
4753 }
4754
4755 #[test]
4756 fn test_duplicate_payment_hash_one_failure_one_success() {
4757         // Topology : A --> B --> C --> D
4758         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4759         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4760         // we forward one of the payments onwards to D.
4761         let chanmon_cfgs = create_chanmon_cfgs(4);
4762         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4763         // When this test was written, the default base fee floated based on the HTLC count.
4764         // It is now fixed, so we simply set the fee to the expected value here.
4765         let mut config = test_default_channel_config();
4766         config.channel_config.forwarding_fee_base_msat = 196;
4767         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4768                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4769         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4770
4771         create_announced_chan_between_nodes(&nodes, 0, 1);
4772         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4773         create_announced_chan_between_nodes(&nodes, 2, 3);
4774
4775         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4776         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4777         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4778         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4779         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4780
4781         let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4782
4783         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4784         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4785         // script push size limit so that the below script length checks match
4786         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4787         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4788                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4789         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4790         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4791
4792         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4793         assert_eq!(commitment_txn[0].input.len(), 1);
4794         check_spends!(commitment_txn[0], chan_2.3);
4795
4796         mine_transaction(&nodes[1], &commitment_txn[0]);
4797         check_closed_broadcast!(nodes[1], true);
4798         check_added_monitors!(nodes[1], 1);
4799         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4800         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4801
4802         let htlc_timeout_tx;
4803         { // Extract one of the two HTLC-Timeout transaction
4804                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4805                 // ChannelMonitor: timeout tx * 2-or-3
4806                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4807
4808                 check_spends!(node_txn[0], commitment_txn[0]);
4809                 assert_eq!(node_txn[0].input.len(), 1);
4810                 assert_eq!(node_txn[0].output.len(), 1);
4811
4812                 if node_txn.len() > 2 {
4813                         check_spends!(node_txn[1], commitment_txn[0]);
4814                         assert_eq!(node_txn[1].input.len(), 1);
4815                         assert_eq!(node_txn[1].output.len(), 1);
4816                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4817
4818                         check_spends!(node_txn[2], commitment_txn[0]);
4819                         assert_eq!(node_txn[2].input.len(), 1);
4820                         assert_eq!(node_txn[2].output.len(), 1);
4821                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4822                 } else {
4823                         check_spends!(node_txn[1], commitment_txn[0]);
4824                         assert_eq!(node_txn[1].input.len(), 1);
4825                         assert_eq!(node_txn[1].output.len(), 1);
4826                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4827                 }
4828
4829                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4830                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4831                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4832                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4833                 if node_txn.len() > 2 {
4834                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4835                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4836                 } else {
4837                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4838                 }
4839         }
4840
4841         nodes[2].node.claim_funds(our_payment_preimage);
4842         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4843
4844         mine_transaction(&nodes[2], &commitment_txn[0]);
4845         check_added_monitors!(nodes[2], 2);
4846         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4847         let events = nodes[2].node.get_and_clear_pending_msg_events();
4848         match events[0] {
4849                 MessageSendEvent::UpdateHTLCs { .. } => {},
4850                 _ => panic!("Unexpected event"),
4851         }
4852         match events[1] {
4853                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4854                 _ => panic!("Unexepected event"),
4855         }
4856         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4857         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4858         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4859         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4860         assert_eq!(htlc_success_txn[0].input.len(), 1);
4861         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4862         assert_eq!(htlc_success_txn[1].input.len(), 1);
4863         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4864         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4865         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4866
4867         mine_transaction(&nodes[1], &htlc_timeout_tx);
4868         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4869         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 }]);
4870         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4871         assert!(htlc_updates.update_add_htlcs.is_empty());
4872         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4873         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4874         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4875         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4876         check_added_monitors!(nodes[1], 1);
4877
4878         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4879         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4880         {
4881                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4882         }
4883         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4884
4885         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4886         mine_transaction(&nodes[1], &htlc_success_txn[1]);
4887         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4888         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4889         assert!(updates.update_add_htlcs.is_empty());
4890         assert!(updates.update_fail_htlcs.is_empty());
4891         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4892         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4893         assert!(updates.update_fail_malformed_htlcs.is_empty());
4894         check_added_monitors!(nodes[1], 1);
4895
4896         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4897         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4898         expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4899 }
4900
4901 #[test]
4902 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4903         let chanmon_cfgs = create_chanmon_cfgs(2);
4904         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4905         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4906         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4907
4908         // Create some initial channels
4909         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4910
4911         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4912         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4913         assert_eq!(local_txn.len(), 1);
4914         assert_eq!(local_txn[0].input.len(), 1);
4915         check_spends!(local_txn[0], chan_1.3);
4916
4917         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4918         nodes[1].node.claim_funds(payment_preimage);
4919         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4920         check_added_monitors!(nodes[1], 1);
4921
4922         mine_transaction(&nodes[1], &local_txn[0]);
4923         check_added_monitors!(nodes[1], 1);
4924         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4925         let events = nodes[1].node.get_and_clear_pending_msg_events();
4926         match events[0] {
4927                 MessageSendEvent::UpdateHTLCs { .. } => {},
4928                 _ => panic!("Unexpected event"),
4929         }
4930         match events[1] {
4931                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4932                 _ => panic!("Unexepected event"),
4933         }
4934         let node_tx = {
4935                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4936                 assert_eq!(node_txn.len(), 1);
4937                 assert_eq!(node_txn[0].input.len(), 1);
4938                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4939                 check_spends!(node_txn[0], local_txn[0]);
4940                 node_txn[0].clone()
4941         };
4942
4943         mine_transaction(&nodes[1], &node_tx);
4944         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4945
4946         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4947         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4948         assert_eq!(spend_txn.len(), 1);
4949         assert_eq!(spend_txn[0].input.len(), 1);
4950         check_spends!(spend_txn[0], node_tx);
4951         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4952 }
4953
4954 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4955         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4956         // unrevoked commitment transaction.
4957         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4958         // a remote RAA before they could be failed backwards (and combinations thereof).
4959         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4960         // use the same payment hashes.
4961         // Thus, we use a six-node network:
4962         //
4963         // A \         / E
4964         //    - C - D -
4965         // B /         \ F
4966         // And test where C fails back to A/B when D announces its latest commitment transaction
4967         let chanmon_cfgs = create_chanmon_cfgs(6);
4968         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4969         // When this test was written, the default base fee floated based on the HTLC count.
4970         // It is now fixed, so we simply set the fee to the expected value here.
4971         let mut config = test_default_channel_config();
4972         config.channel_config.forwarding_fee_base_msat = 196;
4973         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4974                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4975         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4976
4977         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4978         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4979         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4980         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4981         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
4982
4983         // Rebalance and check output sanity...
4984         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4985         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4986         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4987
4988         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4989                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4990         // 0th HTLC:
4991         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
4992         // 1st HTLC:
4993         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
4994         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4995         // 2nd HTLC:
4996         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
4997         // 3rd HTLC:
4998         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
4999         // 4th HTLC:
5000         let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5001         // 5th HTLC:
5002         let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5003         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5004         // 6th HTLC:
5005         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());
5006         // 7th HTLC:
5007         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());
5008
5009         // 8th HTLC:
5010         let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5011         // 9th HTLC:
5012         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5013         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
5014
5015         // 10th HTLC:
5016         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
5017         // 11th HTLC:
5018         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5019         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());
5020
5021         // Double-check that six of the new HTLC were added
5022         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5023         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5024         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5025         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5026
5027         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5028         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5029         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5030         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5031         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5032         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5033         check_added_monitors!(nodes[4], 0);
5034
5035         let failed_destinations = vec![
5036                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5037                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5038                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5039                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5040         ];
5041         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5042         check_added_monitors!(nodes[4], 1);
5043
5044         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5045         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5046         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5047         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5048         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5049         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5050
5051         // Fail 3rd below-dust and 7th above-dust HTLCs
5052         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5053         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5054         check_added_monitors!(nodes[5], 0);
5055
5056         let failed_destinations_2 = vec![
5057                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5058                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5059         ];
5060         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5061         check_added_monitors!(nodes[5], 1);
5062
5063         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5064         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5065         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5066         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5067
5068         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5069
5070         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5071         let failed_destinations_3 = vec![
5072                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5073                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5074                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5075                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5076                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5077                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5078         ];
5079         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5080         check_added_monitors!(nodes[3], 1);
5081         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5082         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5083         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5084         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5085         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5086         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5087         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5088         if deliver_last_raa {
5089                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5090         } else {
5091                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5092         }
5093
5094         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5095         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5096         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5097         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5098         //
5099         // We now broadcast the latest commitment transaction, which *should* result in failures for
5100         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5101         // the non-broadcast above-dust HTLCs.
5102         //
5103         // Alternatively, we may broadcast the previous commitment transaction, which should only
5104         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5105         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5106
5107         if announce_latest {
5108                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5109         } else {
5110                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5111         }
5112         let events = nodes[2].node.get_and_clear_pending_events();
5113         let close_event = if deliver_last_raa {
5114                 assert_eq!(events.len(), 2 + 6);
5115                 events.last().clone().unwrap()
5116         } else {
5117                 assert_eq!(events.len(), 1);
5118                 events.last().clone().unwrap()
5119         };
5120         match close_event {
5121                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5122                 _ => panic!("Unexpected event"),
5123         }
5124
5125         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5126         check_closed_broadcast!(nodes[2], true);
5127         if deliver_last_raa {
5128                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5129
5130                 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();
5131                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5132         } else {
5133                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5134                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5135                 } else {
5136                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5137                 };
5138
5139                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5140         }
5141         check_added_monitors!(nodes[2], 3);
5142
5143         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5144         assert_eq!(cs_msgs.len(), 2);
5145         let mut a_done = false;
5146         for msg in cs_msgs {
5147                 match msg {
5148                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5149                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5150                                 // should be failed-backwards here.
5151                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5152                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5153                                         for htlc in &updates.update_fail_htlcs {
5154                                                 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 });
5155                                         }
5156                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5157                                         assert!(!a_done);
5158                                         a_done = true;
5159                                         &nodes[0]
5160                                 } else {
5161                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5162                                         for htlc in &updates.update_fail_htlcs {
5163                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5164                                         }
5165                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5166                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5167                                         &nodes[1]
5168                                 };
5169                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5170                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5171                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5172                                 if announce_latest {
5173                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5174                                         if *node_id == nodes[0].node.get_our_node_id() {
5175                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5176                                         }
5177                                 }
5178                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5179                         },
5180                         _ => panic!("Unexpected event"),
5181                 }
5182         }
5183
5184         let as_events = nodes[0].node.get_and_clear_pending_events();
5185         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5186         let mut as_failds = HashSet::new();
5187         let mut as_updates = 0;
5188         for event in as_events.iter() {
5189                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5190                         assert!(as_failds.insert(*payment_hash));
5191                         if *payment_hash != payment_hash_2 {
5192                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5193                         } else {
5194                                 assert!(!payment_failed_permanently);
5195                         }
5196                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5197                                 as_updates += 1;
5198                         }
5199                 } else if let &Event::PaymentFailed { .. } = event {
5200                 } else { panic!("Unexpected event"); }
5201         }
5202         assert!(as_failds.contains(&payment_hash_1));
5203         assert!(as_failds.contains(&payment_hash_2));
5204         if announce_latest {
5205                 assert!(as_failds.contains(&payment_hash_3));
5206                 assert!(as_failds.contains(&payment_hash_5));
5207         }
5208         assert!(as_failds.contains(&payment_hash_6));
5209
5210         let bs_events = nodes[1].node.get_and_clear_pending_events();
5211         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5212         let mut bs_failds = HashSet::new();
5213         let mut bs_updates = 0;
5214         for event in bs_events.iter() {
5215                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5216                         assert!(bs_failds.insert(*payment_hash));
5217                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5218                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5219                         } else {
5220                                 assert!(!payment_failed_permanently);
5221                         }
5222                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5223                                 bs_updates += 1;
5224                         }
5225                 } else if let &Event::PaymentFailed { .. } = event {
5226                 } else { panic!("Unexpected event"); }
5227         }
5228         assert!(bs_failds.contains(&payment_hash_1));
5229         assert!(bs_failds.contains(&payment_hash_2));
5230         if announce_latest {
5231                 assert!(bs_failds.contains(&payment_hash_4));
5232         }
5233         assert!(bs_failds.contains(&payment_hash_5));
5234
5235         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5236         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5237         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5238         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5239         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5240         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5241 }
5242
5243 #[test]
5244 fn test_fail_backwards_latest_remote_announce_a() {
5245         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5246 }
5247
5248 #[test]
5249 fn test_fail_backwards_latest_remote_announce_b() {
5250         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5251 }
5252
5253 #[test]
5254 fn test_fail_backwards_previous_remote_announce() {
5255         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5256         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5257         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5258 }
5259
5260 #[test]
5261 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5262         let chanmon_cfgs = create_chanmon_cfgs(2);
5263         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5264         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5265         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5266
5267         // Create some initial channels
5268         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5269
5270         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5271         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5272         assert_eq!(local_txn[0].input.len(), 1);
5273         check_spends!(local_txn[0], chan_1.3);
5274
5275         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5276         mine_transaction(&nodes[0], &local_txn[0]);
5277         check_closed_broadcast!(nodes[0], true);
5278         check_added_monitors!(nodes[0], 1);
5279         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5280         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5281
5282         let htlc_timeout = {
5283                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5284                 assert_eq!(node_txn.len(), 1);
5285                 assert_eq!(node_txn[0].input.len(), 1);
5286                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5287                 check_spends!(node_txn[0], local_txn[0]);
5288                 node_txn[0].clone()
5289         };
5290
5291         mine_transaction(&nodes[0], &htlc_timeout);
5292         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5293         expect_payment_failed!(nodes[0], our_payment_hash, false);
5294
5295         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5296         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5297         assert_eq!(spend_txn.len(), 3);
5298         check_spends!(spend_txn[0], local_txn[0]);
5299         assert_eq!(spend_txn[1].input.len(), 1);
5300         check_spends!(spend_txn[1], htlc_timeout);
5301         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5302         assert_eq!(spend_txn[2].input.len(), 2);
5303         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5304         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5305                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5306 }
5307
5308 #[test]
5309 fn test_key_derivation_params() {
5310         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5311         // manager rotation to test that `channel_keys_id` returned in
5312         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5313         // then derive a `delayed_payment_key`.
5314
5315         let chanmon_cfgs = create_chanmon_cfgs(3);
5316
5317         // We manually create the node configuration to backup the seed.
5318         let seed = [42; 32];
5319         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5320         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);
5321         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5322         let scorer = Mutex::new(test_utils::TestScorer::new());
5323         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5324         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)) };
5325         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5326         node_cfgs.remove(0);
5327         node_cfgs.insert(0, node);
5328
5329         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5330         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5331
5332         // Create some initial channels
5333         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5334         // for node 0
5335         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5336         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5337         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5338
5339         // Ensure all nodes are at the same height
5340         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5341         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5342         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5343         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5344
5345         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5346         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5347         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5348         assert_eq!(local_txn_1[0].input.len(), 1);
5349         check_spends!(local_txn_1[0], chan_1.3);
5350
5351         // We check funding pubkey are unique
5352         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]));
5353         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]));
5354         if from_0_funding_key_0 == from_1_funding_key_0
5355             || from_0_funding_key_0 == from_1_funding_key_1
5356             || from_0_funding_key_1 == from_1_funding_key_0
5357             || from_0_funding_key_1 == from_1_funding_key_1 {
5358                 panic!("Funding pubkeys aren't unique");
5359         }
5360
5361         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5362         mine_transaction(&nodes[0], &local_txn_1[0]);
5363         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5364         check_closed_broadcast!(nodes[0], true);
5365         check_added_monitors!(nodes[0], 1);
5366         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5367
5368         let htlc_timeout = {
5369                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5370                 assert_eq!(node_txn.len(), 1);
5371                 assert_eq!(node_txn[0].input.len(), 1);
5372                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5373                 check_spends!(node_txn[0], local_txn_1[0]);
5374                 node_txn[0].clone()
5375         };
5376
5377         mine_transaction(&nodes[0], &htlc_timeout);
5378         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5379         expect_payment_failed!(nodes[0], our_payment_hash, false);
5380
5381         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5382         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5383         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5384         assert_eq!(spend_txn.len(), 3);
5385         check_spends!(spend_txn[0], local_txn_1[0]);
5386         assert_eq!(spend_txn[1].input.len(), 1);
5387         check_spends!(spend_txn[1], htlc_timeout);
5388         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5389         assert_eq!(spend_txn[2].input.len(), 2);
5390         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5391         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5392                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5393 }
5394
5395 #[test]
5396 fn test_static_output_closing_tx() {
5397         let chanmon_cfgs = create_chanmon_cfgs(2);
5398         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5399         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5400         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5401
5402         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5403
5404         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5405         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5406
5407         mine_transaction(&nodes[0], &closing_tx);
5408         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5409         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5410
5411         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5412         assert_eq!(spend_txn.len(), 1);
5413         check_spends!(spend_txn[0], closing_tx);
5414
5415         mine_transaction(&nodes[1], &closing_tx);
5416         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5417         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5418
5419         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5420         assert_eq!(spend_txn.len(), 1);
5421         check_spends!(spend_txn[0], closing_tx);
5422 }
5423
5424 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5425         let chanmon_cfgs = create_chanmon_cfgs(2);
5426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5428         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5429         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5430
5431         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5432
5433         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5434         // present in B's local commitment transaction, but none of A's commitment transactions.
5435         nodes[1].node.claim_funds(payment_preimage);
5436         check_added_monitors!(nodes[1], 1);
5437         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5438
5439         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5440         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5441         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5442
5443         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5444         check_added_monitors!(nodes[0], 1);
5445         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5446         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5447         check_added_monitors!(nodes[1], 1);
5448
5449         let starting_block = nodes[1].best_block_info();
5450         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5451         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5452                 connect_block(&nodes[1], &block);
5453                 block.header.prev_blockhash = block.block_hash();
5454         }
5455         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5456         check_closed_broadcast!(nodes[1], true);
5457         check_added_monitors!(nodes[1], 1);
5458         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5459 }
5460
5461 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5462         let chanmon_cfgs = create_chanmon_cfgs(2);
5463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5465         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5466         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5467
5468         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5469         nodes[0].node.send_payment_with_route(&route, payment_hash,
5470                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5471         check_added_monitors!(nodes[0], 1);
5472
5473         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5474
5475         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5476         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5477         // to "time out" the HTLC.
5478
5479         let starting_block = nodes[1].best_block_info();
5480         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5481
5482         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5483                 connect_block(&nodes[0], &block);
5484                 block.header.prev_blockhash = block.block_hash();
5485         }
5486         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5487         check_closed_broadcast!(nodes[0], true);
5488         check_added_monitors!(nodes[0], 1);
5489         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5490 }
5491
5492 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5493         let chanmon_cfgs = create_chanmon_cfgs(3);
5494         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5495         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5496         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5497         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5498
5499         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5500         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5501         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5502         // actually revoked.
5503         let htlc_value = if use_dust { 50000 } else { 3000000 };
5504         let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5505         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5506         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5507         check_added_monitors!(nodes[1], 1);
5508
5509         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5510         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5511         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5512         check_added_monitors!(nodes[0], 1);
5513         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5514         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5515         check_added_monitors!(nodes[1], 1);
5516         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5517         check_added_monitors!(nodes[1], 1);
5518         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5519
5520         if check_revoke_no_close {
5521                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5522                 check_added_monitors!(nodes[0], 1);
5523         }
5524
5525         let starting_block = nodes[1].best_block_info();
5526         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5527         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5528                 connect_block(&nodes[0], &block);
5529                 block.header.prev_blockhash = block.block_hash();
5530         }
5531         if !check_revoke_no_close {
5532                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5533                 check_closed_broadcast!(nodes[0], true);
5534                 check_added_monitors!(nodes[0], 1);
5535                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5536         } else {
5537                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5538         }
5539 }
5540
5541 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5542 // There are only a few cases to test here:
5543 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5544 //    broadcastable commitment transactions result in channel closure,
5545 //  * its included in an unrevoked-but-previous remote commitment transaction,
5546 //  * its included in the latest remote or local commitment transactions.
5547 // We test each of the three possible commitment transactions individually and use both dust and
5548 // non-dust HTLCs.
5549 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5550 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5551 // tested for at least one of the cases in other tests.
5552 #[test]
5553 fn htlc_claim_single_commitment_only_a() {
5554         do_htlc_claim_local_commitment_only(true);
5555         do_htlc_claim_local_commitment_only(false);
5556
5557         do_htlc_claim_current_remote_commitment_only(true);
5558         do_htlc_claim_current_remote_commitment_only(false);
5559 }
5560
5561 #[test]
5562 fn htlc_claim_single_commitment_only_b() {
5563         do_htlc_claim_previous_remote_commitment_only(true, false);
5564         do_htlc_claim_previous_remote_commitment_only(false, false);
5565         do_htlc_claim_previous_remote_commitment_only(true, true);
5566         do_htlc_claim_previous_remote_commitment_only(false, true);
5567 }
5568
5569 #[test]
5570 #[should_panic]
5571 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5572         let chanmon_cfgs = create_chanmon_cfgs(2);
5573         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5574         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5575         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5576         // Force duplicate randomness for every get-random call
5577         for node in nodes.iter() {
5578                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5579         }
5580
5581         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5582         let channel_value_satoshis=10000;
5583         let push_msat=10001;
5584         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5585         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5586         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5587         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5588
5589         // Create a second channel with the same random values. This used to panic due to a colliding
5590         // channel_id, but now panics due to a colliding outbound SCID alias.
5591         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5592 }
5593
5594 #[test]
5595 fn bolt2_open_channel_sending_node_checks_part2() {
5596         let chanmon_cfgs = create_chanmon_cfgs(2);
5597         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5598         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5599         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5600
5601         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5602         let channel_value_satoshis=2^24;
5603         let push_msat=10001;
5604         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5605
5606         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5607         let channel_value_satoshis=10000;
5608         // Test when push_msat is equal to 1000 * funding_satoshis.
5609         let push_msat=1000*channel_value_satoshis+1;
5610         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5611
5612         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5613         let channel_value_satoshis=10000;
5614         let push_msat=10001;
5615         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
5616         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5617         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5618
5619         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5620         // 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
5621         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5622
5623         // 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.
5624         assert!(BREAKDOWN_TIMEOUT>0);
5625         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5626
5627         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5628         let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5629         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5630
5631         // 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.
5632         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5633         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5634         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5635         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5636         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5637 }
5638
5639 #[test]
5640 fn bolt2_open_channel_sane_dust_limit() {
5641         let chanmon_cfgs = create_chanmon_cfgs(2);
5642         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5643         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5644         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5645
5646         let channel_value_satoshis=1000000;
5647         let push_msat=10001;
5648         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5649         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5650         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5651         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5652
5653         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5654         let events = nodes[1].node.get_and_clear_pending_msg_events();
5655         let err_msg = match events[0] {
5656                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5657                         msg.clone()
5658                 },
5659                 _ => panic!("Unexpected event"),
5660         };
5661         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5662 }
5663
5664 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5665 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5666 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5667 // is no longer affordable once it's freed.
5668 #[test]
5669 fn test_fail_holding_cell_htlc_upon_free() {
5670         let chanmon_cfgs = create_chanmon_cfgs(2);
5671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5673         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5674         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5675
5676         // First nodes[0] generates an update_fee, setting the channel's
5677         // pending_update_fee.
5678         {
5679                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5680                 *feerate_lock += 20;
5681         }
5682         nodes[0].node.timer_tick_occurred();
5683         check_added_monitors!(nodes[0], 1);
5684
5685         let events = nodes[0].node.get_and_clear_pending_msg_events();
5686         assert_eq!(events.len(), 1);
5687         let (update_msg, commitment_signed) = match events[0] {
5688                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5689                         (update_fee.as_ref(), commitment_signed)
5690                 },
5691                 _ => panic!("Unexpected event"),
5692         };
5693
5694         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5695
5696         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5697         let channel_reserve = chan_stat.channel_reserve_msat;
5698         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5699         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5700
5701         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5702         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5703         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5704
5705         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5706         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5707                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5708         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5709         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5710
5711         // Flush the pending fee update.
5712         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5713         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5714         check_added_monitors!(nodes[1], 1);
5715         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5716         check_added_monitors!(nodes[0], 1);
5717
5718         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5719         // HTLC, but now that the fee has been raised the payment will now fail, causing
5720         // us to surface its failure to the user.
5721         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5722         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5723         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);
5724
5725         // Check that the payment failed to be sent out.
5726         let events = nodes[0].node.get_and_clear_pending_events();
5727         assert_eq!(events.len(), 2);
5728         match &events[0] {
5729                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5730                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5731                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5732                         assert_eq!(*payment_failed_permanently, false);
5733                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5734                 },
5735                 _ => panic!("Unexpected event"),
5736         }
5737         match &events[1] {
5738                 &Event::PaymentFailed { ref payment_hash, .. } => {
5739                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5740                 },
5741                 _ => panic!("Unexpected event"),
5742         }
5743 }
5744
5745 // Test that if multiple HTLCs are released from the holding cell and one is
5746 // valid but the other is no longer valid upon release, the valid HTLC can be
5747 // successfully completed while the other one fails as expected.
5748 #[test]
5749 fn test_free_and_fail_holding_cell_htlcs() {
5750         let chanmon_cfgs = create_chanmon_cfgs(2);
5751         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5752         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5753         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5754         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5755
5756         // First nodes[0] generates an update_fee, setting the channel's
5757         // pending_update_fee.
5758         {
5759                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5760                 *feerate_lock += 200;
5761         }
5762         nodes[0].node.timer_tick_occurred();
5763         check_added_monitors!(nodes[0], 1);
5764
5765         let events = nodes[0].node.get_and_clear_pending_msg_events();
5766         assert_eq!(events.len(), 1);
5767         let (update_msg, commitment_signed) = match events[0] {
5768                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5769                         (update_fee.as_ref(), commitment_signed)
5770                 },
5771                 _ => panic!("Unexpected event"),
5772         };
5773
5774         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5775
5776         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5777         let channel_reserve = chan_stat.channel_reserve_msat;
5778         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5779         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5780
5781         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5782         let amt_1 = 20000;
5783         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5784         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5785         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5786
5787         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5788         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5789                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5790         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5791         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5792         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5793         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5794                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5795         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5796         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5797
5798         // Flush the pending fee update.
5799         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5800         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5801         check_added_monitors!(nodes[1], 1);
5802         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5803         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5804         check_added_monitors!(nodes[0], 2);
5805
5806         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5807         // but now that the fee has been raised the second payment will now fail, causing us
5808         // to surface its failure to the user. The first payment should succeed.
5809         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5810         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5811         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);
5812
5813         // Check that the second payment failed to be sent out.
5814         let events = nodes[0].node.get_and_clear_pending_events();
5815         assert_eq!(events.len(), 2);
5816         match &events[0] {
5817                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5818                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5819                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5820                         assert_eq!(*payment_failed_permanently, false);
5821                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5822                 },
5823                 _ => panic!("Unexpected event"),
5824         }
5825         match &events[1] {
5826                 &Event::PaymentFailed { ref payment_hash, .. } => {
5827                         assert_eq!(payment_hash_2.clone(), *payment_hash);
5828                 },
5829                 _ => panic!("Unexpected event"),
5830         }
5831
5832         // Complete the first payment and the RAA from the fee update.
5833         let (payment_event, send_raa_event) = {
5834                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5835                 assert_eq!(msgs.len(), 2);
5836                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5837         };
5838         let raa = match send_raa_event {
5839                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5840                 _ => panic!("Unexpected event"),
5841         };
5842         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5843         check_added_monitors!(nodes[1], 1);
5844         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5845         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5846         let events = nodes[1].node.get_and_clear_pending_events();
5847         assert_eq!(events.len(), 1);
5848         match events[0] {
5849                 Event::PendingHTLCsForwardable { .. } => {},
5850                 _ => panic!("Unexpected event"),
5851         }
5852         nodes[1].node.process_pending_htlc_forwards();
5853         let events = nodes[1].node.get_and_clear_pending_events();
5854         assert_eq!(events.len(), 1);
5855         match events[0] {
5856                 Event::PaymentClaimable { .. } => {},
5857                 _ => panic!("Unexpected event"),
5858         }
5859         nodes[1].node.claim_funds(payment_preimage_1);
5860         check_added_monitors!(nodes[1], 1);
5861         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5862
5863         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5864         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5865         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5866         expect_payment_sent!(nodes[0], payment_preimage_1);
5867 }
5868
5869 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5870 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5871 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5872 // once it's freed.
5873 #[test]
5874 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5875         let chanmon_cfgs = create_chanmon_cfgs(3);
5876         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5877         // Avoid having to include routing fees in calculations
5878         let mut config = test_default_channel_config();
5879         config.channel_config.forwarding_fee_base_msat = 0;
5880         config.channel_config.forwarding_fee_proportional_millionths = 0;
5881         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5882         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5883         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5884         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5885
5886         // First nodes[1] generates an update_fee, setting the channel's
5887         // pending_update_fee.
5888         {
5889                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5890                 *feerate_lock += 20;
5891         }
5892         nodes[1].node.timer_tick_occurred();
5893         check_added_monitors!(nodes[1], 1);
5894
5895         let events = nodes[1].node.get_and_clear_pending_msg_events();
5896         assert_eq!(events.len(), 1);
5897         let (update_msg, commitment_signed) = match events[0] {
5898                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5899                         (update_fee.as_ref(), commitment_signed)
5900                 },
5901                 _ => panic!("Unexpected event"),
5902         };
5903
5904         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5905
5906         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5907         let channel_reserve = chan_stat.channel_reserve_msat;
5908         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5909         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5910
5911         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5912         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5913         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5914         let payment_event = {
5915                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5916                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5917                 check_added_monitors!(nodes[0], 1);
5918
5919                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5920                 assert_eq!(events.len(), 1);
5921
5922                 SendEvent::from_event(events.remove(0))
5923         };
5924         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5925         check_added_monitors!(nodes[1], 0);
5926         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5927         expect_pending_htlcs_forwardable!(nodes[1]);
5928
5929         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5930         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5931
5932         // Flush the pending fee update.
5933         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5934         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5935         check_added_monitors!(nodes[2], 1);
5936         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5937         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5938         check_added_monitors!(nodes[1], 2);
5939
5940         // A final RAA message is generated to finalize the fee update.
5941         let events = nodes[1].node.get_and_clear_pending_msg_events();
5942         assert_eq!(events.len(), 1);
5943
5944         let raa_msg = match &events[0] {
5945                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5946                         msg.clone()
5947                 },
5948                 _ => panic!("Unexpected event"),
5949         };
5950
5951         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5952         check_added_monitors!(nodes[2], 1);
5953         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5954
5955         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5956         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5957         assert_eq!(process_htlc_forwards_event.len(), 2);
5958         match &process_htlc_forwards_event[0] {
5959                 &Event::PendingHTLCsForwardable { .. } => {},
5960                 _ => panic!("Unexpected event"),
5961         }
5962
5963         // In response, we call ChannelManager's process_pending_htlc_forwards
5964         nodes[1].node.process_pending_htlc_forwards();
5965         check_added_monitors!(nodes[1], 1);
5966
5967         // This causes the HTLC to be failed backwards.
5968         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5969         assert_eq!(fail_event.len(), 1);
5970         let (fail_msg, commitment_signed) = match &fail_event[0] {
5971                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5972                         assert_eq!(updates.update_add_htlcs.len(), 0);
5973                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5974                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5975                         assert_eq!(updates.update_fail_htlcs.len(), 1);
5976                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5977                 },
5978                 _ => panic!("Unexpected event"),
5979         };
5980
5981         // Pass the failure messages back to nodes[0].
5982         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5983         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5984
5985         // Complete the HTLC failure+removal process.
5986         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5987         check_added_monitors!(nodes[0], 1);
5988         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5989         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5990         check_added_monitors!(nodes[1], 2);
5991         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5992         assert_eq!(final_raa_event.len(), 1);
5993         let raa = match &final_raa_event[0] {
5994                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5995                 _ => panic!("Unexpected event"),
5996         };
5997         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5998         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5999         check_added_monitors!(nodes[0], 1);
6000 }
6001
6002 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6003 // 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.
6004 //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.
6005
6006 #[test]
6007 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6008         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6009         let chanmon_cfgs = create_chanmon_cfgs(2);
6010         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6011         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6012         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6013         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6014
6015         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6016         route.paths[0].hops[0].fee_msat = 100;
6017
6018         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6019                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6020                 ), true, APIError::ChannelUnavailable { .. }, {});
6021         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6022 }
6023
6024 #[test]
6025 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6026         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6027         let chanmon_cfgs = create_chanmon_cfgs(2);
6028         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6029         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6030         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6031         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6032
6033         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6034         route.paths[0].hops[0].fee_msat = 0;
6035         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6036                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6037                 true, APIError::ChannelUnavailable { ref err },
6038                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6039
6040         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6041         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6042 }
6043
6044 #[test]
6045 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6046         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6047         let chanmon_cfgs = create_chanmon_cfgs(2);
6048         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6049         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6050         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6051         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6052
6053         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6054         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6055                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6056         check_added_monitors!(nodes[0], 1);
6057         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6058         updates.update_add_htlcs[0].amount_msat = 0;
6059
6060         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6061         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6062         check_closed_broadcast!(nodes[1], true).unwrap();
6063         check_added_monitors!(nodes[1], 1);
6064         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6065 }
6066
6067 #[test]
6068 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6069         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6070         //It is enforced when constructing a route.
6071         let chanmon_cfgs = create_chanmon_cfgs(2);
6072         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6073         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6074         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6075         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6076
6077         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6078                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6079         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6080         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6081         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6082                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6083                 ), true, APIError::InvalidRoute { ref err },
6084                 assert_eq!(err, &"Channel CLTV overflowed?"));
6085 }
6086
6087 #[test]
6088 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6089         //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.
6090         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6091         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6092         let chanmon_cfgs = create_chanmon_cfgs(2);
6093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6095         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6096         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6097         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6098                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6099
6100         // Fetch a route in advance as we will be unable to once we're unable to send.
6101         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6102         for i in 0..max_accepted_htlcs {
6103                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6104                 let payment_event = {
6105                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6106                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6107                         check_added_monitors!(nodes[0], 1);
6108
6109                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6110                         assert_eq!(events.len(), 1);
6111                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6112                                 assert_eq!(htlcs[0].htlc_id, i);
6113                         } else {
6114                                 assert!(false);
6115                         }
6116                         SendEvent::from_event(events.remove(0))
6117                 };
6118                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6119                 check_added_monitors!(nodes[1], 0);
6120                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6121
6122                 expect_pending_htlcs_forwardable!(nodes[1]);
6123                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6124         }
6125         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6126                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6127                 ), true, APIError::ChannelUnavailable { .. }, {});
6128
6129         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6130 }
6131
6132 #[test]
6133 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6134         //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.
6135         let chanmon_cfgs = create_chanmon_cfgs(2);
6136         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6137         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6138         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6139         let channel_value = 100000;
6140         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6141         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6142
6143         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6144
6145         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6146         // Manually create a route over our max in flight (which our router normally automatically
6147         // limits us to.
6148         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6149         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6150                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6151                 ), true, APIError::ChannelUnavailable { .. }, {});
6152         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6153
6154         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6155 }
6156
6157 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6158 #[test]
6159 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6160         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6161         let chanmon_cfgs = create_chanmon_cfgs(2);
6162         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6163         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6164         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6165         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6166         let htlc_minimum_msat: u64;
6167         {
6168                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6169                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6170                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6171                 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6172         }
6173
6174         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6175         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6176                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6177         check_added_monitors!(nodes[0], 1);
6178         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6179         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6180         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6181         assert!(nodes[1].node.list_channels().is_empty());
6182         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6183         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()));
6184         check_added_monitors!(nodes[1], 1);
6185         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6186 }
6187
6188 #[test]
6189 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6190         //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
6191         let chanmon_cfgs = create_chanmon_cfgs(2);
6192         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6193         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6194         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6195         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6196
6197         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6198         let channel_reserve = chan_stat.channel_reserve_msat;
6199         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6200         let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6201         // The 2* and +1 are for the fee spike reserve.
6202         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6203
6204         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6205         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6206         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6207                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6208         check_added_monitors!(nodes[0], 1);
6209         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6210
6211         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6212         // at this time channel-initiatee receivers are not required to enforce that senders
6213         // respect the fee_spike_reserve.
6214         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6215         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6216
6217         assert!(nodes[1].node.list_channels().is_empty());
6218         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6219         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6220         check_added_monitors!(nodes[1], 1);
6221         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6222 }
6223
6224 #[test]
6225 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6226         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6227         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6228         let chanmon_cfgs = create_chanmon_cfgs(2);
6229         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6230         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6231         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6232         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6233
6234         let send_amt = 3999999;
6235         let (mut route, our_payment_hash, _, our_payment_secret) =
6236                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6237         route.paths[0].hops[0].fee_msat = send_amt;
6238         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6239         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6240         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6241         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6242                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6243         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6244
6245         let mut msg = msgs::UpdateAddHTLC {
6246                 channel_id: chan.2,
6247                 htlc_id: 0,
6248                 amount_msat: 1000,
6249                 payment_hash: our_payment_hash,
6250                 cltv_expiry: htlc_cltv,
6251                 onion_routing_packet: onion_packet.clone(),
6252         };
6253
6254         for i in 0..50 {
6255                 msg.htlc_id = i as u64;
6256                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6257         }
6258         msg.htlc_id = (50) as u64;
6259         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6260
6261         assert!(nodes[1].node.list_channels().is_empty());
6262         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6263         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6264         check_added_monitors!(nodes[1], 1);
6265         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6266 }
6267
6268 #[test]
6269 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6270         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6271         let chanmon_cfgs = create_chanmon_cfgs(2);
6272         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6273         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6274         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6275         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6276
6277         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6278         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6279                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6280         check_added_monitors!(nodes[0], 1);
6281         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6282         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;
6283         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6284
6285         assert!(nodes[1].node.list_channels().is_empty());
6286         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6287         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6288         check_added_monitors!(nodes[1], 1);
6289         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6290 }
6291
6292 #[test]
6293 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6294         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6295         let chanmon_cfgs = create_chanmon_cfgs(2);
6296         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6297         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6298         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6299
6300         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6301         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6302         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6303                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6304         check_added_monitors!(nodes[0], 1);
6305         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6306         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6307         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6308
6309         assert!(nodes[1].node.list_channels().is_empty());
6310         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6311         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6312         check_added_monitors!(nodes[1], 1);
6313         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6314 }
6315
6316 #[test]
6317 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6318         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6319         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6320         // after disconnect and that non-sequential htlc_ids result in a channel failure.
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
6326         create_announced_chan_between_nodes(&nodes, 0, 1);
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 updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6332         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6333
6334         //Disconnect and Reconnect
6335         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6336         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6337         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
6338         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6339         assert_eq!(reestablish_1.len(), 1);
6340         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
6341         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6342         assert_eq!(reestablish_2.len(), 1);
6343         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6344         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6345         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6346         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6347
6348         //Resend HTLC
6349         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6350         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6351         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6352         check_added_monitors!(nodes[1], 1);
6353         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6354
6355         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6356
6357         assert!(nodes[1].node.list_channels().is_empty());
6358         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6359         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6360         check_added_monitors!(nodes[1], 1);
6361         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6362 }
6363
6364 #[test]
6365 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6366         //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.
6367
6368         let chanmon_cfgs = create_chanmon_cfgs(2);
6369         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6370         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6371         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6372         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6373         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6374         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6375                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6376
6377         check_added_monitors!(nodes[0], 1);
6378         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6379         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6380
6381         let update_msg = msgs::UpdateFulfillHTLC{
6382                 channel_id: chan.2,
6383                 htlc_id: 0,
6384                 payment_preimage: our_payment_preimage,
6385         };
6386
6387         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6388
6389         assert!(nodes[0].node.list_channels().is_empty());
6390         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6391         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()));
6392         check_added_monitors!(nodes[0], 1);
6393         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6394 }
6395
6396 #[test]
6397 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6398         //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.
6399
6400         let chanmon_cfgs = create_chanmon_cfgs(2);
6401         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6402         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6403         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6404         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6405
6406         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6407         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6408                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6409         check_added_monitors!(nodes[0], 1);
6410         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6411         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6412
6413         let update_msg = msgs::UpdateFailHTLC{
6414                 channel_id: chan.2,
6415                 htlc_id: 0,
6416                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6417         };
6418
6419         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6420
6421         assert!(nodes[0].node.list_channels().is_empty());
6422         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6423         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()));
6424         check_added_monitors!(nodes[0], 1);
6425         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6426 }
6427
6428 #[test]
6429 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6430         //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.
6431
6432         let chanmon_cfgs = create_chanmon_cfgs(2);
6433         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6434         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6435         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6436         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6437
6438         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6439         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6440                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6441         check_added_monitors!(nodes[0], 1);
6442         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6443         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6444         let update_msg = msgs::UpdateFailMalformedHTLC{
6445                 channel_id: chan.2,
6446                 htlc_id: 0,
6447                 sha256_of_onion: [1; 32],
6448                 failure_code: 0x8000,
6449         };
6450
6451         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6452
6453         assert!(nodes[0].node.list_channels().is_empty());
6454         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6455         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()));
6456         check_added_monitors!(nodes[0], 1);
6457         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6458 }
6459
6460 #[test]
6461 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6462         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6463
6464         let chanmon_cfgs = create_chanmon_cfgs(2);
6465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6467         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6468         create_announced_chan_between_nodes(&nodes, 0, 1);
6469
6470         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6471
6472         nodes[1].node.claim_funds(our_payment_preimage);
6473         check_added_monitors!(nodes[1], 1);
6474         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6475
6476         let events = nodes[1].node.get_and_clear_pending_msg_events();
6477         assert_eq!(events.len(), 1);
6478         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6479                 match events[0] {
6480                         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, .. } } => {
6481                                 assert!(update_add_htlcs.is_empty());
6482                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6483                                 assert!(update_fail_htlcs.is_empty());
6484                                 assert!(update_fail_malformed_htlcs.is_empty());
6485                                 assert!(update_fee.is_none());
6486                                 update_fulfill_htlcs[0].clone()
6487                         },
6488                         _ => panic!("Unexpected event"),
6489                 }
6490         };
6491
6492         update_fulfill_msg.htlc_id = 1;
6493
6494         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6495
6496         assert!(nodes[0].node.list_channels().is_empty());
6497         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6498         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6499         check_added_monitors!(nodes[0], 1);
6500         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6501 }
6502
6503 #[test]
6504 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6505         //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.
6506
6507         let chanmon_cfgs = create_chanmon_cfgs(2);
6508         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6509         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6510         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6511         create_announced_chan_between_nodes(&nodes, 0, 1);
6512
6513         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6514
6515         nodes[1].node.claim_funds(our_payment_preimage);
6516         check_added_monitors!(nodes[1], 1);
6517         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6518
6519         let events = nodes[1].node.get_and_clear_pending_msg_events();
6520         assert_eq!(events.len(), 1);
6521         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6522                 match events[0] {
6523                         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, .. } } => {
6524                                 assert!(update_add_htlcs.is_empty());
6525                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6526                                 assert!(update_fail_htlcs.is_empty());
6527                                 assert!(update_fail_malformed_htlcs.is_empty());
6528                                 assert!(update_fee.is_none());
6529                                 update_fulfill_htlcs[0].clone()
6530                         },
6531                         _ => panic!("Unexpected event"),
6532                 }
6533         };
6534
6535         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6536
6537         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6538
6539         assert!(nodes[0].node.list_channels().is_empty());
6540         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6541         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6542         check_added_monitors!(nodes[0], 1);
6543         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6544 }
6545
6546 #[test]
6547 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6548         //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.
6549
6550         let chanmon_cfgs = create_chanmon_cfgs(2);
6551         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6552         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6553         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6554         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6555
6556         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6557         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6558                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6559         check_added_monitors!(nodes[0], 1);
6560
6561         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6563
6564         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6565         check_added_monitors!(nodes[1], 0);
6566         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6567
6568         let events = nodes[1].node.get_and_clear_pending_msg_events();
6569
6570         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6571                 match events[0] {
6572                         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, .. } } => {
6573                                 assert!(update_add_htlcs.is_empty());
6574                                 assert!(update_fulfill_htlcs.is_empty());
6575                                 assert!(update_fail_htlcs.is_empty());
6576                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6577                                 assert!(update_fee.is_none());
6578                                 update_fail_malformed_htlcs[0].clone()
6579                         },
6580                         _ => panic!("Unexpected event"),
6581                 }
6582         };
6583         update_msg.failure_code &= !0x8000;
6584         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6585
6586         assert!(nodes[0].node.list_channels().is_empty());
6587         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6588         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6589         check_added_monitors!(nodes[0], 1);
6590         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6591 }
6592
6593 #[test]
6594 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6595         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6596         //    * 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.
6597
6598         let chanmon_cfgs = create_chanmon_cfgs(3);
6599         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6600         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6601         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6602         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6603         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6604
6605         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6606
6607         //First hop
6608         let mut payment_event = {
6609                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6610                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6611                 check_added_monitors!(nodes[0], 1);
6612                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6613                 assert_eq!(events.len(), 1);
6614                 SendEvent::from_event(events.remove(0))
6615         };
6616         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6617         check_added_monitors!(nodes[1], 0);
6618         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6619         expect_pending_htlcs_forwardable!(nodes[1]);
6620         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6621         assert_eq!(events_2.len(), 1);
6622         check_added_monitors!(nodes[1], 1);
6623         payment_event = SendEvent::from_event(events_2.remove(0));
6624         assert_eq!(payment_event.msgs.len(), 1);
6625
6626         //Second Hop
6627         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6628         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6629         check_added_monitors!(nodes[2], 0);
6630         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6631
6632         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6633         assert_eq!(events_3.len(), 1);
6634         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6635                 match events_3[0] {
6636                         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 } } => {
6637                                 assert!(update_add_htlcs.is_empty());
6638                                 assert!(update_fulfill_htlcs.is_empty());
6639                                 assert!(update_fail_htlcs.is_empty());
6640                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6641                                 assert!(update_fee.is_none());
6642                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6643                         },
6644                         _ => panic!("Unexpected event"),
6645                 }
6646         };
6647
6648         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6649
6650         check_added_monitors!(nodes[1], 0);
6651         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6652         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 }]);
6653         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6654         assert_eq!(events_4.len(), 1);
6655
6656         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6657         match events_4[0] {
6658                 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, .. } } => {
6659                         assert!(update_add_htlcs.is_empty());
6660                         assert!(update_fulfill_htlcs.is_empty());
6661                         assert_eq!(update_fail_htlcs.len(), 1);
6662                         assert!(update_fail_malformed_htlcs.is_empty());
6663                         assert!(update_fee.is_none());
6664                 },
6665                 _ => panic!("Unexpected event"),
6666         };
6667
6668         check_added_monitors!(nodes[1], 1);
6669 }
6670
6671 #[test]
6672 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6673         let chanmon_cfgs = create_chanmon_cfgs(3);
6674         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6675         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6676         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6677         create_announced_chan_between_nodes(&nodes, 0, 1);
6678         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6679
6680         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6681
6682         // First hop
6683         let mut payment_event = {
6684                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6685                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6686                 check_added_monitors!(nodes[0], 1);
6687                 SendEvent::from_node(&nodes[0])
6688         };
6689
6690         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6691         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6692         expect_pending_htlcs_forwardable!(nodes[1]);
6693         check_added_monitors!(nodes[1], 1);
6694         payment_event = SendEvent::from_node(&nodes[1]);
6695         assert_eq!(payment_event.msgs.len(), 1);
6696
6697         // Second Hop
6698         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6699         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6700         check_added_monitors!(nodes[2], 0);
6701         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6702
6703         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6704         assert_eq!(events_3.len(), 1);
6705         match events_3[0] {
6706                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6707                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6708                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6709                         update_msg.failure_code |= 0x2000;
6710
6711                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6712                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6713                 },
6714                 _ => panic!("Unexpected event"),
6715         }
6716
6717         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6718                 vec![HTLCDestination::NextHopChannel {
6719                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6720         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6721         assert_eq!(events_4.len(), 1);
6722         check_added_monitors!(nodes[1], 1);
6723
6724         match events_4[0] {
6725                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6726                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6727                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6728                 },
6729                 _ => panic!("Unexpected event"),
6730         }
6731
6732         let events_5 = nodes[0].node.get_and_clear_pending_events();
6733         assert_eq!(events_5.len(), 2);
6734
6735         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6736         // the node originating the error to its next hop.
6737         match events_5[0] {
6738                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6739                 } => {
6740                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6741                         assert!(is_permanent);
6742                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6743                 },
6744                 _ => panic!("Unexpected event"),
6745         }
6746         match events_5[1] {
6747                 Event::PaymentFailed { payment_hash, .. } => {
6748                         assert_eq!(payment_hash, our_payment_hash);
6749                 },
6750                 _ => panic!("Unexpected event"),
6751         }
6752
6753         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6754 }
6755
6756 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6757         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6758         // 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
6759         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6760
6761         let mut chanmon_cfgs = create_chanmon_cfgs(2);
6762         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6763         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6764         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6765         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6766         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6767
6768         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6769                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6770
6771         // We route 2 dust-HTLCs between A and B
6772         let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6773         let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6774         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6775
6776         // Cache one local commitment tx as previous
6777         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6778
6779         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6780         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6781         check_added_monitors!(nodes[1], 0);
6782         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6783         check_added_monitors!(nodes[1], 1);
6784
6785         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6786         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6787         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6788         check_added_monitors!(nodes[0], 1);
6789
6790         // Cache one local commitment tx as lastest
6791         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6792
6793         let events = nodes[0].node.get_and_clear_pending_msg_events();
6794         match events[0] {
6795                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6796                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6797                 },
6798                 _ => panic!("Unexpected event"),
6799         }
6800         match events[1] {
6801                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6802                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6803                 },
6804                 _ => panic!("Unexpected event"),
6805         }
6806
6807         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6808         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6809         if announce_latest {
6810                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6811         } else {
6812                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6813         }
6814
6815         check_closed_broadcast!(nodes[0], true);
6816         check_added_monitors!(nodes[0], 1);
6817         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6818
6819         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6820         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6821         let events = nodes[0].node.get_and_clear_pending_events();
6822         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6823         assert_eq!(events.len(), 4);
6824         let mut first_failed = false;
6825         for event in events {
6826                 match event {
6827                         Event::PaymentPathFailed { payment_hash, .. } => {
6828                                 if payment_hash == payment_hash_1 {
6829                                         assert!(!first_failed);
6830                                         first_failed = true;
6831                                 } else {
6832                                         assert_eq!(payment_hash, payment_hash_2);
6833                                 }
6834                         },
6835                         Event::PaymentFailed { .. } => {}
6836                         _ => panic!("Unexpected event"),
6837                 }
6838         }
6839 }
6840
6841 #[test]
6842 fn test_failure_delay_dust_htlc_local_commitment() {
6843         do_test_failure_delay_dust_htlc_local_commitment(true);
6844         do_test_failure_delay_dust_htlc_local_commitment(false);
6845 }
6846
6847 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6848         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6849         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6850         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6851         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6852         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6853         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6854
6855         let chanmon_cfgs = create_chanmon_cfgs(3);
6856         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6857         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6858         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6859         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6860
6861         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6862                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6863
6864         let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6865         let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6866
6867         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6868         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6869
6870         // We revoked bs_commitment_tx
6871         if revoked {
6872                 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6873                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6874         }
6875
6876         let mut timeout_tx = Vec::new();
6877         if local {
6878                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6879                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6880                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6881                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6882                 expect_payment_failed!(nodes[0], dust_hash, false);
6883
6884                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6885                 check_closed_broadcast!(nodes[0], true);
6886                 check_added_monitors!(nodes[0], 1);
6887                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6888                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6889                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6890                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6891                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6892                 mine_transaction(&nodes[0], &timeout_tx[0]);
6893                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6894                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6895         } else {
6896                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6897                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6898                 check_closed_broadcast!(nodes[0], true);
6899                 check_added_monitors!(nodes[0], 1);
6900                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6901                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6902
6903                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6904                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6905                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6906                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6907                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6908                 // dust HTLC should have been failed.
6909                 expect_payment_failed!(nodes[0], dust_hash, false);
6910
6911                 if !revoked {
6912                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6913                 } else {
6914                         assert_eq!(timeout_tx[0].lock_time.0, 11);
6915                 }
6916                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6917                 mine_transaction(&nodes[0], &timeout_tx[0]);
6918                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6919                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6920                 expect_payment_failed!(nodes[0], non_dust_hash, false);
6921         }
6922 }
6923
6924 #[test]
6925 fn test_sweep_outbound_htlc_failure_update() {
6926         do_test_sweep_outbound_htlc_failure_update(false, true);
6927         do_test_sweep_outbound_htlc_failure_update(false, false);
6928         do_test_sweep_outbound_htlc_failure_update(true, false);
6929 }
6930
6931 #[test]
6932 fn test_user_configurable_csv_delay() {
6933         // We test our channel constructors yield errors when we pass them absurd csv delay
6934
6935         let mut low_our_to_self_config = UserConfig::default();
6936         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6937         let mut high_their_to_self_config = UserConfig::default();
6938         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6939         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6940         let chanmon_cfgs = create_chanmon_cfgs(2);
6941         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6942         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6943         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6944
6945         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6946         if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6947                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6948                 &low_our_to_self_config, 0, 42)
6949         {
6950                 match error {
6951                         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())); },
6952                         _ => panic!("Unexpected event"),
6953                 }
6954         } else { assert!(false) }
6955
6956         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6957         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6958         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6959         open_channel.to_self_delay = 200;
6960         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6961                 &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,
6962                 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6963         {
6964                 match error {
6965                         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()));  },
6966                         _ => panic!("Unexpected event"),
6967                 }
6968         } else { assert!(false); }
6969
6970         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6971         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6972         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()));
6973         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6974         accept_channel.to_self_delay = 200;
6975         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6976         let reason_msg;
6977         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6978                 match action {
6979                         &ErrorAction::SendErrorMessage { ref msg } => {
6980                                 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()));
6981                                 reason_msg = msg.data.clone();
6982                         },
6983                         _ => { panic!(); }
6984                 }
6985         } else { panic!(); }
6986         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6987
6988         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6989         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6990         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6991         open_channel.to_self_delay = 200;
6992         if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6993                 &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,
6994                 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6995         {
6996                 match error {
6997                         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())); },
6998                         _ => panic!("Unexpected event"),
6999                 }
7000         } else { assert!(false); }
7001 }
7002
7003 #[test]
7004 fn test_check_htlc_underpaying() {
7005         // Send payment through A -> B but A is maliciously
7006         // sending a probe payment (i.e less than expected value0
7007         // to B, B should refuse payment.
7008
7009         let chanmon_cfgs = create_chanmon_cfgs(2);
7010         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7011         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7012         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7013
7014         // Create some initial channels
7015         create_announced_chan_between_nodes(&nodes, 0, 1);
7016
7017         let scorer = test_utils::TestScorer::new();
7018         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7019         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();
7020         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();
7021         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7022         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7023         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7024                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7025         check_added_monitors!(nodes[0], 1);
7026
7027         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7028         assert_eq!(events.len(), 1);
7029         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7030         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7031         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7032
7033         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7034         // and then will wait a second random delay before failing the HTLC back:
7035         expect_pending_htlcs_forwardable!(nodes[1]);
7036         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7037
7038         // Node 3 is expecting payment of 100_000 but received 10_000,
7039         // it should fail htlc like we didn't know the preimage.
7040         nodes[1].node.process_pending_htlc_forwards();
7041
7042         let events = nodes[1].node.get_and_clear_pending_msg_events();
7043         assert_eq!(events.len(), 1);
7044         let (update_fail_htlc, commitment_signed) = match events[0] {
7045                 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 } } => {
7046                         assert!(update_add_htlcs.is_empty());
7047                         assert!(update_fulfill_htlcs.is_empty());
7048                         assert_eq!(update_fail_htlcs.len(), 1);
7049                         assert!(update_fail_malformed_htlcs.is_empty());
7050                         assert!(update_fee.is_none());
7051                         (update_fail_htlcs[0].clone(), commitment_signed)
7052                 },
7053                 _ => panic!("Unexpected event"),
7054         };
7055         check_added_monitors!(nodes[1], 1);
7056
7057         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7058         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7059
7060         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7061         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7062         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7063         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7064 }
7065
7066 #[test]
7067 fn test_announce_disable_channels() {
7068         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7069         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7070
7071         let chanmon_cfgs = create_chanmon_cfgs(2);
7072         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7073         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7074         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7075
7076         create_announced_chan_between_nodes(&nodes, 0, 1);
7077         create_announced_chan_between_nodes(&nodes, 1, 0);
7078         create_announced_chan_between_nodes(&nodes, 0, 1);
7079
7080         // Disconnect peers
7081         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7082         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7083
7084         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7085                 nodes[0].node.timer_tick_occurred();
7086         }
7087         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7088         assert_eq!(msg_events.len(), 3);
7089         let mut chans_disabled = HashMap::new();
7090         for e in msg_events {
7091                 match e {
7092                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7093                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7094                                 // Check that each channel gets updated exactly once
7095                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7096                                         panic!("Generated ChannelUpdate for wrong chan!");
7097                                 }
7098                         },
7099                         _ => panic!("Unexpected event"),
7100                 }
7101         }
7102         // Reconnect peers
7103         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
7104         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7105         assert_eq!(reestablish_1.len(), 3);
7106         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
7107         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7108         assert_eq!(reestablish_2.len(), 3);
7109
7110         // Reestablish chan_1
7111         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7112         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7113         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7114         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7115         // Reestablish chan_2
7116         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7117         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7118         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7119         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7120         // Reestablish chan_3
7121         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7122         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7123         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7124         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7125
7126         for _ in 0..ENABLE_GOSSIP_TICKS {
7127                 nodes[0].node.timer_tick_occurred();
7128         }
7129         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7130         nodes[0].node.timer_tick_occurred();
7131         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7132         assert_eq!(msg_events.len(), 3);
7133         for e in msg_events {
7134                 match e {
7135                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7136                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7137                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7138                                         // Each update should have a higher timestamp than the previous one, replacing
7139                                         // the old one.
7140                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7141                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7142                                 }
7143                         },
7144                         _ => panic!("Unexpected event"),
7145                 }
7146         }
7147         // Check that each channel gets updated exactly once
7148         assert!(chans_disabled.is_empty());
7149 }
7150
7151 #[test]
7152 fn test_bump_penalty_txn_on_revoked_commitment() {
7153         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7154         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7155
7156         let chanmon_cfgs = create_chanmon_cfgs(2);
7157         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7158         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7159         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7160
7161         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7162
7163         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7164         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7165                 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7166         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7167         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7168
7169         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7170         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7171         assert_eq!(revoked_txn[0].output.len(), 4);
7172         assert_eq!(revoked_txn[0].input.len(), 1);
7173         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7174         let revoked_txid = revoked_txn[0].txid();
7175
7176         let mut penalty_sum = 0;
7177         for outp in revoked_txn[0].output.iter() {
7178                 if outp.script_pubkey.is_v0_p2wsh() {
7179                         penalty_sum += outp.value;
7180                 }
7181         }
7182
7183         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7184         let header_114 = connect_blocks(&nodes[1], 14);
7185
7186         // Actually revoke tx by claiming a HTLC
7187         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7188         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7189         check_added_monitors!(nodes[1], 1);
7190
7191         // One or more justice tx should have been broadcast, check it
7192         let penalty_1;
7193         let feerate_1;
7194         {
7195                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7196                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7197                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7198                 assert_eq!(node_txn[0].output.len(), 1);
7199                 check_spends!(node_txn[0], revoked_txn[0]);
7200                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7201                 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7202                 penalty_1 = node_txn[0].txid();
7203                 node_txn.clear();
7204         };
7205
7206         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7207         connect_blocks(&nodes[1], 15);
7208         let mut penalty_2 = penalty_1;
7209         let mut feerate_2 = 0;
7210         {
7211                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7212                 assert_eq!(node_txn.len(), 1);
7213                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7214                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7215                         assert_eq!(node_txn[0].output.len(), 1);
7216                         check_spends!(node_txn[0], revoked_txn[0]);
7217                         penalty_2 = node_txn[0].txid();
7218                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7219                         assert_ne!(penalty_2, penalty_1);
7220                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7221                         feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7222                         // Verify 25% bump heuristic
7223                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7224                         node_txn.clear();
7225                 }
7226         }
7227         assert_ne!(feerate_2, 0);
7228
7229         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7230         connect_blocks(&nodes[1], 1);
7231         let penalty_3;
7232         let mut feerate_3 = 0;
7233         {
7234                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7235                 assert_eq!(node_txn.len(), 1);
7236                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7237                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7238                         assert_eq!(node_txn[0].output.len(), 1);
7239                         check_spends!(node_txn[0], revoked_txn[0]);
7240                         penalty_3 = node_txn[0].txid();
7241                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7242                         assert_ne!(penalty_3, penalty_2);
7243                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7244                         feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7245                         // Verify 25% bump heuristic
7246                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7247                         node_txn.clear();
7248                 }
7249         }
7250         assert_ne!(feerate_3, 0);
7251
7252         nodes[1].node.get_and_clear_pending_events();
7253         nodes[1].node.get_and_clear_pending_msg_events();
7254 }
7255
7256 #[test]
7257 fn test_bump_penalty_txn_on_revoked_htlcs() {
7258         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7259         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7260
7261         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7262         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7263         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7264         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7265         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7266
7267         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7268         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7269         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7270         let scorer = test_utils::TestScorer::new();
7271         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7272         let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7273                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7274         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7275         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7276         let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7277                 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7278         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7279
7280         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7281         assert_eq!(revoked_local_txn[0].input.len(), 1);
7282         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7283
7284         // Revoke local commitment tx
7285         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7286
7287         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7288         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7289         check_closed_broadcast!(nodes[1], true);
7290         check_added_monitors!(nodes[1], 1);
7291         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7292         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7293
7294         let revoked_htlc_txn = {
7295                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7296                 assert_eq!(txn.len(), 2);
7297
7298                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7299                 assert_eq!(txn[0].input.len(), 1);
7300                 check_spends!(txn[0], revoked_local_txn[0]);
7301
7302                 assert_eq!(txn[1].input.len(), 1);
7303                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7304                 assert_eq!(txn[1].output.len(), 1);
7305                 check_spends!(txn[1], revoked_local_txn[0]);
7306
7307                 txn
7308         };
7309
7310         // Broadcast set of revoked txn on A
7311         let hash_128 = connect_blocks(&nodes[0], 40);
7312         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7313         connect_block(&nodes[0], &block_11);
7314         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7315         connect_block(&nodes[0], &block_129);
7316         let events = nodes[0].node.get_and_clear_pending_events();
7317         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7318         match events.last().unwrap() {
7319                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7320                 _ => panic!("Unexpected event"),
7321         }
7322         let first;
7323         let feerate_1;
7324         let penalty_txn;
7325         {
7326                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7327                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7328                 // Verify claim tx are spending revoked HTLC txn
7329
7330                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7331                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7332                 // which are included in the same block (they are broadcasted because we scan the
7333                 // transactions linearly and generate claims as we go, they likely should be removed in the
7334                 // future).
7335                 assert_eq!(node_txn[0].input.len(), 1);
7336                 check_spends!(node_txn[0], revoked_local_txn[0]);
7337                 assert_eq!(node_txn[1].input.len(), 1);
7338                 check_spends!(node_txn[1], revoked_local_txn[0]);
7339                 assert_eq!(node_txn[2].input.len(), 1);
7340                 check_spends!(node_txn[2], revoked_local_txn[0]);
7341
7342                 // Each of the three justice transactions claim a separate (single) output of the three
7343                 // available, which we check here:
7344                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7345                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7346                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7347
7348                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7349                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7350
7351                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7352                 // output, checked above).
7353                 assert_eq!(node_txn[3].input.len(), 2);
7354                 assert_eq!(node_txn[3].output.len(), 1);
7355                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7356
7357                 first = node_txn[3].txid();
7358                 // Store both feerates for later comparison
7359                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7360                 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7361                 penalty_txn = vec![node_txn[2].clone()];
7362                 node_txn.clear();
7363         }
7364
7365         // Connect one more block to see if bumped penalty are issued for HTLC txn
7366         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7367         connect_block(&nodes[0], &block_130);
7368         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7369         connect_block(&nodes[0], &block_131);
7370
7371         // Few more blocks to confirm penalty txn
7372         connect_blocks(&nodes[0], 4);
7373         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7374         let header_144 = connect_blocks(&nodes[0], 9);
7375         let node_txn = {
7376                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7377                 assert_eq!(node_txn.len(), 1);
7378
7379                 assert_eq!(node_txn[0].input.len(), 2);
7380                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7381                 // Verify bumped tx is different and 25% bump heuristic
7382                 assert_ne!(first, node_txn[0].txid());
7383                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7384                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7385                 assert!(feerate_2 * 100 > feerate_1 * 125);
7386                 let txn = vec![node_txn[0].clone()];
7387                 node_txn.clear();
7388                 txn
7389         };
7390         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7391         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7392         connect_blocks(&nodes[0], 20);
7393         {
7394                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7395                 // We verify than no new transaction has been broadcast because previously
7396                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7397                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7398                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7399                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7400                 // up bumped justice generation.
7401                 assert_eq!(node_txn.len(), 0);
7402                 node_txn.clear();
7403         }
7404         check_closed_broadcast!(nodes[0], true);
7405         check_added_monitors!(nodes[0], 1);
7406 }
7407
7408 #[test]
7409 fn test_bump_penalty_txn_on_remote_commitment() {
7410         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7411         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7412
7413         // Create 2 HTLCs
7414         // Provide preimage for one
7415         // Check aggregation
7416
7417         let chanmon_cfgs = create_chanmon_cfgs(2);
7418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7420         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7421
7422         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7423         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7424         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7425
7426         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7427         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7428         assert_eq!(remote_txn[0].output.len(), 4);
7429         assert_eq!(remote_txn[0].input.len(), 1);
7430         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7431
7432         // Claim a HTLC without revocation (provide B monitor with preimage)
7433         nodes[1].node.claim_funds(payment_preimage);
7434         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7435         mine_transaction(&nodes[1], &remote_txn[0]);
7436         check_added_monitors!(nodes[1], 2);
7437         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7438
7439         // One or more claim tx should have been broadcast, check it
7440         let timeout;
7441         let preimage;
7442         let preimage_bump;
7443         let feerate_timeout;
7444         let feerate_preimage;
7445         {
7446                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7447                 // 3 transactions including:
7448                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7449                 assert_eq!(node_txn.len(), 3);
7450                 assert_eq!(node_txn[0].input.len(), 1);
7451                 assert_eq!(node_txn[1].input.len(), 1);
7452                 assert_eq!(node_txn[2].input.len(), 1);
7453                 check_spends!(node_txn[0], remote_txn[0]);
7454                 check_spends!(node_txn[1], remote_txn[0]);
7455                 check_spends!(node_txn[2], remote_txn[0]);
7456
7457                 preimage = node_txn[0].txid();
7458                 let index = node_txn[0].input[0].previous_output.vout;
7459                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7460                 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7461
7462                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7463                         (node_txn[2].clone(), node_txn[1].clone())
7464                 } else {
7465                         (node_txn[1].clone(), node_txn[2].clone())
7466                 };
7467
7468                 preimage_bump = preimage_bump_tx;
7469                 check_spends!(preimage_bump, remote_txn[0]);
7470                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7471
7472                 timeout = timeout_tx.txid();
7473                 let index = timeout_tx.input[0].previous_output.vout;
7474                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7475                 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7476
7477                 node_txn.clear();
7478         };
7479         assert_ne!(feerate_timeout, 0);
7480         assert_ne!(feerate_preimage, 0);
7481
7482         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7483         connect_blocks(&nodes[1], 1);
7484         {
7485                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7486                 assert_eq!(node_txn.len(), 1);
7487                 assert_eq!(node_txn[0].input.len(), 1);
7488                 assert_eq!(preimage_bump.input.len(), 1);
7489                 check_spends!(node_txn[0], remote_txn[0]);
7490                 check_spends!(preimage_bump, remote_txn[0]);
7491
7492                 let index = preimage_bump.input[0].previous_output.vout;
7493                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7494                 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7495                 assert!(new_feerate * 100 > feerate_timeout * 125);
7496                 assert_ne!(timeout, preimage_bump.txid());
7497
7498                 let index = node_txn[0].input[0].previous_output.vout;
7499                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7500                 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7501                 assert!(new_feerate * 100 > feerate_preimage * 125);
7502                 assert_ne!(preimage, node_txn[0].txid());
7503
7504                 node_txn.clear();
7505         }
7506
7507         nodes[1].node.get_and_clear_pending_events();
7508         nodes[1].node.get_and_clear_pending_msg_events();
7509 }
7510
7511 #[test]
7512 fn test_counterparty_raa_skip_no_crash() {
7513         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7514         // commitment transaction, we would have happily carried on and provided them the next
7515         // commitment transaction based on one RAA forward. This would probably eventually have led to
7516         // channel closure, but it would not have resulted in funds loss. Still, our
7517         // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7518         // check simply that the channel is closed in response to such an RAA, but don't check whether
7519         // we decide to punish our counterparty for revoking their funds (as we don't currently
7520         // implement that).
7521         let chanmon_cfgs = create_chanmon_cfgs(2);
7522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7525         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7526
7527         let per_commitment_secret;
7528         let next_per_commitment_point;
7529         {
7530                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7531                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7532                 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7533
7534                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7535
7536                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7537                 keys.get_enforcement_state().last_holder_commitment -= 1;
7538                 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7539
7540                 // Must revoke without gaps
7541                 keys.get_enforcement_state().last_holder_commitment -= 1;
7542                 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7543
7544                 keys.get_enforcement_state().last_holder_commitment -= 1;
7545                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7546                         &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7547         }
7548
7549         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7550                 &msgs::RevokeAndACK {
7551                         channel_id,
7552                         per_commitment_secret,
7553                         next_per_commitment_point,
7554                         #[cfg(taproot)]
7555                         next_local_nonce: None,
7556                 });
7557         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7558         check_added_monitors!(nodes[1], 1);
7559         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7560 }
7561
7562 #[test]
7563 fn test_bump_txn_sanitize_tracking_maps() {
7564         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7565         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7566
7567         let chanmon_cfgs = create_chanmon_cfgs(2);
7568         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7569         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7570         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7571
7572         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7573         // Lock HTLC in both directions
7574         let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7575         let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7576
7577         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7578         assert_eq!(revoked_local_txn[0].input.len(), 1);
7579         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7580
7581         // Revoke local commitment tx
7582         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7583
7584         // Broadcast set of revoked txn on A
7585         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7586         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7587         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7588
7589         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7590         check_closed_broadcast!(nodes[0], true);
7591         check_added_monitors!(nodes[0], 1);
7592         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7593         let penalty_txn = {
7594                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7595                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7596                 check_spends!(node_txn[0], revoked_local_txn[0]);
7597                 check_spends!(node_txn[1], revoked_local_txn[0]);
7598                 check_spends!(node_txn[2], revoked_local_txn[0]);
7599                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7600                 node_txn.clear();
7601                 penalty_txn
7602         };
7603         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7604         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7605         {
7606                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7607                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7608                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7609         }
7610 }
7611
7612 #[test]
7613 fn test_channel_conf_timeout() {
7614         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7615         // confirm within 2016 blocks, as recommended by BOLT 2.
7616         let chanmon_cfgs = create_chanmon_cfgs(2);
7617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7619         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7620
7621         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7622
7623         // The outbound node should wait forever for confirmation:
7624         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7625         // copied here instead of directly referencing the constant.
7626         connect_blocks(&nodes[0], 2016);
7627         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7628
7629         // The inbound node should fail the channel after exactly 2016 blocks
7630         connect_blocks(&nodes[1], 2015);
7631         check_added_monitors!(nodes[1], 0);
7632         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7633
7634         connect_blocks(&nodes[1], 1);
7635         check_added_monitors!(nodes[1], 1);
7636         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7637         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7638         assert_eq!(close_ev.len(), 1);
7639         match close_ev[0] {
7640                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7641                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7642                         assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7643                 },
7644                 _ => panic!("Unexpected event"),
7645         }
7646 }
7647
7648 #[test]
7649 fn test_override_channel_config() {
7650         let chanmon_cfgs = create_chanmon_cfgs(2);
7651         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7652         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7653         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7654
7655         // Node0 initiates a channel to node1 using the override config.
7656         let mut override_config = UserConfig::default();
7657         override_config.channel_handshake_config.our_to_self_delay = 200;
7658
7659         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7660
7661         // Assert the channel created by node0 is using the override config.
7662         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7663         assert_eq!(res.channel_flags, 0);
7664         assert_eq!(res.to_self_delay, 200);
7665 }
7666
7667 #[test]
7668 fn test_override_0msat_htlc_minimum() {
7669         let mut zero_config = UserConfig::default();
7670         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7671         let chanmon_cfgs = create_chanmon_cfgs(2);
7672         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7673         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7674         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7675
7676         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7677         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7678         assert_eq!(res.htlc_minimum_msat, 1);
7679
7680         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7681         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7682         assert_eq!(res.htlc_minimum_msat, 1);
7683 }
7684
7685 #[test]
7686 fn test_channel_update_has_correct_htlc_maximum_msat() {
7687         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7688         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7689         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7690         // 90% of the `channel_value`.
7691         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7692
7693         let mut config_30_percent = UserConfig::default();
7694         config_30_percent.channel_handshake_config.announced_channel = true;
7695         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7696         let mut config_50_percent = UserConfig::default();
7697         config_50_percent.channel_handshake_config.announced_channel = true;
7698         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7699         let mut config_95_percent = UserConfig::default();
7700         config_95_percent.channel_handshake_config.announced_channel = true;
7701         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7702         let mut config_100_percent = UserConfig::default();
7703         config_100_percent.channel_handshake_config.announced_channel = true;
7704         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7705
7706         let chanmon_cfgs = create_chanmon_cfgs(4);
7707         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7708         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)]);
7709         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7710
7711         let channel_value_satoshis = 100000;
7712         let channel_value_msat = channel_value_satoshis * 1000;
7713         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7714         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7715         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7716
7717         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7718         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7719
7720         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7721         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7722         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7723         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7724         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7725         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7726
7727         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7728         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7729         // `channel_value`.
7730         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7731         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7732         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7733         // `channel_value`.
7734         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7735 }
7736
7737 #[test]
7738 fn test_manually_accept_inbound_channel_request() {
7739         let mut manually_accept_conf = UserConfig::default();
7740         manually_accept_conf.manually_accept_inbound_channels = true;
7741         let chanmon_cfgs = create_chanmon_cfgs(2);
7742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745
7746         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7747         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7748
7749         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7750
7751         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7752         // accepting the inbound channel request.
7753         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7754
7755         let events = nodes[1].node.get_and_clear_pending_events();
7756         match events[0] {
7757                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7758                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7759                 }
7760                 _ => panic!("Unexpected event"),
7761         }
7762
7763         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7764         assert_eq!(accept_msg_ev.len(), 1);
7765
7766         match accept_msg_ev[0] {
7767                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7768                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7769                 }
7770                 _ => panic!("Unexpected event"),
7771         }
7772
7773         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7774
7775         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7776         assert_eq!(close_msg_ev.len(), 1);
7777
7778         let events = nodes[1].node.get_and_clear_pending_events();
7779         match events[0] {
7780                 Event::ChannelClosed { user_channel_id, .. } => {
7781                         assert_eq!(user_channel_id, 23);
7782                 }
7783                 _ => panic!("Unexpected event"),
7784         }
7785 }
7786
7787 #[test]
7788 fn test_manually_reject_inbound_channel_request() {
7789         let mut manually_accept_conf = UserConfig::default();
7790         manually_accept_conf.manually_accept_inbound_channels = true;
7791         let chanmon_cfgs = create_chanmon_cfgs(2);
7792         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7793         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7794         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7795
7796         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7797         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7798
7799         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7800
7801         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7802         // rejecting the inbound channel request.
7803         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7804
7805         let events = nodes[1].node.get_and_clear_pending_events();
7806         match events[0] {
7807                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7808                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7809                 }
7810                 _ => panic!("Unexpected event"),
7811         }
7812
7813         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7814         assert_eq!(close_msg_ev.len(), 1);
7815
7816         match close_msg_ev[0] {
7817                 MessageSendEvent::HandleError { ref node_id, .. } => {
7818                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7819                 }
7820                 _ => panic!("Unexpected event"),
7821         }
7822         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7823 }
7824
7825 #[test]
7826 fn test_reject_funding_before_inbound_channel_accepted() {
7827         // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7828         // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7829         // the node operator before the counterparty sends a `FundingCreated` message. If a
7830         // `FundingCreated` message is received before the channel is accepted, it should be rejected
7831         // and the channel should be closed.
7832         let mut manually_accept_conf = UserConfig::default();
7833         manually_accept_conf.manually_accept_inbound_channels = true;
7834         let chanmon_cfgs = create_chanmon_cfgs(2);
7835         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7836         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7837         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7838
7839         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7840         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7841         let temp_channel_id = res.temporary_channel_id;
7842
7843         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7844
7845         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7846         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7847
7848         // Clear the `Event::OpenChannelRequest` event without responding to the request.
7849         nodes[1].node.get_and_clear_pending_events();
7850
7851         // Get the `AcceptChannel` message of `nodes[1]` without calling
7852         // `ChannelManager::accept_inbound_channel`, which generates a
7853         // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7854         // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7855         // succeed when `nodes[0]` is passed to it.
7856         let accept_chan_msg = {
7857                 let mut node_1_per_peer_lock;
7858                 let mut node_1_peer_state_lock;
7859                 let channel =  get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7860                 channel.get_accept_channel_message()
7861         };
7862         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7863
7864         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7865
7866         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7867         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7868
7869         // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7870         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
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         let expected_err = "FundingCreated message received before the channel was accepted";
7876         match close_msg_ev[0] {
7877                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7878                         assert_eq!(msg.channel_id, temp_channel_id);
7879                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7880                         assert_eq!(msg.data, expected_err);
7881                 }
7882                 _ => panic!("Unexpected event"),
7883         }
7884
7885         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7886 }
7887
7888 #[test]
7889 fn test_can_not_accept_inbound_channel_twice() {
7890         let mut manually_accept_conf = UserConfig::default();
7891         manually_accept_conf.manually_accept_inbound_channels = true;
7892         let chanmon_cfgs = create_chanmon_cfgs(2);
7893         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7894         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7895         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7896
7897         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7898         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7899
7900         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7901
7902         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7903         // accepting the inbound channel request.
7904         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7905
7906         let events = nodes[1].node.get_and_clear_pending_events();
7907         match events[0] {
7908                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7909                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7910                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7911                         match api_res {
7912                                 Err(APIError::APIMisuseError { err }) => {
7913                                         assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7914                                 },
7915                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7916                                 Err(_) => panic!("Unexpected Error"),
7917                         }
7918                 }
7919                 _ => panic!("Unexpected event"),
7920         }
7921
7922         // Ensure that the channel wasn't closed after attempting to accept it twice.
7923         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7924         assert_eq!(accept_msg_ev.len(), 1);
7925
7926         match accept_msg_ev[0] {
7927                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7928                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7929                 }
7930                 _ => panic!("Unexpected event"),
7931         }
7932 }
7933
7934 #[test]
7935 fn test_can_not_accept_unknown_inbound_channel() {
7936         let chanmon_cfg = create_chanmon_cfgs(2);
7937         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7938         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7939         let nodes = create_network(2, &node_cfg, &node_chanmgr);
7940
7941         let unknown_channel_id = [0; 32];
7942         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7943         match api_res {
7944                 Err(APIError::ChannelUnavailable { err }) => {
7945                         assert_eq!(err, format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(unknown_channel_id), nodes[1].node.get_our_node_id()));
7946                 },
7947                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7948                 Err(_) => panic!("Unexpected Error"),
7949         }
7950 }
7951
7952 #[test]
7953 fn test_onion_value_mpp_set_calculation() {
7954         // Test that we use the onion value `amt_to_forward` when
7955         // calculating whether we've reached the `total_msat` of an MPP
7956         // by having a routing node forward more than `amt_to_forward`
7957         // and checking that the receiving node doesn't generate
7958         // a PaymentClaimable event too early
7959         let node_count = 4;
7960         let chanmon_cfgs = create_chanmon_cfgs(node_count);
7961         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7962         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7963         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7964
7965         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7966         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7967         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7968         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7969
7970         let total_msat = 100_000;
7971         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7972         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7973         let sample_path = route.paths.pop().unwrap();
7974
7975         let mut path_1 = sample_path.clone();
7976         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7977         path_1.hops[0].short_channel_id = chan_1_id;
7978         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7979         path_1.hops[1].short_channel_id = chan_3_id;
7980         path_1.hops[1].fee_msat = 100_000;
7981         route.paths.push(path_1);
7982
7983         let mut path_2 = sample_path.clone();
7984         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
7985         path_2.hops[0].short_channel_id = chan_2_id;
7986         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
7987         path_2.hops[1].short_channel_id = chan_4_id;
7988         path_2.hops[1].fee_msat = 1_000;
7989         route.paths.push(path_2);
7990
7991         // Send payment
7992         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7993         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
7994                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
7995         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
7996                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
7997         check_added_monitors!(nodes[0], expected_paths.len());
7998
7999         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8000         assert_eq!(events.len(), expected_paths.len());
8001
8002         // First path
8003         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8004         let mut payment_event = SendEvent::from_event(ev);
8005         let mut prev_node = &nodes[0];
8006
8007         for (idx, &node) in expected_paths[0].iter().enumerate() {
8008                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8009
8010                 if idx == 0 { // routing node
8011                         let session_priv = [3; 32];
8012                         let height = nodes[0].best_block_info().1;
8013                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8014                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8015                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8016                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8017                         // Edit amt_to_forward to simulate the sender having set
8018                         // the final amount and the routing node taking less fee
8019                         onion_payloads[1].amt_to_forward = 99_000;
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 #[allow(deprecated)]
8189 fn test_secret_timeout() {
8190         // Simple test of payment secret storage time outs. After
8191         // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8192         let chanmon_cfgs = create_chanmon_cfgs(2);
8193         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8194         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8195         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8196
8197         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8198
8199         let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8200
8201         // We should fail to register the same payment hash twice, at least until we've connected a
8202         // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8203         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8204                 assert_eq!(err, "Duplicate payment hash");
8205         } else { panic!(); }
8206         let mut block = {
8207                 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8208                 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8209         };
8210         connect_block(&nodes[1], &block);
8211         if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8212                 assert_eq!(err, "Duplicate payment hash");
8213         } else { panic!(); }
8214
8215         // If we then connect the second block, we should be able to register the same payment hash
8216         // again (this time getting a new payment secret).
8217         block.header.prev_blockhash = block.header.block_hash();
8218         block.header.time += 1;
8219         connect_block(&nodes[1], &block);
8220         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8221         assert_ne!(payment_secret_1, our_payment_secret);
8222
8223         {
8224                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8225                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8226                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8227                 check_added_monitors!(nodes[0], 1);
8228                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8229                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8230                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8231                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8232         }
8233         // Note that after leaving the above scope we have no knowledge of any arguments or return
8234         // values from previous calls.
8235         expect_pending_htlcs_forwardable!(nodes[1]);
8236         let events = nodes[1].node.get_and_clear_pending_events();
8237         assert_eq!(events.len(), 1);
8238         match events[0] {
8239                 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8240                         assert!(payment_preimage.is_none());
8241                         assert_eq!(payment_secret, our_payment_secret);
8242                         // We don't actually have the payment preimage with which to claim this payment!
8243                 },
8244                 _ => panic!("Unexpected event"),
8245         }
8246 }
8247
8248 #[test]
8249 fn test_bad_secret_hash() {
8250         // Simple test of unregistered payment hash/invalid payment secret handling
8251         let chanmon_cfgs = create_chanmon_cfgs(2);
8252         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8253         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8254         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8255
8256         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8257
8258         let random_payment_hash = PaymentHash([42; 32]);
8259         let random_payment_secret = PaymentSecret([43; 32]);
8260         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8261         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8262
8263         // All the below cases should end up being handled exactly identically, so we macro the
8264         // resulting events.
8265         macro_rules! handle_unknown_invalid_payment_data {
8266                 ($payment_hash: expr) => {
8267                         check_added_monitors!(nodes[0], 1);
8268                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8269                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8270                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8271                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8272
8273                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8274                         // again to process the pending backwards-failure of the HTLC
8275                         expect_pending_htlcs_forwardable!(nodes[1]);
8276                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8277                         check_added_monitors!(nodes[1], 1);
8278
8279                         // We should fail the payment back
8280                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8281                         match events.pop().unwrap() {
8282                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8283                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8284                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8285                                 },
8286                                 _ => panic!("Unexpected event"),
8287                         }
8288                 }
8289         }
8290
8291         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8292         // Error data is the HTLC value (100,000) and current block height
8293         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8294
8295         // Send a payment with the right payment hash but the wrong payment secret
8296         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8297                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8298         handle_unknown_invalid_payment_data!(our_payment_hash);
8299         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8300
8301         // Send a payment with a random payment hash, but the right payment secret
8302         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8303                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8304         handle_unknown_invalid_payment_data!(random_payment_hash);
8305         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8306
8307         // Send a payment with a random payment hash and random payment secret
8308         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8309                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8310         handle_unknown_invalid_payment_data!(random_payment_hash);
8311         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8312 }
8313
8314 #[test]
8315 fn test_update_err_monitor_lockdown() {
8316         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8317         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8318         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8319         // error.
8320         //
8321         // This scenario may happen in a watchtower setup, where watchtower process a block height
8322         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8323         // commitment at same time.
8324
8325         let chanmon_cfgs = create_chanmon_cfgs(2);
8326         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8327         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8328         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8329
8330         // Create some initial channel
8331         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8332         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8333
8334         // Rebalance the network to generate htlc in the two directions
8335         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8336
8337         // Route a HTLC from node 0 to node 1 (but don't settle)
8338         let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8339
8340         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8341         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8342         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8343         let persister = test_utils::TestPersister::new();
8344         let watchtower = {
8345                 let new_monitor = {
8346                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8347                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8348                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8349                         assert!(new_monitor == *monitor);
8350                         new_monitor
8351                 };
8352                 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);
8353                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8354                 watchtower
8355         };
8356         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8357         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8358         // transaction lock time requirements here.
8359         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8360         watchtower.chain_monitor.block_connected(&block, 200);
8361
8362         // Try to update ChannelMonitor
8363         nodes[1].node.claim_funds(preimage);
8364         check_added_monitors!(nodes[1], 1);
8365         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8366
8367         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8368         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8369         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8370         {
8371                 let mut node_0_per_peer_lock;
8372                 let mut node_0_peer_state_lock;
8373                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8374                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8375                         assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8376                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8377                 } else { assert!(false); }
8378         }
8379         // Our local monitor is in-sync and hasn't processed yet timeout
8380         check_added_monitors!(nodes[0], 1);
8381         let events = nodes[0].node.get_and_clear_pending_events();
8382         assert_eq!(events.len(), 1);
8383 }
8384
8385 #[test]
8386 fn test_concurrent_monitor_claim() {
8387         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8388         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8389         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8390         // state N+1 confirms. Alice claims output from state N+1.
8391
8392         let chanmon_cfgs = create_chanmon_cfgs(2);
8393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8395         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8396
8397         // Create some initial channel
8398         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8399         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8400
8401         // Rebalance the network to generate htlc in the two directions
8402         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8403
8404         // Route a HTLC from node 0 to node 1 (but don't settle)
8405         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8406
8407         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8408         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8409         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8410         let persister = test_utils::TestPersister::new();
8411         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8412                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8413         );
8414         let watchtower_alice = {
8415                 let new_monitor = {
8416                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8417                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8418                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8419                         assert!(new_monitor == *monitor);
8420                         new_monitor
8421                 };
8422                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8423                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8424                 watchtower
8425         };
8426         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8427         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8428         // requirements here.
8429         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8430         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8431         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8432
8433         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8434         let alice_state = {
8435                 let mut txn = alice_broadcaster.txn_broadcast();
8436                 assert_eq!(txn.len(), 2);
8437                 txn.remove(0)
8438         };
8439
8440         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8441         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8442         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8443         let persister = test_utils::TestPersister::new();
8444         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8445         let watchtower_bob = {
8446                 let new_monitor = {
8447                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8448                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8449                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8450                         assert!(new_monitor == *monitor);
8451                         new_monitor
8452                 };
8453                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8454                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8455                 watchtower
8456         };
8457         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8458
8459         // Route another payment to generate another update with still previous HTLC pending
8460         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8461         nodes[1].node.send_payment_with_route(&route, payment_hash,
8462                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8463         check_added_monitors!(nodes[1], 1);
8464
8465         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8466         assert_eq!(updates.update_add_htlcs.len(), 1);
8467         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8468         {
8469                 let mut node_0_per_peer_lock;
8470                 let mut node_0_peer_state_lock;
8471                 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8472                 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8473                         // Watchtower Alice should already have seen the block and reject the update
8474                         assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8475                         assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8476                         assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8477                 } else { assert!(false); }
8478         }
8479         // Our local monitor is in-sync and hasn't processed yet timeout
8480         check_added_monitors!(nodes[0], 1);
8481
8482         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8483         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8484
8485         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8486         let bob_state_y;
8487         {
8488                 let mut txn = bob_broadcaster.txn_broadcast();
8489                 assert_eq!(txn.len(), 2);
8490                 bob_state_y = txn.remove(0);
8491         };
8492
8493         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8494         let height = HTLC_TIMEOUT_BROADCAST + 1;
8495         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8496         check_closed_broadcast(&nodes[0], 1, true);
8497         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8498         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8499         check_added_monitors(&nodes[0], 1);
8500         {
8501                 let htlc_txn = alice_broadcaster.txn_broadcast();
8502                 assert_eq!(htlc_txn.len(), 2);
8503                 check_spends!(htlc_txn[0], bob_state_y);
8504                 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8505                 // it. However, she should, because it now has an invalid parent.
8506                 check_spends!(htlc_txn[1], alice_state);
8507         }
8508 }
8509
8510 #[test]
8511 fn test_pre_lockin_no_chan_closed_update() {
8512         // Test that if a peer closes a channel in response to a funding_created message we don't
8513         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8514         // message).
8515         //
8516         // Doing so would imply a channel monitor update before the initial channel monitor
8517         // registration, violating our API guarantees.
8518         //
8519         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8520         // then opening a second channel with the same funding output as the first (which is not
8521         // rejected because the first channel does not exist in the ChannelManager) and closing it
8522         // before receiving funding_signed.
8523         let chanmon_cfgs = create_chanmon_cfgs(2);
8524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8527
8528         // Create an initial channel
8529         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8530         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8531         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8532         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8533         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8534
8535         // Move the first channel through the funding flow...
8536         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8537
8538         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8539         check_added_monitors!(nodes[0], 0);
8540
8541         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8542         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8543         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8544         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8545         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8546 }
8547
8548 #[test]
8549 fn test_htlc_no_detection() {
8550         // This test is a mutation to underscore the detection logic bug we had
8551         // before #653. HTLC value routed is above the remaining balance, thus
8552         // inverting HTLC and `to_remote` output. HTLC will come second and
8553         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8554         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8555         // outputs order detection for correct spending children filtring.
8556
8557         let chanmon_cfgs = create_chanmon_cfgs(2);
8558         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8559         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8560         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8561
8562         // Create some initial channels
8563         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8564
8565         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8566         let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8567         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8568         assert_eq!(local_txn[0].input.len(), 1);
8569         assert_eq!(local_txn[0].output.len(), 3);
8570         check_spends!(local_txn[0], chan_1.3);
8571
8572         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8573         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8574         connect_block(&nodes[0], &block);
8575         // We deliberately connect the local tx twice as this should provoke a failure calling
8576         // this test before #653 fix.
8577         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8578         check_closed_broadcast!(nodes[0], true);
8579         check_added_monitors!(nodes[0], 1);
8580         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8581         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8582
8583         let htlc_timeout = {
8584                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8585                 assert_eq!(node_txn.len(), 1);
8586                 assert_eq!(node_txn[0].input.len(), 1);
8587                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8588                 check_spends!(node_txn[0], local_txn[0]);
8589                 node_txn[0].clone()
8590         };
8591
8592         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8593         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8594         expect_payment_failed!(nodes[0], our_payment_hash, false);
8595 }
8596
8597 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8598         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8599         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8600         // Carol, Alice would be the upstream node, and Carol the downstream.)
8601         //
8602         // Steps of the test:
8603         // 1) Alice sends a HTLC to Carol through Bob.
8604         // 2) Carol doesn't settle the HTLC.
8605         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8606         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8607         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8608         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8609         // 5) Carol release the preimage to Bob off-chain.
8610         // 6) Bob claims the offered output on the broadcasted commitment.
8611         let chanmon_cfgs = create_chanmon_cfgs(3);
8612         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8613         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8614         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8615
8616         // Create some initial channels
8617         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8618         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8619
8620         // Steps (1) and (2):
8621         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8622         let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8623
8624         // Check that Alice's commitment transaction now contains an output for this HTLC.
8625         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8626         check_spends!(alice_txn[0], chan_ab.3);
8627         assert_eq!(alice_txn[0].output.len(), 2);
8628         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8629         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8630         assert_eq!(alice_txn.len(), 2);
8631
8632         // Steps (3) and (4):
8633         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8634         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8635         let mut force_closing_node = 0; // Alice force-closes
8636         let mut counterparty_node = 1; // Bob if Alice force-closes
8637
8638         // Bob force-closes
8639         if !broadcast_alice {
8640                 force_closing_node = 1;
8641                 counterparty_node = 0;
8642         }
8643         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8644         check_closed_broadcast!(nodes[force_closing_node], true);
8645         check_added_monitors!(nodes[force_closing_node], 1);
8646         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8647         if go_onchain_before_fulfill {
8648                 let txn_to_broadcast = match broadcast_alice {
8649                         true => alice_txn.clone(),
8650                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8651                 };
8652                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8653                 if broadcast_alice {
8654                         check_closed_broadcast!(nodes[1], true);
8655                         check_added_monitors!(nodes[1], 1);
8656                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8657                 }
8658         }
8659
8660         // Step (5):
8661         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8662         // process of removing the HTLC from their commitment transactions.
8663         nodes[2].node.claim_funds(payment_preimage);
8664         check_added_monitors!(nodes[2], 1);
8665         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8666
8667         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8668         assert!(carol_updates.update_add_htlcs.is_empty());
8669         assert!(carol_updates.update_fail_htlcs.is_empty());
8670         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8671         assert!(carol_updates.update_fee.is_none());
8672         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8673
8674         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8675         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8676         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8677         if !go_onchain_before_fulfill && broadcast_alice {
8678                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8679                 assert_eq!(events.len(), 1);
8680                 match events[0] {
8681                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8682                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8683                         },
8684                         _ => panic!("Unexpected event"),
8685                 };
8686         }
8687         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8688         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8689         // Carol<->Bob's updated commitment transaction info.
8690         check_added_monitors!(nodes[1], 2);
8691
8692         let events = nodes[1].node.get_and_clear_pending_msg_events();
8693         assert_eq!(events.len(), 2);
8694         let bob_revocation = match events[0] {
8695                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8696                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8697                         (*msg).clone()
8698                 },
8699                 _ => panic!("Unexpected event"),
8700         };
8701         let bob_updates = match events[1] {
8702                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8703                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8704                         (*updates).clone()
8705                 },
8706                 _ => panic!("Unexpected event"),
8707         };
8708
8709         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8710         check_added_monitors!(nodes[2], 1);
8711         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8712         check_added_monitors!(nodes[2], 1);
8713
8714         let events = nodes[2].node.get_and_clear_pending_msg_events();
8715         assert_eq!(events.len(), 1);
8716         let carol_revocation = match events[0] {
8717                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8718                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8719                         (*msg).clone()
8720                 },
8721                 _ => panic!("Unexpected event"),
8722         };
8723         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8724         check_added_monitors!(nodes[1], 1);
8725
8726         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8727         // here's where we put said channel's commitment tx on-chain.
8728         let mut txn_to_broadcast = alice_txn.clone();
8729         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8730         if !go_onchain_before_fulfill {
8731                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8732                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8733                 if broadcast_alice {
8734                         check_closed_broadcast!(nodes[1], true);
8735                         check_added_monitors!(nodes[1], 1);
8736                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8737                 }
8738                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8739                 if broadcast_alice {
8740                         assert_eq!(bob_txn.len(), 1);
8741                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8742                 } else {
8743                         assert_eq!(bob_txn.len(), 2);
8744                         check_spends!(bob_txn[0], chan_ab.3);
8745                 }
8746         }
8747
8748         // Step (6):
8749         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8750         // broadcasted commitment transaction.
8751         {
8752                 let script_weight = match broadcast_alice {
8753                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8754                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8755                 };
8756                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8757                 // Bob force-closed and broadcasts the commitment transaction along with a
8758                 // HTLC-output-claiming transaction.
8759                 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8760                 if broadcast_alice {
8761                         assert_eq!(bob_txn.len(), 1);
8762                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8763                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8764                 } else {
8765                         assert_eq!(bob_txn.len(), 2);
8766                         check_spends!(bob_txn[1], txn_to_broadcast[0]);
8767                         assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8768                 }
8769         }
8770 }
8771
8772 #[test]
8773 fn test_onchain_htlc_settlement_after_close() {
8774         do_test_onchain_htlc_settlement_after_close(true, true);
8775         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8776         do_test_onchain_htlc_settlement_after_close(true, false);
8777         do_test_onchain_htlc_settlement_after_close(false, false);
8778 }
8779
8780 #[test]
8781 fn test_duplicate_temporary_channel_id_from_different_peers() {
8782         // Tests that we can accept two different `OpenChannel` requests with the same
8783         // `temporary_channel_id`, as long as they are from different peers.
8784         let chanmon_cfgs = create_chanmon_cfgs(3);
8785         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8786         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8787         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8788
8789         // Create an first channel channel
8790         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8791         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8792
8793         // Create an second channel
8794         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8795         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8796
8797         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8798         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8799         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8800
8801         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8802         // `temporary_channel_id` as they are from different peers.
8803         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8804         {
8805                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8806                 assert_eq!(events.len(), 1);
8807                 match &events[0] {
8808                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8809                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8810                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8811                         },
8812                         _ => panic!("Unexpected event"),
8813                 }
8814         }
8815
8816         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8817         {
8818                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8819                 assert_eq!(events.len(), 1);
8820                 match &events[0] {
8821                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8822                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8823                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8824                         },
8825                         _ => panic!("Unexpected event"),
8826                 }
8827         }
8828 }
8829
8830 #[test]
8831 fn test_duplicate_chan_id() {
8832         // Test that if a given peer tries to open a channel with the same channel_id as one that is
8833         // already open we reject it and keep the old channel.
8834         //
8835         // Previously, full_stack_target managed to figure out that if you tried to open two channels
8836         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8837         // the existing channel when we detect the duplicate new channel, screwing up our monitor
8838         // updating logic for the existing channel.
8839         let chanmon_cfgs = create_chanmon_cfgs(2);
8840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8842         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8843
8844         // Create an initial channel
8845         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8846         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8847         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8848         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()));
8849
8850         // Try to create a second channel with the same temporary_channel_id as the first and check
8851         // that it is rejected.
8852         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8853         {
8854                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8855                 assert_eq!(events.len(), 1);
8856                 match events[0] {
8857                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8858                                 // Technically, at this point, nodes[1] would be justified in thinking both the
8859                                 // first (valid) and second (invalid) channels are closed, given they both have
8860                                 // the same non-temporary channel_id. However, currently we do not, so we just
8861                                 // move forward with it.
8862                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8863                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8864                         },
8865                         _ => panic!("Unexpected event"),
8866                 }
8867         }
8868
8869         // Move the first channel through the funding flow...
8870         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8871
8872         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8873         check_added_monitors!(nodes[0], 0);
8874
8875         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8876         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8877         {
8878                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8879                 assert_eq!(added_monitors.len(), 1);
8880                 assert_eq!(added_monitors[0].0, funding_output);
8881                 added_monitors.clear();
8882         }
8883         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8884
8885         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8886
8887         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8888         let channel_id = funding_outpoint.to_channel_id();
8889
8890         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8891         // temporary one).
8892
8893         // First try to open a second channel with a temporary channel id equal to the txid-based one.
8894         // Technically this is allowed by the spec, but we don't support it and there's little reason
8895         // to. Still, it shouldn't cause any other issues.
8896         open_chan_msg.temporary_channel_id = channel_id;
8897         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8898         {
8899                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8900                 assert_eq!(events.len(), 1);
8901                 match events[0] {
8902                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8903                                 // Technically, at this point, nodes[1] would be justified in thinking both
8904                                 // channels are closed, but currently we do not, so we just move forward with it.
8905                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8906                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8907                         },
8908                         _ => panic!("Unexpected event"),
8909                 }
8910         }
8911
8912         // Now try to create a second channel which has a duplicate funding output.
8913         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8914         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8915         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8916         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()));
8917         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8918
8919         let funding_created = {
8920                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8921                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8922                 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8923                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8924                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8925                 // channelmanager in a possibly nonsense state instead).
8926                 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8927                 let logger = test_utils::TestLogger::new();
8928                 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8929         };
8930         check_added_monitors!(nodes[0], 0);
8931         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8932         // At this point we'll look up if the channel_id is present and immediately fail the channel
8933         // without trying to persist the `ChannelMonitor`.
8934         check_added_monitors!(nodes[1], 0);
8935
8936         // ...still, nodes[1] will reject the duplicate channel.
8937         {
8938                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8939                 assert_eq!(events.len(), 1);
8940                 match events[0] {
8941                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8942                                 // Technically, at this point, nodes[1] would be justified in thinking both
8943                                 // channels are closed, but currently we do not, so we just move forward with it.
8944                                 assert_eq!(msg.channel_id, channel_id);
8945                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8946                         },
8947                         _ => panic!("Unexpected event"),
8948                 }
8949         }
8950
8951         // finally, finish creating the original channel and send a payment over it to make sure
8952         // everything is functional.
8953         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8954         {
8955                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8956                 assert_eq!(added_monitors.len(), 1);
8957                 assert_eq!(added_monitors[0].0, funding_output);
8958                 added_monitors.clear();
8959         }
8960         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8961
8962         let events_4 = nodes[0].node.get_and_clear_pending_events();
8963         assert_eq!(events_4.len(), 0);
8964         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8965         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8966
8967         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8968         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8969         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8970
8971         send_payment(&nodes[0], &[&nodes[1]], 8000000);
8972 }
8973
8974 #[test]
8975 fn test_error_chans_closed() {
8976         // Test that we properly handle error messages, closing appropriate channels.
8977         //
8978         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8979         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8980         // we can test various edge cases around it to ensure we don't regress.
8981         let chanmon_cfgs = create_chanmon_cfgs(3);
8982         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8983         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8984         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8985
8986         // Create some initial channels
8987         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8988         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8989         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8990
8991         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8992         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8993         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8994
8995         // Closing a channel from a different peer has no effect
8996         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8997         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8998
8999         // Closing one channel doesn't impact others
9000         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9001         check_added_monitors!(nodes[0], 1);
9002         check_closed_broadcast!(nodes[0], false);
9003         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9004         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9005         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9006         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);
9007         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);
9008
9009         // A null channel ID should close all channels
9010         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9011         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9012         check_added_monitors!(nodes[0], 2);
9013         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9014         let events = nodes[0].node.get_and_clear_pending_msg_events();
9015         assert_eq!(events.len(), 2);
9016         match events[0] {
9017                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9018                         assert_eq!(msg.contents.flags & 2, 2);
9019                 },
9020                 _ => panic!("Unexpected event"),
9021         }
9022         match events[1] {
9023                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9024                         assert_eq!(msg.contents.flags & 2, 2);
9025                 },
9026                 _ => panic!("Unexpected event"),
9027         }
9028         // Note that at this point users of a standard PeerHandler will end up calling
9029         // peer_disconnected.
9030         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9031         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9032
9033         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9034         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9035         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9036 }
9037
9038 #[test]
9039 fn test_invalid_funding_tx() {
9040         // Test that we properly handle invalid funding transactions sent to us from a peer.
9041         //
9042         // Previously, all other major lightning implementations had failed to properly sanitize
9043         // funding transactions from their counterparties, leading to a multi-implementation critical
9044         // security vulnerability (though we always sanitized properly, we've previously had
9045         // un-released crashes in the sanitization process).
9046         //
9047         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9048         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9049         // gave up on it. We test this here by generating such a transaction.
9050         let chanmon_cfgs = create_chanmon_cfgs(2);
9051         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9052         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9053         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9054
9055         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9056         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()));
9057         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()));
9058
9059         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9060
9061         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9062         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9063         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9064         // its length.
9065         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9066         let wit_program_script: Script = wit_program.into();
9067         for output in tx.output.iter_mut() {
9068                 // Make the confirmed funding transaction have a bogus script_pubkey
9069                 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9070         }
9071
9072         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9073         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()));
9074         check_added_monitors!(nodes[1], 1);
9075         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9076
9077         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()));
9078         check_added_monitors!(nodes[0], 1);
9079         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9080
9081         let events_1 = nodes[0].node.get_and_clear_pending_events();
9082         assert_eq!(events_1.len(), 0);
9083
9084         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9085         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9086         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9087
9088         let expected_err = "funding tx had wrong script/value or output index";
9089         confirm_transaction_at(&nodes[1], &tx, 1);
9090         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9091         check_added_monitors!(nodes[1], 1);
9092         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9093         assert_eq!(events_2.len(), 1);
9094         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9095                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9096                 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9097                         assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9098                 } else { panic!(); }
9099         } else { panic!(); }
9100         assert_eq!(nodes[1].node.list_channels().len(), 0);
9101
9102         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9103         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9104         // as its not 32 bytes long.
9105         let mut spend_tx = Transaction {
9106                 version: 2i32, lock_time: PackedLockTime::ZERO,
9107                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9108                         previous_output: BitcoinOutPoint {
9109                                 txid: tx.txid(),
9110                                 vout: idx as u32,
9111                         },
9112                         script_sig: Script::new(),
9113                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9114                         witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9115                 }).collect(),
9116                 output: vec![TxOut {
9117                         value: 1000,
9118                         script_pubkey: Script::new(),
9119                 }]
9120         };
9121         check_spends!(spend_tx, tx);
9122         mine_transaction(&nodes[1], &spend_tx);
9123 }
9124
9125 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9126         // In the first version of the chain::Confirm interface, after a refactor was made to not
9127         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9128         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9129         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9130         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9131         // spending transaction until height N+1 (or greater). This was due to the way
9132         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9133         // spending transaction at the height the input transaction was confirmed at, not whether we
9134         // should broadcast a spending transaction at the current height.
9135         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9136         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9137         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9138         // until we learned about an additional block.
9139         //
9140         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9141         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9142         let chanmon_cfgs = create_chanmon_cfgs(3);
9143         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9144         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9145         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9146         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9147
9148         create_announced_chan_between_nodes(&nodes, 0, 1);
9149         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9150         let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9151         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9152         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9153
9154         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9155         check_closed_broadcast!(nodes[1], true);
9156         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9157         check_added_monitors!(nodes[1], 1);
9158         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9159         assert_eq!(node_txn.len(), 1);
9160
9161         let conf_height = nodes[1].best_block_info().1;
9162         if !test_height_before_timelock {
9163                 connect_blocks(&nodes[1], 24 * 6);
9164         }
9165         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9166                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9167         if test_height_before_timelock {
9168                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9169                 // generate any events or broadcast any transactions
9170                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9171                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9172         } else {
9173                 // We should broadcast an HTLC transaction spending our funding transaction first
9174                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9175                 assert_eq!(spending_txn.len(), 2);
9176                 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9177                 check_spends!(spending_txn[1], node_txn[0]);
9178                 // We should also generate a SpendableOutputs event with the to_self output (as its
9179                 // timelock is up).
9180                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9181                 assert_eq!(descriptor_spend_txn.len(), 1);
9182
9183                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9184                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9185                 // additional block built on top of the current chain.
9186                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9187                         &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9188                 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 }]);
9189                 check_added_monitors!(nodes[1], 1);
9190
9191                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9192                 assert!(updates.update_add_htlcs.is_empty());
9193                 assert!(updates.update_fulfill_htlcs.is_empty());
9194                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9195                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9196                 assert!(updates.update_fee.is_none());
9197                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9198                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9199                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9200         }
9201 }
9202
9203 #[test]
9204 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9205         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9206         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9207 }
9208
9209 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9210         let chanmon_cfgs = create_chanmon_cfgs(2);
9211         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9212         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9213         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9214
9215         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9216
9217         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9218                 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9219         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9220
9221         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9222
9223         {
9224                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9225                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9226                 check_added_monitors!(nodes[0], 1);
9227                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9228                 assert_eq!(events.len(), 1);
9229                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9230                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9231                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9232         }
9233         expect_pending_htlcs_forwardable!(nodes[1]);
9234         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9235
9236         {
9237                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9238                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9239                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9240                 check_added_monitors!(nodes[0], 1);
9241                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9242                 assert_eq!(events.len(), 1);
9243                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9244                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9245                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9246                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9247                 // assume the second is a privacy attack (no longer particularly relevant
9248                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9249                 // the first HTLC delivered above.
9250         }
9251
9252         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9253         nodes[1].node.process_pending_htlc_forwards();
9254
9255         if test_for_second_fail_panic {
9256                 // Now we go fail back the first HTLC from the user end.
9257                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9258
9259                 let expected_destinations = vec![
9260                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9261                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9262                 ];
9263                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9264                 nodes[1].node.process_pending_htlc_forwards();
9265
9266                 check_added_monitors!(nodes[1], 1);
9267                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9268                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9269
9270                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9271                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9272                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9273
9274                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9275                 assert_eq!(failure_events.len(), 4);
9276                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9277                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9278                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9279                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9280         } else {
9281                 // Let the second HTLC fail and claim the first
9282                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9283                 nodes[1].node.process_pending_htlc_forwards();
9284
9285                 check_added_monitors!(nodes[1], 1);
9286                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9287                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9288                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9289
9290                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9291
9292                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9293         }
9294 }
9295
9296 #[test]
9297 fn test_dup_htlc_second_fail_panic() {
9298         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9299         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9300         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9301         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9302         do_test_dup_htlc_second_rejected(true);
9303 }
9304
9305 #[test]
9306 fn test_dup_htlc_second_rejected() {
9307         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9308         // simply reject the second HTLC but are still able to claim the first HTLC.
9309         do_test_dup_htlc_second_rejected(false);
9310 }
9311
9312 #[test]
9313 fn test_inconsistent_mpp_params() {
9314         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9315         // such HTLC and allow the second to stay.
9316         let chanmon_cfgs = create_chanmon_cfgs(4);
9317         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9318         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9319         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9320
9321         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9322         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9323         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9324         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9325
9326         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9327                 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9328         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9329         assert_eq!(route.paths.len(), 2);
9330         route.paths.sort_by(|path_a, _| {
9331                 // Sort the path so that the path through nodes[1] comes first
9332                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9333                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9334         });
9335
9336         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9337
9338         let cur_height = nodes[0].best_block_info().1;
9339         let payment_id = PaymentId([42; 32]);
9340
9341         let session_privs = {
9342                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9343                 // ultimately have, just not right away.
9344                 let mut dup_route = route.clone();
9345                 dup_route.paths.push(route.paths[1].clone());
9346                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9347                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9348         };
9349         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9350                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9351                 &None, session_privs[0]).unwrap();
9352         check_added_monitors!(nodes[0], 1);
9353
9354         {
9355                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9356                 assert_eq!(events.len(), 1);
9357                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9358         }
9359         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9360
9361         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9362                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9363         check_added_monitors!(nodes[0], 1);
9364
9365         {
9366                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9367                 assert_eq!(events.len(), 1);
9368                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9369
9370                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9371                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9372
9373                 expect_pending_htlcs_forwardable!(nodes[2]);
9374                 check_added_monitors!(nodes[2], 1);
9375
9376                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9377                 assert_eq!(events.len(), 1);
9378                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9379
9380                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9381                 check_added_monitors!(nodes[3], 0);
9382                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9383
9384                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9385                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9386                 // post-payment_secrets) and fail back the new HTLC.
9387         }
9388         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9389         nodes[3].node.process_pending_htlc_forwards();
9390         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9391         nodes[3].node.process_pending_htlc_forwards();
9392
9393         check_added_monitors!(nodes[3], 1);
9394
9395         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9396         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9397         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9398
9399         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 }]);
9400         check_added_monitors!(nodes[2], 1);
9401
9402         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9403         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9404         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9405
9406         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9407
9408         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9409                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9410                 &None, session_privs[2]).unwrap();
9411         check_added_monitors!(nodes[0], 1);
9412
9413         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9414         assert_eq!(events.len(), 1);
9415         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9416
9417         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9418         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9419 }
9420
9421 #[test]
9422 fn test_keysend_payments_to_public_node() {
9423         let chanmon_cfgs = create_chanmon_cfgs(2);
9424         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9425         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9426         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9427
9428         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9429         let network_graph = nodes[0].network_graph.clone();
9430         let payer_pubkey = nodes[0].node.get_our_node_id();
9431         let payee_pubkey = nodes[1].node.get_our_node_id();
9432         let route_params = RouteParameters {
9433                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9434                 final_value_msat: 10000,
9435         };
9436         let scorer = test_utils::TestScorer::new();
9437         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9438         let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9439
9440         let test_preimage = PaymentPreimage([42; 32]);
9441         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9442                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9443         check_added_monitors!(nodes[0], 1);
9444         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9445         assert_eq!(events.len(), 1);
9446         let event = events.pop().unwrap();
9447         let path = vec![&nodes[1]];
9448         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9449         claim_payment(&nodes[0], &path, test_preimage);
9450 }
9451
9452 #[test]
9453 fn test_keysend_payments_to_private_node() {
9454         let chanmon_cfgs = create_chanmon_cfgs(2);
9455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9457         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9458
9459         let payer_pubkey = nodes[0].node.get_our_node_id();
9460         let payee_pubkey = nodes[1].node.get_our_node_id();
9461
9462         let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9463         let route_params = RouteParameters {
9464                 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9465                 final_value_msat: 10000,
9466         };
9467         let network_graph = nodes[0].network_graph.clone();
9468         let first_hops = nodes[0].node.list_usable_channels();
9469         let scorer = test_utils::TestScorer::new();
9470         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9471         let route = find_route(
9472                 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9473                 nodes[0].logger, &scorer, &(), &random_seed_bytes
9474         ).unwrap();
9475
9476         let test_preimage = PaymentPreimage([42; 32]);
9477         let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9478                 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9479         check_added_monitors!(nodes[0], 1);
9480         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9481         assert_eq!(events.len(), 1);
9482         let event = events.pop().unwrap();
9483         let path = vec![&nodes[1]];
9484         pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9485         claim_payment(&nodes[0], &path, test_preimage);
9486 }
9487
9488 #[test]
9489 fn test_double_partial_claim() {
9490         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9491         // time out, the sender resends only some of the MPP parts, then the user processes the
9492         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9493         // amount.
9494         let chanmon_cfgs = create_chanmon_cfgs(4);
9495         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9496         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9497         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9498
9499         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9500         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9501         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9502         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9503
9504         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9505         assert_eq!(route.paths.len(), 2);
9506         route.paths.sort_by(|path_a, _| {
9507                 // Sort the path so that the path through nodes[1] comes first
9508                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9509                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9510         });
9511
9512         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9513         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9514         // amount of time to respond to.
9515
9516         // Connect some blocks to time out the payment
9517         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9518         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9519
9520         let failed_destinations = vec![
9521                 HTLCDestination::FailedPayment { payment_hash },
9522                 HTLCDestination::FailedPayment { payment_hash },
9523         ];
9524         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9525
9526         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9527
9528         // nodes[1] now retries one of the two paths...
9529         nodes[0].node.send_payment_with_route(&route, payment_hash,
9530                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9531         check_added_monitors!(nodes[0], 2);
9532
9533         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9534         assert_eq!(events.len(), 2);
9535         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9536         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9537
9538         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9539         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9540         nodes[3].node.claim_funds(payment_preimage);
9541         check_added_monitors!(nodes[3], 0);
9542         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9543 }
9544
9545 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9546 #[derive(Clone, Copy, PartialEq)]
9547 enum ExposureEvent {
9548         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9549         AtHTLCForward,
9550         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9551         AtHTLCReception,
9552         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9553         AtUpdateFeeOutbound,
9554 }
9555
9556 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9557         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9558         // policy.
9559         //
9560         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9561         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9562         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9563         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9564         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9565         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9566         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9567         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9568
9569         let chanmon_cfgs = create_chanmon_cfgs(2);
9570         let mut config = test_default_channel_config();
9571         config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9572         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9573         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9574         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9575
9576         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9577         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9578         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9579         open_channel.max_accepted_htlcs = 60;
9580         if on_holder_tx {
9581                 open_channel.dust_limit_satoshis = 546;
9582         }
9583         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9584         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9585         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9586
9587         let opt_anchors = false;
9588
9589         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9590
9591         if on_holder_tx {
9592                 let mut node_0_per_peer_lock;
9593                 let mut node_0_peer_state_lock;
9594                 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9595                 chan.holder_dust_limit_satoshis = 546;
9596         }
9597
9598         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9599         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()));
9600         check_added_monitors!(nodes[1], 1);
9601         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9602
9603         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()));
9604         check_added_monitors!(nodes[0], 1);
9605         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9606
9607         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9608         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9609         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9610
9611         // Fetch a route in advance as we will be unable to once we're unable to send.
9612         let (mut route, payment_hash, _, payment_secret) =
9613                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9614
9615         let dust_buffer_feerate = {
9616                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9617                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9618                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9619                 chan.get_dust_buffer_feerate(None) as u64
9620         };
9621         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9622         let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9623
9624         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9625         let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9626
9627         let dust_htlc_on_counterparty_tx: u64 = 4;
9628         let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9629
9630         if on_holder_tx {
9631                 if dust_outbound_balance {
9632                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9633                         // Outbound dust balance: 4372 sats
9634                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9635                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9636                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9637                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9638                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9639                         }
9640                 } else {
9641                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9642                         // Inbound dust balance: 4372 sats
9643                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9644                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9645                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9646                         }
9647                 }
9648         } else {
9649                 if dust_outbound_balance {
9650                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9651                         // Outbound dust balance: 5000 sats
9652                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9653                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9654                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9655                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9656                         }
9657                 } else {
9658                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9659                         // Inbound dust balance: 5000 sats
9660                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9661                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9662                         }
9663                 }
9664         }
9665
9666         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9667                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9668                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9669                 // With default dust exposure: 5000 sats
9670                 if on_holder_tx {
9671                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9672                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9673                                 ), true, APIError::ChannelUnavailable { .. }, {});
9674                 } else {
9675                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9676                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9677                                 ), true, APIError::ChannelUnavailable { .. }, {});
9678                 }
9679         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9680                 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 + 1 });
9681                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9682                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9683                 check_added_monitors!(nodes[1], 1);
9684                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9685                 assert_eq!(events.len(), 1);
9686                 let payment_event = SendEvent::from_event(events.remove(0));
9687                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9688                 // With default dust exposure: 5000 sats
9689                 if on_holder_tx {
9690                         // Outbound dust balance: 6399 sats
9691                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9692                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9693                         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 }, config.channel_config.max_dust_htlc_exposure_msat), 1);
9694                 } else {
9695                         // Outbound dust balance: 5200 sats
9696                         nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9697                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9698                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 1,
9699                                         config.channel_config.max_dust_htlc_exposure_msat), 1);
9700                 }
9701         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9702                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9703                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9704                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9705                 {
9706                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9707                         *feerate_lock = *feerate_lock * 10;
9708                 }
9709                 nodes[0].node.timer_tick_occurred();
9710                 check_added_monitors!(nodes[0], 1);
9711                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9712         }
9713
9714         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9715         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9716         added_monitors.clear();
9717 }
9718
9719 #[test]
9720 fn test_max_dust_htlc_exposure() {
9721         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9722         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9723         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9724         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9725         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9726         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9727         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9728         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9729         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9730         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9731         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9732         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9733 }
9734
9735 #[test]
9736 fn test_non_final_funding_tx() {
9737         let chanmon_cfgs = create_chanmon_cfgs(2);
9738         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9739         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9740         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9741
9742         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9743         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9744         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9745         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9746         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9747
9748         let best_height = nodes[0].node.best_block.read().unwrap().height();
9749
9750         let chan_id = *nodes[0].network_chan_count.borrow();
9751         let events = nodes[0].node.get_and_clear_pending_events();
9752         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9753         assert_eq!(events.len(), 1);
9754         let mut tx = match events[0] {
9755                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9756                         // Timelock the transaction _beyond_ the best client height + 1.
9757                         Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9758                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9759                         }]}
9760                 },
9761                 _ => panic!("Unexpected event"),
9762         };
9763         // Transaction should fail as it's evaluated as non-final for propagation.
9764         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9765                 Err(APIError::APIMisuseError { err }) => {
9766                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9767                 },
9768                 _ => panic!()
9769         }
9770
9771         // However, transaction should be accepted if it's in a +1 headroom from best block.
9772         tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9773         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9774         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9775 }
9776
9777 #[test]
9778 fn accept_busted_but_better_fee() {
9779         // If a peer sends us a fee update that is too low, but higher than our previous channel
9780         // feerate, we should accept it. In the future we may want to consider closing the channel
9781         // later, but for now we only accept the update.
9782         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9783         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9784         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9785         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9786
9787         create_chan_between_nodes(&nodes[0], &nodes[1]);
9788
9789         // Set nodes[1] to expect 5,000 sat/kW.
9790         {
9791                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9792                 *feerate_lock = 5000;
9793         }
9794
9795         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9796         {
9797                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9798                 *feerate_lock = 1000;
9799         }
9800         nodes[0].node.timer_tick_occurred();
9801         check_added_monitors!(nodes[0], 1);
9802
9803         let events = nodes[0].node.get_and_clear_pending_msg_events();
9804         assert_eq!(events.len(), 1);
9805         match events[0] {
9806                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9807                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9808                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9809                 },
9810                 _ => panic!("Unexpected event"),
9811         };
9812
9813         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9814         // it.
9815         {
9816                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9817                 *feerate_lock = 2000;
9818         }
9819         nodes[0].node.timer_tick_occurred();
9820         check_added_monitors!(nodes[0], 1);
9821
9822         let events = nodes[0].node.get_and_clear_pending_msg_events();
9823         assert_eq!(events.len(), 1);
9824         match events[0] {
9825                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9826                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9827                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9828                 },
9829                 _ => panic!("Unexpected event"),
9830         };
9831
9832         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9833         // channel.
9834         {
9835                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9836                 *feerate_lock = 1000;
9837         }
9838         nodes[0].node.timer_tick_occurred();
9839         check_added_monitors!(nodes[0], 1);
9840
9841         let events = nodes[0].node.get_and_clear_pending_msg_events();
9842         assert_eq!(events.len(), 1);
9843         match events[0] {
9844                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9845                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9846                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9847                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9848                         check_closed_broadcast!(nodes[1], true);
9849                         check_added_monitors!(nodes[1], 1);
9850                 },
9851                 _ => panic!("Unexpected event"),
9852         };
9853 }
9854
9855 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9856         let mut chanmon_cfgs = create_chanmon_cfgs(2);
9857         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9858         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9859         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9860         let min_final_cltv_expiry_delta = 120;
9861         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9862                 min_final_cltv_expiry_delta - 2 };
9863         let recv_value = 100_000;
9864
9865         create_chan_between_nodes(&nodes[0], &nodes[1]);
9866
9867         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9868         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9869                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9870                         Some(recv_value), Some(min_final_cltv_expiry_delta));
9871                 (payment_hash, payment_preimage, payment_secret)
9872         } else {
9873                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9874                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9875         };
9876         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9877         nodes[0].node.send_payment_with_route(&route, payment_hash,
9878                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9879         check_added_monitors!(nodes[0], 1);
9880         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9881         assert_eq!(events.len(), 1);
9882         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9883         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9884         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9885         expect_pending_htlcs_forwardable!(nodes[1]);
9886
9887         if valid_delta {
9888                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9889                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9890
9891                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9892         } else {
9893                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9894
9895                 check_added_monitors!(nodes[1], 1);
9896
9897                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9898                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9899                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9900
9901                 expect_payment_failed!(nodes[0], payment_hash, true);
9902         }
9903 }
9904
9905 #[test]
9906 fn test_payment_with_custom_min_cltv_expiry_delta() {
9907         do_payment_with_custom_min_final_cltv_expiry(false, false);
9908         do_payment_with_custom_min_final_cltv_expiry(false, true);
9909         do_payment_with_custom_min_final_cltv_expiry(true, false);
9910         do_payment_with_custom_min_final_cltv_expiry(true, true);
9911 }