Blinded payments to unannounced introduction node
[rust-lightning] / lightning / src / routing / router.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 //! The router finds paths within a [`NetworkGraph`] for a payment.
11
12 use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
13
14 use crate::blinded_path::{BlindedHop, BlindedPath, Direction, IntroductionNode};
15 use crate::blinded_path::message;
16 use crate::blinded_path::payment::{ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs, self};
17 use crate::ln::{PaymentHash, PaymentPreimage};
18 use crate::ln::channel_state::ChannelDetails;
19 use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA, RecipientOnionFields};
20 use crate::ln::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
21 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
22 use crate::ln::onion_utils;
23 use crate::offers::invoice::{BlindedPayInfo, Bolt12Invoice};
24 use crate::onion_message::messenger::{DefaultMessageRouter, Destination, MessageRouter, OnionMessagePath};
25 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
26 use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
27 use crate::sign::EntropySource;
28 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
29 use crate::util::logger::{Level, Logger};
30 use crate::crypto::chacha20::ChaCha20;
31
32 use crate::io;
33 use crate::prelude::*;
34 use alloc::collections::BinaryHeap;
35 use core::{cmp, fmt};
36 use core::ops::Deref;
37
38 /// A [`Router`] implemented using [`find_route`].
39 ///
40 /// # Privacy
41 ///
42 /// Implements [`MessageRouter`] by delegating to [`DefaultMessageRouter`]. See those docs for
43 /// privacy implications.
44 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
45         L::Target: Logger,
46         S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
47         ES::Target: EntropySource,
48 {
49         network_graph: G,
50         logger: L,
51         entropy_source: ES,
52         scorer: S,
53         score_params: SP,
54         message_router: DefaultMessageRouter<G, L, ES>,
55 }
56
57 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref + Clone, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
58         L::Target: Logger,
59         S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
60         ES::Target: EntropySource,
61 {
62         /// Creates a new router.
63         pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
64                 let message_router = DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone());
65                 Self { network_graph, logger, entropy_source, scorer, score_params, message_router }
66         }
67 }
68
69 impl<G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
70         L::Target: Logger,
71         S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
72         ES::Target: EntropySource,
73 {
74         fn find_route(
75                 &self,
76                 payer: &PublicKey,
77                 params: &RouteParameters,
78                 first_hops: Option<&[&ChannelDetails]>,
79                 inflight_htlcs: InFlightHtlcs
80         ) -> Result<Route, LightningError> {
81                 let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
82                 find_route(
83                         payer, params, &self.network_graph, first_hops, &*self.logger,
84                         &ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
85                         &self.score_params,
86                         &random_seed_bytes
87                 )
88         }
89
90         fn create_blinded_payment_paths<
91                 T: secp256k1::Signing + secp256k1::Verification
92         > (
93                 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
94                 amount_msats: u64, secp_ctx: &Secp256k1<T>
95         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()> {
96                 // Limit the number of blinded paths that are computed.
97                 const MAX_PAYMENT_PATHS: usize = 3;
98
99                 // Ensure peers have at least three channels so that it is more difficult to infer the
100                 // recipient's node_id.
101                 const MIN_PEER_CHANNELS: usize = 3;
102
103                 let has_one_peer = first_hops
104                         .first()
105                         .map(|details| details.counterparty.node_id)
106                         .map(|node_id| first_hops
107                                 .iter()
108                                 .skip(1)
109                                 .all(|details| details.counterparty.node_id == node_id)
110                         )
111                         .unwrap_or(false);
112
113                 let network_graph = self.network_graph.deref().read_only();
114                 let is_recipient_announced =
115                         network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
116
117                 let paths = first_hops.into_iter()
118                         .filter(|details| details.counterparty.features.supports_route_blinding())
119                         .filter(|details| amount_msats <= details.inbound_capacity_msat)
120                         .filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
121                         .filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
122                         .filter(|details| network_graph
123                                         .node(&NodeId::from_pubkey(&details.counterparty.node_id))
124                                         .map(|node_info| node_info.channels.len() >= MIN_PEER_CHANNELS)
125                                         // Allow payments directly with the only peer when unannounced.
126                                         .unwrap_or(!is_recipient_announced && has_one_peer)
127                         )
128                         .filter_map(|details| {
129                                 let short_channel_id = match details.get_inbound_payment_scid() {
130                                         Some(short_channel_id) => short_channel_id,
131                                         None => return None,
132                                 };
133                                 let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
134                                         Some(forwarding_info) => match forwarding_info.try_into() {
135                                                 Ok(payment_relay) => payment_relay,
136                                                 Err(()) => return None,
137                                         },
138                                         None => return None,
139                                 };
140
141                                 let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
142                                 let payment_constraints = PaymentConstraints {
143                                         max_cltv_expiry: tlvs.payment_constraints.max_cltv_expiry + cltv_expiry_delta,
144                                         htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
145                                 };
146                                 Some(payment::ForwardNode {
147                                         tlvs: ForwardTlvs {
148                                                 short_channel_id,
149                                                 payment_relay,
150                                                 payment_constraints,
151                                                 features: BlindedHopFeatures::empty(),
152                                         },
153                                         node_id: details.counterparty.node_id,
154                                         htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
155                                 })
156                         })
157                         .map(|forward_node| {
158                                 BlindedPath::new_for_payment(
159                                         &[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
160                                         &*self.entropy_source, secp_ctx
161                                 )
162                         })
163                         .take(MAX_PAYMENT_PATHS)
164                         .collect::<Result<Vec<_>, _>>();
165
166                 match paths {
167                         Ok(paths) if !paths.is_empty() => Ok(paths),
168                         _ => {
169                                 if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
170                                         BlindedPath::one_hop_for_payment(
171                                                 recipient, tlvs, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source, secp_ctx
172                                         ).map(|path| vec![path])
173                                 } else {
174                                         Err(())
175                                 }
176                         },
177                 }
178         }
179 }
180
181 impl< G: Deref<Target = NetworkGraph<L>> + Clone, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> MessageRouter for DefaultRouter<G, L, ES, S, SP, Sc> where
182         L::Target: Logger,
183         S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
184         ES::Target: EntropySource,
185 {
186         fn find_path(
187                 &self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination
188         ) -> Result<OnionMessagePath, ()> {
189                 self.message_router.find_path(sender, peers, destination)
190         }
191
192         fn create_blinded_paths<
193                 T: secp256k1::Signing + secp256k1::Verification
194         > (
195                 &self, recipient: PublicKey, peers: Vec<PublicKey>, secp_ctx: &Secp256k1<T>,
196         ) -> Result<Vec<BlindedPath>, ()> {
197                 self.message_router.create_blinded_paths(recipient, peers, secp_ctx)
198         }
199
200         fn create_compact_blinded_paths<
201                 T: secp256k1::Signing + secp256k1::Verification
202         > (
203                 &self, recipient: PublicKey, peers: Vec<message::ForwardNode>, secp_ctx: &Secp256k1<T>,
204         ) -> Result<Vec<BlindedPath>, ()> {
205                 self.message_router.create_compact_blinded_paths(recipient, peers, secp_ctx)
206         }
207 }
208
209 /// A trait defining behavior for routing a payment.
210 pub trait Router: MessageRouter {
211         /// Finds a [`Route`] for a payment between the given `payer` and a payee.
212         ///
213         /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
214         /// and [`RouteParameters::final_value_msat`], respectively.
215         fn find_route(
216                 &self, payer: &PublicKey, route_params: &RouteParameters,
217                 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
218         ) -> Result<Route, LightningError>;
219
220         /// Finds a [`Route`] for a payment between the given `payer` and a payee.
221         ///
222         /// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
223         /// and [`RouteParameters::final_value_msat`], respectively.
224         ///
225         /// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
226         /// payment.
227         fn find_route_with_id(
228                 &self, payer: &PublicKey, route_params: &RouteParameters,
229                 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
230                 _payment_hash: PaymentHash, _payment_id: PaymentId
231         ) -> Result<Route, LightningError> {
232                 self.find_route(payer, route_params, first_hops, inflight_htlcs)
233         }
234
235         /// Creates [`BlindedPath`]s for payment to the `recipient` node. The channels in `first_hops`
236         /// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
237         /// given in `tlvs`.
238         fn create_blinded_payment_paths<
239                 T: secp256k1::Signing + secp256k1::Verification
240         > (
241                 &self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
242                 amount_msats: u64, secp_ctx: &Secp256k1<T>
243         ) -> Result<Vec<(BlindedPayInfo, BlindedPath)>, ()>;
244 }
245
246 /// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
247 ///
248 /// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
249 /// [`find_route`].
250 ///
251 /// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
252 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
253         scorer: S,
254         // Maps a channel's short channel id and its direction to the liquidity used up.
255         inflight_htlcs: &'a InFlightHtlcs,
256 }
257 impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
258         /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
259         pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
260                 ScorerAccountingForInFlightHtlcs {
261                         scorer,
262                         inflight_htlcs
263                 }
264         }
265 }
266
267 impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
268         type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
269         fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
270                 let target = match candidate.target() {
271                         Some(target) => target,
272                         None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
273                 };
274                 let short_channel_id = match candidate.short_channel_id() {
275                         Some(short_channel_id) => short_channel_id,
276                         None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
277                 };
278                 let source = candidate.source();
279                 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
280                         &source, &target, short_channel_id
281                 ) {
282                         let usage = ChannelUsage {
283                                 inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
284                                 ..usage
285                         };
286
287                         self.scorer.channel_penalty_msat(candidate, usage, score_params)
288                 } else {
289                         self.scorer.channel_penalty_msat(candidate, usage, score_params)
290                 }
291         }
292 }
293
294 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
295 /// in-use channel liquidity.
296 #[derive(Clone)]
297 pub struct InFlightHtlcs(
298         // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
299         // is traveling in. The direction boolean is determined by checking if the HTLC source's public
300         // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
301         // details.
302         HashMap<(u64, bool), u64>
303 );
304
305 impl InFlightHtlcs {
306         /// Constructs an empty `InFlightHtlcs`.
307         pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
308
309         /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
310         pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
311                 if path.hops.is_empty() { return };
312
313                 let mut cumulative_msat = 0;
314                 if let Some(tail) = &path.blinded_tail {
315                         cumulative_msat += tail.final_value_msat;
316                 }
317
318                 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
319                 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
320                 // the router excludes the payer node. In the following lines, the payer's information is
321                 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
322                 // in our sliding window of two.
323                 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
324                         .map(|hop| hop.pubkey)
325                         .chain(core::iter::once(payer_node_id));
326
327                 // Taking the reversed vector from above, we zip it with just the reversed hops list to
328                 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
329                 // the total amount sent.
330                 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
331                         cumulative_msat += next_hop.fee_msat;
332                         self.0
333                                 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
334                                 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
335                                 .or_insert(cumulative_msat);
336                 }
337         }
338
339         /// Adds a known HTLC given the public key of the HTLC source, target, and short channel
340         /// id.
341         pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
342                 self.0
343                         .entry((channel_scid, source < target))
344                         .and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
345                         .or_insert(used_msat);
346         }
347
348         /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
349         /// id.
350         pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
351                 self.0.get(&(channel_scid, source < target)).map(|v| *v)
352         }
353 }
354
355 impl Writeable for InFlightHtlcs {
356         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
357 }
358
359 impl Readable for InFlightHtlcs {
360         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
361                 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
362                 Ok(Self(infight_map))
363         }
364 }
365
366 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
367 /// that leads to it.
368 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
369 pub struct RouteHop {
370         /// The node_id of the node at this hop.
371         pub pubkey: PublicKey,
372         /// The node_announcement features of the node at this hop. For the last hop, these may be
373         /// amended to match the features present in the invoice this node generated.
374         pub node_features: NodeFeatures,
375         /// The channel that should be used from the previous hop to reach this node.
376         pub short_channel_id: u64,
377         /// The channel_announcement features of the channel that should be used from the previous hop
378         /// to reach this node.
379         pub channel_features: ChannelFeatures,
380         /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
381         /// If this is the last hop in [`Path::hops`]:
382         /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
383         /// * otherwise, this is the full value of this [`Path`]'s part of the payment
384         ///
385         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
386         pub fee_msat: u64,
387         /// The CLTV delta added for this hop.
388         /// If this is the last hop in [`Path::hops`]:
389         /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
390         /// * otherwise, this is the CLTV delta expected at the destination
391         ///
392         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
393         pub cltv_expiry_delta: u32,
394         /// Indicates whether this hop is possibly announced in the public network graph.
395         ///
396         /// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
397         /// either know for sure it's announced in the public graph, or if any public channels exist
398         /// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
399         /// the channel to be unannounced.
400         ///
401         /// Will be `true` for objects serialized with LDK version 0.0.116 and before.
402         pub maybe_announced_channel: bool,
403 }
404
405 impl_writeable_tlv_based!(RouteHop, {
406         (0, pubkey, required),
407         (1, maybe_announced_channel, (default_value, true)),
408         (2, node_features, required),
409         (4, short_channel_id, required),
410         (6, channel_features, required),
411         (8, fee_msat, required),
412         (10, cltv_expiry_delta, required),
413 });
414
415 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
416 /// their [`Bolt12Invoice`].
417 ///
418 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
419 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
420 pub struct BlindedTail {
421         /// The hops of the [`BlindedPath`] provided by the recipient.
422         ///
423         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
424         pub hops: Vec<BlindedHop>,
425         /// The blinding point of the [`BlindedPath`] provided by the recipient.
426         ///
427         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
428         pub blinding_point: PublicKey,
429         /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
430         /// inferring the destination. May be 0.
431         pub excess_final_cltv_expiry_delta: u32,
432         /// The total amount paid on this [`Path`], excluding the fees.
433         pub final_value_msat: u64,
434 }
435
436 impl_writeable_tlv_based!(BlindedTail, {
437         (0, hops, required_vec),
438         (2, blinding_point, required),
439         (4, excess_final_cltv_expiry_delta, required),
440         (6, final_value_msat, required),
441 });
442
443 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
444 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
445 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
446 pub struct Path {
447         /// The list of unblinded hops in this [`Path`]. Must be at least length one.
448         pub hops: Vec<RouteHop>,
449         /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
450         pub blinded_tail: Option<BlindedTail>,
451 }
452
453 impl Path {
454         /// Gets the fees for a given path, excluding any excess paid to the recipient.
455         pub fn fee_msat(&self) -> u64 {
456                 match &self.blinded_tail {
457                         Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
458                         None => {
459                                 // Do not count last hop of each path since that's the full value of the payment
460                                 self.hops.split_last().map_or(0,
461                                         |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
462                         }
463                 }
464         }
465
466         /// Gets the total amount paid on this [`Path`], excluding the fees.
467         pub fn final_value_msat(&self) -> u64 {
468                 match &self.blinded_tail {
469                         Some(blinded_tail) => blinded_tail.final_value_msat,
470                         None => self.hops.last().map_or(0, |hop| hop.fee_msat)
471                 }
472         }
473
474         /// Gets the final hop's CLTV expiry delta.
475         pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
476                 match &self.blinded_tail {
477                         Some(_) => None,
478                         None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
479                 }
480         }
481 }
482
483 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
484 /// it can take multiple paths. Each path is composed of one or more hops through the network.
485 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
486 pub struct Route {
487         /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
488         /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
489         /// the same.
490         pub paths: Vec<Path>,
491         /// The `route_params` parameter passed to [`find_route`].
492         ///
493         /// This is used by `ChannelManager` to track information which may be required for retries.
494         ///
495         /// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
496         pub route_params: Option<RouteParameters>,
497 }
498
499 impl Route {
500         /// Returns the total amount of fees paid on this [`Route`].
501         ///
502         /// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
503         /// the recipient, which can happen in excess of the amount passed to [`find_route`] via
504         /// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
505         ///
506         /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
507         pub fn get_total_fees(&self) -> u64 {
508                 let overpaid_value_msat = self.route_params.as_ref()
509                         .map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
510                 overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
511         }
512
513         /// Returns the total amount paid on this [`Route`], excluding the fees.
514         ///
515         /// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
516         /// we had to reach the [`htlc_minimum_msat`] limits.
517         ///
518         /// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
519         pub fn get_total_amount(&self) -> u64 {
520                 self.paths.iter().map(|path| path.final_value_msat()).sum()
521         }
522 }
523
524 impl fmt::Display for Route {
525         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
526                 log_route!(self).fmt(f)
527         }
528 }
529
530 const SERIALIZATION_VERSION: u8 = 1;
531 const MIN_SERIALIZATION_VERSION: u8 = 1;
532
533 impl Writeable for Route {
534         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
535                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
536                 (self.paths.len() as u64).write(writer)?;
537                 let mut blinded_tails = Vec::new();
538                 for (idx, path) in self.paths.iter().enumerate() {
539                         (path.hops.len() as u8).write(writer)?;
540                         for hop in path.hops.iter() {
541                                 hop.write(writer)?;
542                         }
543                         if let Some(blinded_tail) = &path.blinded_tail {
544                                 if blinded_tails.is_empty() {
545                                         blinded_tails = Vec::with_capacity(path.hops.len());
546                                         for _ in 0..idx {
547                                                 blinded_tails.push(None);
548                                         }
549                                 }
550                                 blinded_tails.push(Some(blinded_tail));
551                         } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
552                 }
553                 write_tlv_fields!(writer, {
554                         // For compatibility with LDK versions prior to 0.0.117, we take the individual
555                         // RouteParameters' fields and reconstruct them on read.
556                         (1, self.route_params.as_ref().map(|p| &p.payment_params), option),
557                         (2, blinded_tails, optional_vec),
558                         (3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
559                         (5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
560                 });
561                 Ok(())
562         }
563 }
564
565 impl Readable for Route {
566         fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
567                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
568                 let path_count: u64 = Readable::read(reader)?;
569                 if path_count == 0 { return Err(DecodeError::InvalidValue); }
570                 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
571                 let mut min_final_cltv_expiry_delta = u32::max_value();
572                 for _ in 0..path_count {
573                         let hop_count: u8 = Readable::read(reader)?;
574                         let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
575                         for _ in 0..hop_count {
576                                 hops.push(Readable::read(reader)?);
577                         }
578                         if hops.is_empty() { return Err(DecodeError::InvalidValue); }
579                         min_final_cltv_expiry_delta =
580                                 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
581                         paths.push(Path { hops, blinded_tail: None });
582                 }
583                 _init_and_read_len_prefixed_tlv_fields!(reader, {
584                         (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
585                         (2, blinded_tails, optional_vec),
586                         (3, final_value_msat, option),
587                         (5, max_total_routing_fee_msat, option)
588                 });
589                 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
590                 if blinded_tails.len() != 0 {
591                         if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
592                         for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
593                                 path.blinded_tail = blinded_tail_opt;
594                         }
595                 }
596
597                 // If we previously wrote the corresponding fields, reconstruct RouteParameters.
598                 let route_params = match (payment_params, final_value_msat) {
599                         (Some(payment_params), Some(final_value_msat)) => {
600                                 Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
601                         }
602                         _ => None,
603                 };
604
605                 Ok(Route { paths, route_params })
606         }
607 }
608
609 /// Parameters needed to find a [`Route`].
610 ///
611 /// Passed to [`find_route`] and [`build_route_from_hops`].
612 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
613 pub struct RouteParameters {
614         /// The parameters of the failed payment path.
615         pub payment_params: PaymentParameters,
616
617         /// The amount in msats sent on the failed payment path.
618         pub final_value_msat: u64,
619
620         /// The maximum total fees, in millisatoshi, that may accrue during route finding.
621         ///
622         /// This limit also applies to the total fees that may arise while retrying failed payment
623         /// paths.
624         ///
625         /// Note that values below a few sats may result in some paths being spuriously ignored.
626         pub max_total_routing_fee_msat: Option<u64>,
627 }
628
629 impl RouteParameters {
630         /// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
631         ///
632         /// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
633         pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
634                 Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
635         }
636
637         /// Sets the maximum number of hops that can be included in a payment path, based on the provided
638         /// [`RecipientOnionFields`] and blinded paths.
639         pub fn set_max_path_length(
640                 &mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32
641         ) -> Result<(), ()> {
642                 let keysend_preimage_opt = is_keysend.then(|| PaymentPreimage([42; 32]));
643                 onion_utils::set_max_path_length(
644                         self, recipient_onion, keysend_preimage_opt, best_block_height
645                 )
646         }
647 }
648
649 impl Writeable for RouteParameters {
650         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
651                 write_tlv_fields!(writer, {
652                         (0, self.payment_params, required),
653                         (1, self.max_total_routing_fee_msat, option),
654                         (2, self.final_value_msat, required),
655                         // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
656                         // `RouteParameters` directly. For compatibility, we write it here.
657                         (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
658                 });
659                 Ok(())
660         }
661 }
662
663 impl Readable for RouteParameters {
664         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
665                 _init_and_read_len_prefixed_tlv_fields!(reader, {
666                         (0, payment_params, (required: ReadableArgs, 0)),
667                         (1, max_total_routing_fee_msat, option),
668                         (2, final_value_msat, required),
669                         (4, final_cltv_delta, option),
670                 });
671                 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
672                 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
673                         if final_cltv_expiry_delta == &0 {
674                                 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
675                         }
676                 }
677                 Ok(Self {
678                         payment_params,
679                         final_value_msat: final_value_msat.0.unwrap(),
680                         max_total_routing_fee_msat,
681                 })
682         }
683 }
684
685 /// Maximum total CTLV difference we allow for a full payment path.
686 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
687
688 /// Maximum number of paths we allow an (MPP) payment to have.
689 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
690 // limits, but for now more than 10 paths likely carries too much one-path failure.
691 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
692
693 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
694
695 // The median hop CLTV expiry delta currently seen in the network.
696 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
697
698 /// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
699 /// payment metadata, custom TLVs, or blinded paths are included in the payment.
700 // During routing, we only consider paths shorter than our maximum length estimate.
701 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
702 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
703 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
704 //
705 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
706 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
707 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
708 // (payment_secret and total_msat) = 93 bytes for the final hop.
709 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
710 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
711 pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
712
713 /// Information used to route a payment.
714 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
715 pub struct PaymentParameters {
716         /// Information about the payee, such as their features and route hints for their channels.
717         pub payee: Payee,
718
719         /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
720         pub expiry_time: Option<u64>,
721
722         /// The maximum total CLTV delta we accept for the route.
723         /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
724         pub max_total_cltv_expiry_delta: u32,
725
726         /// The maximum number of paths that may be used by (MPP) payments.
727         /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
728         pub max_path_count: u8,
729
730         /// The maximum number of [`Path::hops`] in any returned path.
731         /// Defaults to [`MAX_PATH_LENGTH_ESTIMATE`].
732         pub max_path_length: u8,
733
734         /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
735         /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
736         /// a lower value prefers to send larger MPP parts, potentially saturating channels and
737         /// increasing failure probability for those paths.
738         ///
739         /// Note that this restriction will be relaxed during pathfinding after paths which meet this
740         /// restriction have been found. While paths which meet this criteria will be searched for, it
741         /// is ultimately up to the scorer to select them over other paths.
742         ///
743         /// A value of 0 will allow payments up to and including a channel's total announced usable
744         /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
745         ///
746         /// Default value: 2
747         pub max_channel_saturation_power_of_half: u8,
748
749         /// A list of SCIDs which this payment was previously attempted over and which caused the
750         /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
751         /// these SCIDs.
752         pub previously_failed_channels: Vec<u64>,
753
754         /// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
755         /// payment was previously attempted over and which caused the payment to fail. Future attempts
756         /// for the same payment shouldn't be relayed through any of these blinded paths.
757         pub previously_failed_blinded_path_idxs: Vec<u64>,
758 }
759
760 impl Writeable for PaymentParameters {
761         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
762                 let mut clear_hints = &vec![];
763                 let mut blinded_hints = &vec![];
764                 match &self.payee {
765                         Payee::Clear { route_hints, .. } => clear_hints = route_hints,
766                         Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
767                 }
768                 write_tlv_fields!(writer, {
769                         (0, self.payee.node_id(), option),
770                         (1, self.max_total_cltv_expiry_delta, required),
771                         (2, self.payee.features(), option),
772                         (3, self.max_path_count, required),
773                         (4, *clear_hints, required_vec),
774                         (5, self.max_channel_saturation_power_of_half, required),
775                         (6, self.expiry_time, option),
776                         (7, self.previously_failed_channels, required_vec),
777                         (8, *blinded_hints, optional_vec),
778                         (9, self.payee.final_cltv_expiry_delta(), option),
779                         (11, self.previously_failed_blinded_path_idxs, required_vec),
780                         (13, self.max_path_length, required),
781                 });
782                 Ok(())
783         }
784 }
785
786 impl ReadableArgs<u32> for PaymentParameters {
787         fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
788                 _init_and_read_len_prefixed_tlv_fields!(reader, {
789                         (0, payee_pubkey, option),
790                         (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
791                         (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
792                         (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
793                         (4, clear_route_hints, required_vec),
794                         (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
795                         (6, expiry_time, option),
796                         (7, previously_failed_channels, optional_vec),
797                         (8, blinded_route_hints, optional_vec),
798                         (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
799                         (11, previously_failed_blinded_path_idxs, optional_vec),
800                         (13, max_path_length, (default_value, MAX_PATH_LENGTH_ESTIMATE)),
801                 });
802                 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
803                 let payee = if blinded_route_hints.len() != 0 {
804                         if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
805                         Payee::Blinded {
806                                 route_hints: blinded_route_hints,
807                                 features: features.and_then(|f: Features| f.bolt12()),
808                         }
809                 } else {
810                         Payee::Clear {
811                                 route_hints: clear_route_hints,
812                                 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
813                                 features: features.and_then(|f| f.bolt11()),
814                                 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
815                         }
816                 };
817                 Ok(Self {
818                         max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
819                         max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
820                         payee,
821                         max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
822                         expiry_time,
823                         previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
824                         previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
825                         max_path_length: _init_tlv_based_struct_field!(max_path_length, (default_value, unused)),
826                 })
827         }
828 }
829
830
831 impl PaymentParameters {
832         /// Creates a payee with the node id of the given `pubkey`.
833         ///
834         /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
835         /// provided.
836         pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
837                 Self {
838                         payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
839                         expiry_time: None,
840                         max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
841                         max_path_count: DEFAULT_MAX_PATH_COUNT,
842                         max_path_length: MAX_PATH_LENGTH_ESTIMATE,
843                         max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
844                         previously_failed_channels: Vec::new(),
845                         previously_failed_blinded_path_idxs: Vec::new(),
846                 }
847         }
848
849         /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
850         ///
851         /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
852         /// provided.
853         ///
854         /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
855         /// whether your router will be allowed to find a multi-part route for this payment. If you
856         /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
857         /// [`RecipientOnionFields::secret_only`].
858         ///
859         /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
860         pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
861                 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
862                         .with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
863                         .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
864         }
865
866         /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
867         /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
868         /// [`PaymentParameters::expiry_time`].
869         pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
870                 Self::blinded(invoice.payment_paths().to_vec())
871                         .with_bolt12_features(invoice.invoice_features().clone()).unwrap()
872                         .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
873         }
874
875         /// Creates parameters for paying to a blinded payee from the provided blinded route hints.
876         pub fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
877                 Self {
878                         payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
879                         expiry_time: None,
880                         max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
881                         max_path_count: DEFAULT_MAX_PATH_COUNT,
882                         max_path_length: MAX_PATH_LENGTH_ESTIMATE,
883                         max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
884                         previously_failed_channels: Vec::new(),
885                         previously_failed_blinded_path_idxs: Vec::new(),
886                 }
887         }
888
889         /// Includes the payee's features. Errors if the parameters were not initialized with
890         /// [`PaymentParameters::from_bolt12_invoice`].
891         ///
892         /// This is not exported to bindings users since bindings don't support move semantics
893         pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
894                 match self.payee {
895                         Payee::Clear { .. } => Err(()),
896                         Payee::Blinded { route_hints, .. } =>
897                                 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
898                 }
899         }
900
901         /// Includes the payee's features. Errors if the parameters were initialized with
902         /// [`PaymentParameters::from_bolt12_invoice`].
903         ///
904         /// This is not exported to bindings users since bindings don't support move semantics
905         pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
906                 match self.payee {
907                         Payee::Blinded { .. } => Err(()),
908                         Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
909                                 Ok(Self {
910                                         payee: Payee::Clear {
911                                                 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
912                                         }, ..self
913                                 })
914                 }
915         }
916
917         /// Includes hints for routing to the payee. Errors if the parameters were initialized with
918         /// [`PaymentParameters::from_bolt12_invoice`].
919         ///
920         /// This is not exported to bindings users since bindings don't support move semantics
921         pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
922                 match self.payee {
923                         Payee::Blinded { .. } => Err(()),
924                         Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
925                                 Ok(Self {
926                                         payee: Payee::Clear {
927                                                 route_hints, node_id, features, final_cltv_expiry_delta,
928                                         }, ..self
929                                 })
930                 }
931         }
932
933         /// Includes a payment expiration in seconds relative to the UNIX epoch.
934         ///
935         /// This is not exported to bindings users since bindings don't support move semantics
936         pub fn with_expiry_time(self, expiry_time: u64) -> Self {
937                 Self { expiry_time: Some(expiry_time), ..self }
938         }
939
940         /// Includes a limit for the total CLTV expiry delta which is considered during routing
941         ///
942         /// This is not exported to bindings users since bindings don't support move semantics
943         pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
944                 Self { max_total_cltv_expiry_delta, ..self }
945         }
946
947         /// Includes a limit for the maximum number of payment paths that may be used.
948         ///
949         /// This is not exported to bindings users since bindings don't support move semantics
950         pub fn with_max_path_count(self, max_path_count: u8) -> Self {
951                 Self { max_path_count, ..self }
952         }
953
954         /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
955         /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
956         ///
957         /// This is not exported to bindings users since bindings don't support move semantics
958         pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
959                 Self { max_channel_saturation_power_of_half, ..self }
960         }
961
962         pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
963                 let mut found_blinded_tail = false;
964                 for (idx, (_, path)) in self.payee.blinded_route_hints().iter().enumerate() {
965                         if failed_blinded_tail.hops == path.blinded_hops &&
966                                 failed_blinded_tail.blinding_point == path.blinding_point
967                         {
968                                 self.previously_failed_blinded_path_idxs.push(idx as u64);
969                                 found_blinded_tail = true;
970                         }
971                 }
972                 debug_assert!(found_blinded_tail);
973         }
974 }
975
976 /// The recipient of a payment, differing based on whether they've hidden their identity with route
977 /// blinding.
978 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
979 pub enum Payee {
980         /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
981         /// will be included in the final [`Route`].
982         Blinded {
983                 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
984                 /// node id.
985                 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
986                 /// Features supported by the payee.
987                 ///
988                 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
989                 /// features.
990                 features: Option<Bolt12InvoiceFeatures>,
991         },
992         /// The recipient included these route hints in their BOLT11 invoice.
993         Clear {
994                 /// The node id of the payee.
995                 node_id: PublicKey,
996                 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
997                 route_hints: Vec<RouteHint>,
998                 /// Features supported by the payee.
999                 ///
1000                 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
1001                 /// does not contain any features.
1002                 ///
1003                 /// [`for_keysend`]: PaymentParameters::for_keysend
1004                 features: Option<Bolt11InvoiceFeatures>,
1005                 /// The minimum CLTV delta at the end of the route. This value must not be zero.
1006                 final_cltv_expiry_delta: u32,
1007         },
1008 }
1009
1010 impl Payee {
1011         fn node_id(&self) -> Option<PublicKey> {
1012                 match self {
1013                         Self::Clear { node_id, .. } => Some(*node_id),
1014                         _ => None,
1015                 }
1016         }
1017         fn node_features(&self) -> Option<NodeFeatures> {
1018                 match self {
1019                         Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
1020                         Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
1021                 }
1022         }
1023         fn supports_basic_mpp(&self) -> bool {
1024                 match self {
1025                         Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1026                         Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1027                 }
1028         }
1029         fn features(&self) -> Option<FeaturesRef> {
1030                 match self {
1031                         Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
1032                         Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
1033                 }
1034         }
1035         fn final_cltv_expiry_delta(&self) -> Option<u32> {
1036                 match self {
1037                         Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
1038                         _ => None,
1039                 }
1040         }
1041         pub(crate) fn blinded_route_hints(&self) -> &[(BlindedPayInfo, BlindedPath)] {
1042                 match self {
1043                         Self::Blinded { route_hints, .. } => &route_hints[..],
1044                         Self::Clear { .. } => &[]
1045                 }
1046         }
1047
1048         fn unblinded_route_hints(&self) -> &[RouteHint] {
1049                 match self {
1050                         Self::Blinded { .. } => &[],
1051                         Self::Clear { route_hints, .. } => &route_hints[..]
1052                 }
1053         }
1054 }
1055
1056 enum FeaturesRef<'a> {
1057         Bolt11(&'a Bolt11InvoiceFeatures),
1058         Bolt12(&'a Bolt12InvoiceFeatures),
1059 }
1060 enum Features {
1061         Bolt11(Bolt11InvoiceFeatures),
1062         Bolt12(Bolt12InvoiceFeatures),
1063 }
1064
1065 impl Features {
1066         fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1067                 match self {
1068                         Self::Bolt12(f) => Some(f),
1069                         _ => None,
1070                 }
1071         }
1072         fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1073                 match self {
1074                         Self::Bolt11(f) => Some(f),
1075                         _ => None,
1076                 }
1077         }
1078 }
1079
1080 impl<'a> Writeable for FeaturesRef<'a> {
1081         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1082                 match self {
1083                         Self::Bolt11(f) => Ok(f.write(w)?),
1084                         Self::Bolt12(f) => Ok(f.write(w)?),
1085                 }
1086         }
1087 }
1088
1089 impl ReadableArgs<bool> for Features {
1090         fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1091                 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1092                 Ok(Self::Bolt12(Readable::read(reader)?))
1093         }
1094 }
1095
1096 /// A list of hops along a payment path terminating with a channel to the recipient.
1097 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1098 pub struct RouteHint(pub Vec<RouteHintHop>);
1099
1100 impl Writeable for RouteHint {
1101         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1102                 (self.0.len() as u64).write(writer)?;
1103                 for hop in self.0.iter() {
1104                         hop.write(writer)?;
1105                 }
1106                 Ok(())
1107         }
1108 }
1109
1110 impl Readable for RouteHint {
1111         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1112                 let hop_count: u64 = Readable::read(reader)?;
1113                 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1114                 for _ in 0..hop_count {
1115                         hops.push(Readable::read(reader)?);
1116                 }
1117                 Ok(Self(hops))
1118         }
1119 }
1120
1121 /// A channel descriptor for a hop along a payment path.
1122 ///
1123 /// While this generally comes from BOLT 11's `r` field, this struct includes more fields than are
1124 /// available in BOLT 11. Thus, encoding and decoding this via `lightning-invoice` is lossy, as
1125 /// fields not supported in BOLT 11 will be stripped.
1126 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
1127 pub struct RouteHintHop {
1128         /// The node_id of the non-target end of the route
1129         pub src_node_id: PublicKey,
1130         /// The short_channel_id of this channel
1131         pub short_channel_id: u64,
1132         /// The fees which must be paid to use this channel
1133         pub fees: RoutingFees,
1134         /// The difference in CLTV values between this node and the next node.
1135         pub cltv_expiry_delta: u16,
1136         /// The minimum value, in msat, which must be relayed to the next hop.
1137         pub htlc_minimum_msat: Option<u64>,
1138         /// The maximum value in msat available for routing with a single HTLC.
1139         pub htlc_maximum_msat: Option<u64>,
1140 }
1141
1142 impl_writeable_tlv_based!(RouteHintHop, {
1143         (0, src_node_id, required),
1144         (1, htlc_minimum_msat, option),
1145         (2, short_channel_id, required),
1146         (3, htlc_maximum_msat, option),
1147         (4, fees, required),
1148         (6, cltv_expiry_delta, required),
1149 });
1150
1151 #[derive(Eq, PartialEq)]
1152 #[repr(align(64))] // Force the size to 64 bytes
1153 struct RouteGraphNode {
1154         node_id: NodeId,
1155         score: u64,
1156         // The maximum value a yet-to-be-constructed payment path might flow through this node.
1157         // This value is upper-bounded by us by:
1158         // - how much is needed for a path being constructed
1159         // - how much value can channels following this node (up to the destination) can contribute,
1160         //   considering their capacity and fees
1161         value_contribution_msat: u64,
1162         total_cltv_delta: u32,
1163         /// The number of hops walked up to this node.
1164         path_length_to_node: u8,
1165 }
1166
1167 impl cmp::Ord for RouteGraphNode {
1168         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1169                 other.score.cmp(&self.score).then_with(|| other.node_id.cmp(&self.node_id))
1170         }
1171 }
1172
1173 impl cmp::PartialOrd for RouteGraphNode {
1174         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1175                 Some(self.cmp(other))
1176         }
1177 }
1178
1179 // While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1180 // substantially when it is laid out at exactly 64 bytes.
1181 //
1182 // Thus, we use `#[repr(C)]` on the struct to force a suboptimal layout and check that it stays 64
1183 // bytes here.
1184 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1185 const _GRAPH_NODE_SMALL: usize = 64 - core::mem::size_of::<RouteGraphNode>();
1186 #[cfg(any(ldk_bench, not(any(test, fuzzing))))]
1187 const _GRAPH_NODE_FIXED_SIZE: usize = core::mem::size_of::<RouteGraphNode>() - 64;
1188
1189 /// A [`CandidateRouteHop::FirstHop`] entry.
1190 #[derive(Clone, Debug)]
1191 pub struct FirstHopCandidate<'a> {
1192         /// Channel details of the first hop
1193         ///
1194         /// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1195         /// has been funded and is able to pay), and accessor methods may panic otherwise.
1196         ///
1197         /// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1198         ///
1199         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1200         pub details: &'a ChannelDetails,
1201         /// The node id of the payer, which is also the source side of this candidate route hop.
1202         ///
1203         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1204         pub payer_node_id: &'a NodeId,
1205 }
1206
1207 /// A [`CandidateRouteHop::PublicHop`] entry.
1208 #[derive(Clone, Debug)]
1209 pub struct PublicHopCandidate<'a> {
1210         /// Information about the channel, including potentially its capacity and
1211         /// direction-specific information.
1212         ///
1213         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1214         pub info: DirectedChannelInfo<'a>,
1215         /// The short channel ID of the channel, i.e. the identifier by which we refer to this
1216         /// channel.
1217         pub short_channel_id: u64,
1218 }
1219
1220 /// A [`CandidateRouteHop::PrivateHop`] entry.
1221 #[derive(Clone, Debug)]
1222 pub struct PrivateHopCandidate<'a> {
1223         /// Information about the private hop communicated via BOLT 11.
1224         ///
1225         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1226         pub hint: &'a RouteHintHop,
1227         /// Node id of the next hop in BOLT 11 route hint.
1228         ///
1229         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1230         pub target_node_id: &'a NodeId
1231 }
1232
1233 /// A [`CandidateRouteHop::Blinded`] entry.
1234 #[derive(Clone, Debug)]
1235 pub struct BlindedPathCandidate<'a> {
1236         /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1237         /// hops.
1238         ///
1239         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1240         pub source_node_id: &'a NodeId,
1241         /// Information about the blinded path including the fee, HTLC amount limits, and
1242         /// cryptographic material required to build an HTLC through the given path.
1243         ///
1244         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1245         pub hint: &'a (BlindedPayInfo, BlindedPath),
1246         /// Index of the hint in the original list of blinded hints.
1247         ///
1248         /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1249         /// a short channel ID for this hop.
1250         hint_idx: usize,
1251 }
1252
1253 /// A [`CandidateRouteHop::OneHopBlinded`] entry.
1254 #[derive(Clone, Debug)]
1255 pub struct OneHopBlindedPathCandidate<'a> {
1256         /// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1257         /// hops.
1258         ///
1259         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1260         pub source_node_id: &'a NodeId,
1261         /// Information about the blinded path including the fee, HTLC amount limits, and
1262         /// cryptographic material required to build an HTLC terminating with the given path.
1263         ///
1264         /// Note that the [`BlindedPayInfo`] is ignored here.
1265         ///
1266         /// This is not exported to bindings users as lifetimes are not expressible in most languages.
1267         pub hint: &'a (BlindedPayInfo, BlindedPath),
1268         /// Index of the hint in the original list of blinded hints.
1269         ///
1270         /// This is used to cheaply uniquely identify this blinded path, even though we don't have
1271         /// a short channel ID for this hop.
1272         hint_idx: usize,
1273 }
1274
1275 /// A wrapper around the various hop representations.
1276 ///
1277 /// Can be used to examine the properties of a hop,
1278 /// potentially to decide whether to include it in a route.
1279 #[derive(Clone, Debug)]
1280 pub enum CandidateRouteHop<'a> {
1281         /// A hop from the payer, where the outbound liquidity is known.
1282         FirstHop(FirstHopCandidate<'a>),
1283         /// A hop found in the [`ReadOnlyNetworkGraph`].
1284         PublicHop(PublicHopCandidate<'a>),
1285         /// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1286         ///
1287         /// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1288         /// terminate at the payee.
1289         PrivateHop(PrivateHopCandidate<'a>),
1290         /// A blinded path which starts with an introduction point and ultimately terminates with the
1291         /// payee.
1292         ///
1293         /// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1294         /// `None` in this state.
1295         ///
1296         /// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1297         /// path, the full path is treated as a single [`CandidateRouteHop`].
1298         Blinded(BlindedPathCandidate<'a>),
1299         /// Similar to [`Self::Blinded`], but the path here only has one hop.
1300         ///
1301         /// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1302         /// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1303         /// payee's identity - it's the introduction point!
1304         ///
1305         /// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1306         /// to the hops *between* the introduction node and the destination.
1307         ///
1308         /// This primarily exists to track that we need to included a blinded path at the end of our
1309         /// [`Route`], even though it doesn't actually add an additional hop in the payment.
1310         OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1311 }
1312
1313 impl<'a> CandidateRouteHop<'a> {
1314         /// Returns the short channel ID for this hop, if one is known.
1315         ///
1316         /// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1317         /// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1318         ///
1319         /// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1320         /// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1321         /// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1322         /// (which is always true for channels which are funded and ready for use).
1323         ///
1324         /// In other words, this should always return `Some` as long as the candidate hop is not a
1325         /// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1326         ///
1327         /// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1328         /// define a global namespace.
1329         #[inline]
1330         fn short_channel_id(&self) -> Option<u64> {
1331                 match self {
1332                         CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1333                         CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1334                         CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1335                         CandidateRouteHop::Blinded(_) => None,
1336                         CandidateRouteHop::OneHopBlinded(_) => None,
1337                 }
1338         }
1339
1340         /// Returns the globally unique short channel ID for this hop, if one is known.
1341         ///
1342         /// This only returns `Some` if the channel is public (either our own, or one we've learned
1343         /// from the public network graph), and thus the short channel ID we have for this channel is
1344         /// globally unique and identifies this channel in a global namespace.
1345         #[inline]
1346         pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1347                 match self {
1348                         CandidateRouteHop::FirstHop(hop) => if hop.details.is_public { hop.details.short_channel_id } else { None },
1349                         CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1350                         CandidateRouteHop::PrivateHop(_) => None,
1351                         CandidateRouteHop::Blinded(_) => None,
1352                         CandidateRouteHop::OneHopBlinded(_) => None,
1353                 }
1354         }
1355
1356         // NOTE: This may alloc memory so avoid calling it in a hot code path.
1357         fn features(&self) -> ChannelFeatures {
1358                 match self {
1359                         CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1360                         CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1361                         CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1362                         CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1363                         CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1364                 }
1365         }
1366
1367         /// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1368         /// next-hop for an HTLC taking this hop.
1369         ///
1370         /// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1371         /// next-hop goes on chain with a payment preimage.
1372         #[inline]
1373         pub fn cltv_expiry_delta(&self) -> u32 {
1374                 match self {
1375                         CandidateRouteHop::FirstHop(_) => 0,
1376                         CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1377                         CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1378                         CandidateRouteHop::Blinded(hop) => hop.hint.0.cltv_expiry_delta as u32,
1379                         CandidateRouteHop::OneHopBlinded(_) => 0,
1380                 }
1381         }
1382
1383         /// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1384         #[inline]
1385         pub fn htlc_minimum_msat(&self) -> u64 {
1386                 match self {
1387                         CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1388                         CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1389                         CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1390                         CandidateRouteHop::Blinded(hop) => hop.hint.0.htlc_minimum_msat,
1391                         CandidateRouteHop::OneHopBlinded { .. } => 0,
1392                 }
1393         }
1394
1395         /// Returns the fees that must be paid to route an HTLC over this channel.
1396         #[inline]
1397         pub fn fees(&self) -> RoutingFees {
1398                 match self {
1399                         CandidateRouteHop::FirstHop(_) => RoutingFees {
1400                                 base_msat: 0, proportional_millionths: 0,
1401                         },
1402                         CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1403                         CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1404                         CandidateRouteHop::Blinded(hop) => {
1405                                 RoutingFees {
1406                                         base_msat: hop.hint.0.fee_base_msat,
1407                                         proportional_millionths: hop.hint.0.fee_proportional_millionths
1408                                 }
1409                         },
1410                         CandidateRouteHop::OneHopBlinded(_) =>
1411                                 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1412                 }
1413         }
1414
1415         /// Fetch the effective capacity of this hop.
1416         ///
1417         /// Note that this may be somewhat expensive, so calls to this should be limited and results
1418         /// cached!
1419         fn effective_capacity(&self) -> EffectiveCapacity {
1420                 match self {
1421                         CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1422                                 liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1423                         },
1424                         CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1425                         CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1426                                 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1427                         CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1428                                 EffectiveCapacity::Infinite,
1429                         CandidateRouteHop::Blinded(hop) =>
1430                                 EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.0.htlc_maximum_msat },
1431                         CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1432                 }
1433         }
1434
1435         /// Returns an ID describing the given hop.
1436         ///
1437         /// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1438         #[inline]
1439         fn id(&self) -> CandidateHopId {
1440                 match self {
1441                         CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1442                         CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1443                         _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1444                 }
1445         }
1446         fn blinded_path(&self) -> Option<&'a BlindedPath> {
1447                 match self {
1448                         CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1449                                 Some(&hint.1)
1450                         },
1451                         _ => None,
1452                 }
1453         }
1454         fn blinded_hint_idx(&self) -> Option<usize> {
1455                 match self {
1456                         Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1457                         Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1458                                 Some(*hint_idx)
1459                         },
1460                         _ => None,
1461                 }
1462         }
1463         /// Returns the source node id of current hop.
1464         ///
1465         /// Source node id refers to the node forwarding the HTLC through this hop.
1466         ///
1467         /// For [`Self::FirstHop`] we return payer's node id.
1468         #[inline]
1469         pub fn source(&self) -> NodeId {
1470                 match self {
1471                         CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1472                         CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1473                         CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1474                         CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1475                         CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1476                 }
1477         }
1478         /// Returns the target node id of this hop, if known.
1479         ///
1480         /// Target node id refers to the node receiving the HTLC after this hop.
1481         ///
1482         /// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1483         /// path is unknown.
1484         ///
1485         /// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1486         /// and such a return value would be somewhat nonsensical.
1487         #[inline]
1488         pub fn target(&self) -> Option<NodeId> {
1489                 match self {
1490                         CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1491                         CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1492                         CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1493                         CandidateRouteHop::Blinded(_) => None,
1494                         CandidateRouteHop::OneHopBlinded(_) => None,
1495                 }
1496         }
1497 }
1498
1499 /// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1500 ///
1501 /// For blinded paths, this ID is unique only within a given [`find_route`] call.
1502 ///
1503 /// For other hops, because SCIDs between private channels and public channels can conflict, this
1504 /// isn't guaranteed to be unique at all.
1505 ///
1506 /// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1507 /// difficult-to-use API.
1508 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1509 enum CandidateHopId {
1510         /// Contains (scid, src_node_id < target_node_id)
1511         Clear((u64, bool)),
1512         /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1513         Blinded(usize),
1514 }
1515
1516 #[inline]
1517 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1518         let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1519         match capacity {
1520                 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1521                 EffectiveCapacity::Infinite => u64::max_value(),
1522                 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1523                 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1524                         amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1525                 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1526                 // expected to have been generated from up-to-date capacity information.
1527                 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1528                 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1529                         cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1530         }
1531 }
1532
1533 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1534 -> bool where I1::Item: PartialEq<I2::Item> {
1535         loop {
1536                 let a = iter_a.next();
1537                 let b = iter_b.next();
1538                 if a.is_none() && b.is_none() { return true; }
1539                 if a.is_none() || b.is_none() { return false; }
1540                 if a.unwrap().ne(&b.unwrap()) { return false; }
1541         }
1542 }
1543
1544 /// It's useful to keep track of the hops associated with the fees required to use them,
1545 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1546 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1547 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1548 #[derive(Clone)]
1549 #[repr(C)] // Force fields to appear in the order we define them.
1550 struct PathBuildingHop<'a> {
1551         candidate: CandidateRouteHop<'a>,
1552         /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1553         /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1554         /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1555         /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1556         /// avoid processing them again.
1557         was_processed: bool,
1558         /// Used to compare channels when choosing the for routing.
1559         /// Includes paying for the use of a hop and the following hops, as well as
1560         /// an estimated cost of reaching this hop.
1561         /// Might get stale when fees are recomputed. Primarily for internal use.
1562         total_fee_msat: u64,
1563         /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1564         /// walk and may be invalid thereafter.
1565         path_htlc_minimum_msat: u64,
1566         /// All penalties incurred from this channel on the way to the destination, as calculated using
1567         /// channel scoring.
1568         path_penalty_msat: u64,
1569
1570         // The last 16 bytes are on the next cache line by default in glibc's malloc. Thus, we should
1571         // only place fields which are not hot there. Luckily, the next three fields are only read if
1572         // we end up on the selected path, and only in the final path layout phase, so we don't care
1573         // too much if reading them is slow.
1574
1575         fee_msat: u64,
1576
1577         /// All the fees paid *after* this channel on the way to the destination
1578         next_hops_fee_msat: u64,
1579         /// Fee paid for the use of the current channel (see candidate.fees()).
1580         /// The value will be actually deducted from the counterparty balance on the previous link.
1581         hop_use_fee_msat: u64,
1582
1583         #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1584         // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1585         // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1586         // value_contribution_msat, which requires tracking it here. See comments below where it is
1587         // used for more info.
1588         value_contribution_msat: u64,
1589 }
1590
1591 // Checks that the entries in the `find_route` `dist` map fit in (exactly) two standard x86-64
1592 // cache lines. Sadly, they're not guaranteed to actually lie on a cache line (and in fact,
1593 // generally won't, because at least glibc's malloc will align to a nice, big, round
1594 // boundary...plus 16), but at least it will reduce the amount of data we'll need to load.
1595 //
1596 // Note that these assertions only pass on somewhat recent rustc, and thus are gated on the
1597 // ldk_bench flag.
1598 #[cfg(ldk_bench)]
1599 const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<(NodeId, PathBuildingHop)>();
1600 #[cfg(ldk_bench)]
1601 const _NODE_MAP_SIZE_EXACTLY_CACHE_LINES: usize = core::mem::size_of::<(NodeId, PathBuildingHop)>() - 128;
1602
1603 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1604         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1605                 let mut debug_struct = f.debug_struct("PathBuildingHop");
1606                 debug_struct
1607                         .field("node_id", &self.candidate.target())
1608                         .field("short_channel_id", &self.candidate.short_channel_id())
1609                         .field("total_fee_msat", &self.total_fee_msat)
1610                         .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1611                         .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1612                         .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1613                         .field("path_penalty_msat", &self.path_penalty_msat)
1614                         .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1615                         .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1616                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1617                 let debug_struct = debug_struct
1618                         .field("value_contribution_msat", &self.value_contribution_msat);
1619                 debug_struct.finish()
1620         }
1621 }
1622
1623 // Instantiated with a list of hops with correct data in them collected during path finding,
1624 // an instance of this struct should be further modified only via given methods.
1625 #[derive(Clone)]
1626 struct PaymentPath<'a> {
1627         hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1628 }
1629
1630 impl<'a> PaymentPath<'a> {
1631         // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1632         fn get_value_msat(&self) -> u64 {
1633                 self.hops.last().unwrap().0.fee_msat
1634         }
1635
1636         fn get_path_penalty_msat(&self) -> u64 {
1637                 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1638         }
1639
1640         fn get_total_fee_paid_msat(&self) -> u64 {
1641                 if self.hops.len() < 1 {
1642                         return 0;
1643                 }
1644                 let mut result = 0;
1645                 // Can't use next_hops_fee_msat because it gets outdated.
1646                 for (i, (hop, _)) in self.hops.iter().enumerate() {
1647                         if i != self.hops.len() - 1 {
1648                                 result += hop.fee_msat;
1649                         }
1650                 }
1651                 return result;
1652         }
1653
1654         fn get_cost_msat(&self) -> u64 {
1655                 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1656         }
1657
1658         // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1659         // to change fees may result in an inconsistency.
1660         //
1661         // Sometimes we call this function right after constructing a path which is inconsistent in
1662         // that it the value being transferred has decreased while we were doing path finding, leading
1663         // to the fees being paid not lining up with the actual limits.
1664         //
1665         // Note that this function is not aware of the available_liquidity limit, and thus does not
1666         // support increasing the value being transferred beyond what was selected during the initial
1667         // routing passes.
1668         //
1669         // Returns the amount that this path contributes to the total payment value, which may be greater
1670         // than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1671         fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1672                 let mut extra_contribution_msat = 0;
1673                 let mut total_fee_paid_msat = 0 as u64;
1674                 for i in (0..self.hops.len()).rev() {
1675                         let last_hop = i == self.hops.len() - 1;
1676
1677                         // For non-last-hop, this value will represent the fees paid on the current hop. It
1678                         // will consist of the fees for the use of the next hop, and extra fees to match
1679                         // htlc_minimum_msat of the current channel. Last hop is handled separately.
1680                         let mut cur_hop_fees_msat = 0;
1681                         if !last_hop {
1682                                 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1683                         }
1684
1685                         let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1686                         cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1687                         cur_hop.path_penalty_msat += extra_contribution_msat;
1688                         // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1689                         // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1690                         // set it too high just to maliciously take more fees by exploiting this
1691                         // match htlc_minimum_msat logic.
1692                         let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1693                         if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1694                                 // Note that there is a risk that *previous hops* (those closer to us, as we go
1695                                 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1696                                 //
1697                                 // This might make us end up with a broken route, although this should be super-rare
1698                                 // in practice, both because of how healthy channels look like, and how we pick
1699                                 // channels in add_entry.
1700                                 // Also, this can't be exploited more heavily than *announce a free path and fail
1701                                 // all payments*.
1702                                 cur_hop_transferred_amount_msat += extra_fees_msat;
1703
1704                                 // We remember and return the extra fees on the final hop to allow accounting for
1705                                 // them in the path's value contribution.
1706                                 if last_hop {
1707                                         extra_contribution_msat = extra_fees_msat;
1708                                 } else {
1709                                         total_fee_paid_msat += extra_fees_msat;
1710                                         cur_hop_fees_msat += extra_fees_msat;
1711                                 }
1712                         }
1713
1714                         if last_hop {
1715                                 // Final hop is a special case: it usually has just value_msat (by design), but also
1716                                 // it still could overpay for the htlc_minimum_msat.
1717                                 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1718                         } else {
1719                                 // Propagate updated fees for the use of the channels to one hop back, where they
1720                                 // will be actually paid (fee_msat). The last hop is handled above separately.
1721                                 cur_hop.fee_msat = cur_hop_fees_msat;
1722                         }
1723
1724                         // Fee for the use of the current hop which will be deducted on the previous hop.
1725                         // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1726                         // this channel is free for us.
1727                         if i != 0 {
1728                                 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1729                                         cur_hop.hop_use_fee_msat = new_fee;
1730                                         total_fee_paid_msat += new_fee;
1731                                 } else {
1732                                         // It should not be possible because this function is called only to reduce the
1733                                         // value. In that case, compute_fee was already called with the same fees for
1734                                         // larger amount and there was no overflow.
1735                                         unreachable!();
1736                                 }
1737                         }
1738                 }
1739                 value_msat + extra_contribution_msat
1740         }
1741 }
1742
1743 #[inline(always)]
1744 /// Calculate the fees required to route the given amount over a channel with the given fees.
1745 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1746         amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1747                 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1748 }
1749
1750 #[inline(always)]
1751 /// Calculate the fees required to route the given amount over a channel with the given fees,
1752 /// saturating to [`u64::max_value`].
1753 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1754         amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1755                 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1756                 .saturating_add(channel_fees.base_msat as u64)
1757 }
1758
1759 /// The default `features` we assume for a node in a route, when no `features` are known about that
1760 /// specific node.
1761 ///
1762 /// Default features are:
1763 /// * variable_length_onion_optional
1764 fn default_node_features() -> NodeFeatures {
1765         let mut features = NodeFeatures::empty();
1766         features.set_variable_length_onion_optional();
1767         features
1768 }
1769
1770 struct LoggedPayeePubkey(Option<PublicKey>);
1771 impl fmt::Display for LoggedPayeePubkey {
1772         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1773                 match self.0 {
1774                         Some(pk) => {
1775                                 "payee node id ".fmt(f)?;
1776                                 pk.fmt(f)
1777                         },
1778                         None => {
1779                                 "blinded payee".fmt(f)
1780                         },
1781                 }
1782         }
1783 }
1784
1785 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1786 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1787         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1788                 match self.0 {
1789                         CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1790                                 "blinded route hint with introduction node ".fmt(f)?;
1791                                 match &hint.1.introduction_node {
1792                                         IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
1793                                         IntroductionNode::DirectedShortChannelId(direction, scid) => {
1794                                                 match direction {
1795                                                         Direction::NodeOne => {
1796                                                                 write!(f, "one on channel with SCID {}", scid)?;
1797                                                         },
1798                                                         Direction::NodeTwo => {
1799                                                                 write!(f, "two on channel with SCID {}", scid)?;
1800                                                         },
1801                                                 }
1802                                         }
1803                                 }
1804                                 " and blinding point ".fmt(f)?;
1805                                 hint.1.blinding_point.fmt(f)
1806                         },
1807                         CandidateRouteHop::FirstHop(_) => {
1808                                 "first hop with SCID ".fmt(f)?;
1809                                 self.0.short_channel_id().unwrap().fmt(f)
1810                         },
1811                         CandidateRouteHop::PrivateHop(_) => {
1812                                 "route hint with SCID ".fmt(f)?;
1813                                 self.0.short_channel_id().unwrap().fmt(f)
1814                         },
1815                         _ => {
1816                                 "SCID ".fmt(f)?;
1817                                 self.0.short_channel_id().unwrap().fmt(f)
1818                         },
1819                 }
1820         }
1821 }
1822
1823 #[inline]
1824 fn sort_first_hop_channels(
1825         channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1826         recommended_value_msat: u64, our_node_pubkey: &PublicKey
1827 ) {
1828         // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1829         // most like to use.
1830         //
1831         // First, if channels are below `recommended_value_msat`, sort them in descending order,
1832         // preferring larger channels to avoid splitting the payment into more MPP parts than is
1833         // required.
1834         //
1835         // Second, because simply always sorting in descending order would always use our largest
1836         // available outbound capacity, needlessly fragmenting our available channel capacities,
1837         // sort channels above `recommended_value_msat` in ascending order, preferring channels
1838         // which have enough, but not too much, capacity for the payment.
1839         //
1840         // Available outbound balances factor in liquidity already reserved for previously found paths.
1841         channels.sort_unstable_by(|chan_a, chan_b| {
1842                 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1843                         .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1844                         our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1845                 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1846                         .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1847                         our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1848                 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1849                         // Sort in descending order
1850                         chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1851                 } else {
1852                         // Sort in ascending order
1853                         chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1854                 }
1855         });
1856 }
1857
1858 /// Finds a route from us (payer) to the given target node (payee).
1859 ///
1860 /// If the payee provided features in their invoice, they should be provided via the `payee` field
1861 /// in the given [`RouteParameters::payment_params`].
1862 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1863 ///
1864 /// Private routing paths between a public node and the target may be included in the `payee` field
1865 /// of [`RouteParameters::payment_params`].
1866 ///
1867 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1868 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1869 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1870 ///
1871 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1872 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1873 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1874 ///
1875 /// # Panics
1876 ///
1877 /// Panics if first_hops contains channels without `short_channel_id`s;
1878 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1879 ///
1880 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1881 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1882 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1883 pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
1884         our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1885         network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1886         scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1887 ) -> Result<Route, LightningError>
1888 where L::Target: Logger, GL::Target: Logger {
1889         let graph_lock = network_graph.read_only();
1890         let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
1891                 scorer, score_params, random_seed_bytes)?;
1892         add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1893         Ok(route)
1894 }
1895
1896 pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
1897         our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
1898         first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
1899         _random_seed_bytes: &[u8; 32]
1900 ) -> Result<Route, LightningError>
1901 where L::Target: Logger {
1902
1903         let payment_params = &route_params.payment_params;
1904         let max_path_length = core::cmp::min(payment_params.max_path_length, MAX_PATH_LENGTH_ESTIMATE);
1905         let final_value_msat = route_params.final_value_msat;
1906         // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1907         // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1908         // so use a dummy id for this in the blinded case.
1909         let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1910         const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1911         let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1912         let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1913         let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1914
1915         if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1916                 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1917         }
1918         if our_node_id == maybe_dummy_payee_node_id {
1919                 return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
1920         }
1921
1922         if final_value_msat > MAX_VALUE_MSAT {
1923                 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1924         }
1925
1926         if final_value_msat == 0 {
1927                 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1928         }
1929
1930         let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter()
1931                 .map(|(_, path)| path.public_introduction_node_id(network_graph))
1932                 .collect::<Vec<_>>();
1933         match &payment_params.payee {
1934                 Payee::Clear { route_hints, node_id, .. } => {
1935                         for route in route_hints.iter() {
1936                                 for hop in &route.0 {
1937                                         if hop.src_node_id == *node_id {
1938                                                 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1939                                         }
1940                                 }
1941                         }
1942                 },
1943                 Payee::Blinded { route_hints, .. } => {
1944                         if introduction_node_id_cache.iter().all(|introduction_node_id| *introduction_node_id == Some(&our_node_id)) {
1945                                 return Err(LightningError{err: "Cannot generate a route to blinded paths if we are the introduction node to all of them".to_owned(), action: ErrorAction::IgnoreError});
1946                         }
1947                         for ((_, blinded_path), introduction_node_id) in route_hints.iter().zip(introduction_node_id_cache.iter()) {
1948                                 if blinded_path.blinded_hops.len() == 0 {
1949                                         return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1950                                 } else if *introduction_node_id == Some(&our_node_id) {
1951                                         log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1952                                 } else if blinded_path.blinded_hops.len() == 1 &&
1953                                         route_hints
1954                                                 .iter().zip(introduction_node_id_cache.iter())
1955                                                 .filter(|((_, p), _)| p.blinded_hops.len() == 1)
1956                                                 .any(|(_, p_introduction_node_id)| p_introduction_node_id != introduction_node_id)
1957                                 {
1958                                         return Err(LightningError{err: format!("1-hop blinded paths must all have matching introduction node ids"), action: ErrorAction::IgnoreError});
1959                                 }
1960                         }
1961                 }
1962         }
1963         let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1964         if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1965                 return Err(LightningError{err: "Can't find a route where the maximum total CLTV expiry delta is below the final CLTV expiry.".to_owned(), action: ErrorAction::IgnoreError});
1966         }
1967
1968         // The general routing idea is the following:
1969         // 1. Fill first/last hops communicated by the caller.
1970         // 2. Attempt to construct a path from payer to payee for transferring
1971         //    any ~sufficient (described later) value.
1972         //    If succeed, remember which channels were used and how much liquidity they have available,
1973         //    so that future paths don't rely on the same liquidity.
1974         // 3. Proceed to the next step if:
1975         //    - we hit the recommended target value;
1976         //    - OR if we could not construct a new path. Any next attempt will fail too.
1977         //    Otherwise, repeat step 2.
1978         // 4. See if we managed to collect paths which aggregately are able to transfer target value
1979         //    (not recommended value).
1980         // 5. If yes, proceed. If not, fail routing.
1981         // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1982         //    transferred up to the transfer target value.
1983         // 7. Reduce the value of the last path until we are sending only the target value.
1984         // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1985         //    them so that we're not sending two HTLCs along the same path.
1986
1987         // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1988         // distance from the payee
1989         //
1990         // We are not a faithful Dijkstra's implementation because we can change values which impact
1991         // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1992         // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1993         // the value we are currently attempting to send over a path, we simply reduce the value being
1994         // sent along the path for any hops after that channel. This may imply that later fees (which
1995         // we've already tabulated) are lower because a smaller value is passing through the channels
1996         // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1997         // channels which were selected earlier (and which may still be used for other paths without a
1998         // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1999         // de-preferenced.
2000         //
2001         // One potentially problematic case for this algorithm would be if there are many
2002         // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
2003         // graph walking), we may never find a path which is not liquidity-limited and has lower
2004         // proportional fee (and only lower absolute fee when considering the ultimate value sent).
2005         // Because we only consider paths with at least 5% of the total value being sent, the damage
2006         // from such a case should be limited, however this could be further reduced in the future by
2007         // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
2008         // limits for the purposes of fee calculation.
2009         //
2010         // Alternatively, we could store more detailed path information in the heap (targets, below)
2011         // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
2012         // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
2013         // and practically (as we would need to store dynamically-allocated path information in heap
2014         // objects, increasing malloc traffic and indirect memory access significantly). Further, the
2015         // results of such an algorithm would likely be biased towards lower-value paths.
2016         //
2017         // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
2018         // outside of our current search value, running a path search more times to gather candidate
2019         // paths at different values. While this may be acceptable, further path searches may increase
2020         // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
2021         // graph for candidate paths, calculating the maximum value which can realistically be sent at
2022         // the same time, remaining generic across different payment values.
2023
2024         let network_channels = network_graph.channels();
2025         let network_nodes = network_graph.nodes();
2026
2027         if payment_params.max_path_count == 0 {
2028                 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
2029         }
2030
2031         // Allow MPP only if we have a features set from somewhere that indicates the payee supports
2032         // it. If the payee supports it they're supposed to include it in the invoice, so that should
2033         // work reliably.
2034         let allow_mpp = if payment_params.max_path_count == 1 {
2035                 false
2036         } else if payment_params.payee.supports_basic_mpp() {
2037                 true
2038         } else if let Some(payee) = payee_node_id_opt {
2039                 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
2040                         |info| info.features().supports_basic_mpp()))
2041         } else { false };
2042
2043         let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
2044
2045         let first_hop_count = first_hops.map(|hops| hops.len()).unwrap_or(0);
2046         log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph of {} nodes and {} channels with a fee limit of {} msat",
2047                 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
2048                 if allow_mpp { "with" } else { "without" },
2049                 first_hop_count, if first_hops.is_some() { "" } else { "not " },
2050                 network_graph.nodes().len(), network_graph.channels().len(),
2051                 max_total_routing_fee_msat);
2052
2053         if first_hop_count < 10 {
2054                 if let Some(hops) = first_hops {
2055                         for hop in hops {
2056                                 log_trace!(
2057                                         logger,
2058                                         " First hop through {}/{} can send between {}msat and {}msat (inclusive).",
2059                                         hop.counterparty.node_id,
2060                                         hop.get_outbound_payment_scid().unwrap_or(0),
2061                                         hop.next_outbound_htlc_minimum_msat,
2062                                         hop.next_outbound_htlc_limit_msat
2063                                 );
2064                         }
2065                 }
2066         }
2067
2068         // Step (1).
2069         // Prepare the data we'll use for payee-to-payer search by
2070         // inserting first hops suggested by the caller as targets.
2071         // Our search will then attempt to reach them while traversing from the payee node.
2072         let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
2073                 hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2074         if let Some(hops) = first_hops {
2075                 for chan in hops {
2076                         if chan.get_outbound_payment_scid().is_none() {
2077                                 panic!("first_hops should be filled in with usable channels, not pending ones");
2078                         }
2079                         if chan.counterparty.node_id == *our_node_pubkey {
2080                                 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2081                         }
2082                         first_hop_targets
2083                                 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
2084                                 .or_insert(Vec::new())
2085                                 .push(chan);
2086                 }
2087                 if first_hop_targets.is_empty() {
2088                         return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2089                 }
2090         }
2091
2092         let mut private_hop_key_cache = hash_map_with_capacity(
2093                 payment_params.payee.unblinded_route_hints().iter().map(|path| path.0.len()).sum()
2094         );
2095
2096         // Because we store references to private hop node_ids in `dist`, below, we need them to exist
2097         // (as `NodeId`, not `PublicKey`) for the lifetime of `dist`. Thus, we calculate all the keys
2098         // we'll need here and simply fetch them when routing.
2099         private_hop_key_cache.insert(maybe_dummy_payee_pk, NodeId::from_pubkey(&maybe_dummy_payee_pk));
2100         for route in payment_params.payee.unblinded_route_hints().iter() {
2101                 for hop in route.0.iter() {
2102                         private_hop_key_cache.insert(hop.src_node_id, NodeId::from_pubkey(&hop.src_node_id));
2103                 }
2104         }
2105
2106         // The main heap containing all candidate next-hops sorted by their score (max(fee,
2107         // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2108         // adding duplicate entries when we find a better path to a given node.
2109         let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2110
2111         // Map from node_id to information about the best current path to that node, including feerate
2112         // information.
2113         let mut dist: HashMap<NodeId, PathBuildingHop> = hash_map_with_capacity(network_nodes.len());
2114
2115         // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2116         // indicating that we may wish to try again with a higher value, potentially paying to meet an
2117         // htlc_minimum with extra fees while still finding a cheaper path.
2118         let mut hit_minimum_limit;
2119
2120         // When arranging a route, we select multiple paths so that we can make a multi-path payment.
2121         // We start with a path_value of the exact amount we want, and if that generates a route we may
2122         // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2123         // amount we want in total across paths, selecting the best subset at the end.
2124         const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2125         let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2126         let mut path_value_msat = final_value_msat;
2127
2128         // Routing Fragmentation Mitigation heuristic:
2129         //
2130         // Routing fragmentation across many payment paths increases the overall routing
2131         // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2132         // Taking too many smaller paths also increases the chance of payment failure.
2133         // Thus to avoid this effect, we require from our collected links to provide
2134         // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2135         // This requirement is currently set to be 1/max_path_count of the payment
2136         // value to ensure we only ever return routes that do not violate this limit.
2137         let minimal_value_contribution_msat: u64 = if allow_mpp {
2138                 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2139         } else {
2140                 final_value_msat
2141         };
2142
2143         // When we start collecting routes we enforce the max_channel_saturation_power_of_half
2144         // requirement strictly. After we've collected enough (or if we fail to find new routes) we
2145         // drop the requirement by setting this to 0.
2146         let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2147
2148         // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2149         // determine if the channel can be used by additional MPP paths or to inform path finding
2150         // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2151         // is used. Hence, liquidity used in one direction will not offset any used in the opposite
2152         // direction.
2153         let mut used_liquidities: HashMap<CandidateHopId, u64> =
2154                 hash_map_with_capacity(network_nodes.len());
2155
2156         // Keeping track of how much value we already collected across other paths. Helps to decide
2157         // when we want to stop looking for new paths.
2158         let mut already_collected_value_msat = 0;
2159
2160         for (_, channels) in first_hop_targets.iter_mut() {
2161                 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2162                         our_node_pubkey);
2163         }
2164
2165         log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2166                 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2167
2168         // Remember how many candidates we ignored to allow for some logging afterwards.
2169         let mut num_ignored_value_contribution: u32 = 0;
2170         let mut num_ignored_path_length_limit: u32 = 0;
2171         let mut num_ignored_cltv_delta_limit: u32 = 0;
2172         let mut num_ignored_previously_failed: u32 = 0;
2173         let mut num_ignored_total_fee_limit: u32 = 0;
2174         let mut num_ignored_avoid_overpayment: u32 = 0;
2175         let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2176
2177         macro_rules! add_entry {
2178                 // Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2179                 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2180                 // since that value has to be transferred over this channel.
2181                 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2182                 ( $candidate: expr, $next_hops_fee_msat: expr,
2183                         $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2184                         $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2185                         // We "return" whether we updated the path at the end, and how much we can route via
2186                         // this channel, via this:
2187                         let mut hop_contribution_amt_msat = None;
2188                         // Channels to self should not be used. This is more of belt-and-suspenders, because in
2189                         // practice these cases should be caught earlier:
2190                         // - for regular channels at channel announcement (TODO)
2191                         // - for first and last hops early in get_route
2192                         let src_node_id = $candidate.source();
2193                         if Some(src_node_id) != $candidate.target() {
2194                                 let scid_opt = $candidate.short_channel_id();
2195                                 let effective_capacity = $candidate.effective_capacity();
2196                                 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2197
2198                                 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2199                                 // It may be misleading because we might later choose to reduce the value transferred
2200                                 // over these channels, and the channel which was insufficient might become sufficient.
2201                                 // Worst case: we drop a good channel here because it can't cover the high following
2202                                 // fees caused by one expensive channel, but then this channel could have been used
2203                                 // if the amount being transferred over this path is lower.
2204                                 // We do this for now, but this is a subject for removal.
2205                                 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2206                                         let used_liquidity_msat = used_liquidities
2207                                                 .get(&$candidate.id())
2208                                                 .map_or(0, |used_liquidity_msat| {
2209                                                         available_value_contribution_msat = available_value_contribution_msat
2210                                                                 .saturating_sub(*used_liquidity_msat);
2211                                                         *used_liquidity_msat
2212                                                 });
2213
2214                                         // Verify the liquidity offered by this channel complies to the minimal contribution.
2215                                         let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
2216                                         // Do not consider candidate hops that would exceed the maximum path length.
2217                                         let path_length_to_node = $next_hops_path_length
2218                                                 + if $candidate.blinded_hint_idx().is_some() { 0 } else { 1 };
2219                                         let exceeds_max_path_length = path_length_to_node > max_path_length;
2220
2221                                         // Do not consider candidates that exceed the maximum total cltv expiry limit.
2222                                         // In order to already account for some of the privacy enhancing random CLTV
2223                                         // expiry delta offset we add on top later, we subtract a rough estimate
2224                                         // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2225                                         let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2226                                                 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2227                                                 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
2228                                         let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2229                                                 .saturating_add($candidate.cltv_expiry_delta());
2230                                         let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
2231
2232                                         let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2233                                         // Includes paying fees for the use of the following channels.
2234                                         let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2235                                                 Some(result) => result,
2236                                                 // Can't overflow due to how the values were computed right above.
2237                                                 None => unreachable!(),
2238                                         };
2239                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2240                                         let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
2241                                                 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2242
2243                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2244                                         let may_overpay_to_meet_path_minimum_msat =
2245                                                 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
2246                                                   recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
2247                                                  (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2248                                                   recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
2249
2250                                         let payment_failed_on_this_channel = match scid_opt {
2251                                                 Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2252                                                 None => match $candidate.blinded_hint_idx() {
2253                                                         Some(idx) => {
2254                                                                 payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2255                                                         },
2256                                                         None => false,
2257                                                 },
2258                                         };
2259
2260                                         let (should_log_candidate, first_hop_details) = match $candidate {
2261                                                 CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2262                                                 CandidateRouteHop::PrivateHop(_) => (true, None),
2263                                                 CandidateRouteHop::Blinded(_) => (true, None),
2264                                                 CandidateRouteHop::OneHopBlinded(_) => (true, None),
2265                                                 _ => (false, None),
2266                                         };
2267
2268                                         // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2269                                         // bother considering this channel. If retrying with recommended_value_msat may
2270                                         // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2271                                         // around again with a higher amount.
2272                                         if !contributes_sufficient_value {
2273                                                 if should_log_candidate {
2274                                                         log_trace!(logger, "Ignoring {} due to insufficient value contribution (channel max {:?}).",
2275                                                                 LoggedCandidateHop(&$candidate),
2276                                                                 effective_capacity);
2277                                                 }
2278                                                 num_ignored_value_contribution += 1;
2279                                         } else if exceeds_max_path_length {
2280                                                 if should_log_candidate {
2281                                                         log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2282                                                 }
2283                                                 num_ignored_path_length_limit += 1;
2284                                         } else if exceeds_cltv_delta_limit {
2285                                                 if should_log_candidate {
2286                                                         log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2287
2288                                                         if let Some(_) = first_hop_details {
2289                                                                 log_trace!(logger,
2290                                                                         "First hop candidate cltv_expiry_delta: {}. Limit: {}",
2291                                                                         hop_total_cltv_delta,
2292                                                                         max_total_cltv_expiry_delta,
2293                                                                 );
2294                                                         }
2295                                                 }
2296                                                 num_ignored_cltv_delta_limit += 1;
2297                                         } else if payment_failed_on_this_channel {
2298                                                 if should_log_candidate {
2299                                                         log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2300                                                 }
2301                                                 num_ignored_previously_failed += 1;
2302                                         } else if may_overpay_to_meet_path_minimum_msat {
2303                                                 if should_log_candidate {
2304                                                         log_trace!(logger,
2305                                                                 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit ({}).",
2306                                                                 LoggedCandidateHop(&$candidate), $candidate.htlc_minimum_msat());
2307                                                 }
2308                                                 num_ignored_avoid_overpayment += 1;
2309                                                 hit_minimum_limit = true;
2310                                         } else if over_path_minimum_msat {
2311                                                 // Note that low contribution here (limited by available_liquidity_msat)
2312                                                 // might violate htlc_minimum_msat on the hops which are next along the
2313                                                 // payment path (upstream to the payee). To avoid that, we recompute
2314                                                 // path fees knowing the final path contribution after constructing it.
2315                                                 let curr_min = cmp::max(
2316                                                         $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
2317                                                 );
2318                                                 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
2319                                                         .saturating_add(curr_min);
2320                                                 let hm_entry = dist.entry(src_node_id);
2321                                                 let old_entry = hm_entry.or_insert_with(|| {
2322                                                         // If there was previously no known way to access the source node
2323                                                         // (recall it goes payee-to-payer) of short_channel_id, first add a
2324                                                         // semi-dummy record just to compute the fees to reach the source node.
2325                                                         // This will affect our decision on selecting short_channel_id
2326                                                         // as a way to reach the $candidate.target() node.
2327                                                         PathBuildingHop {
2328                                                                 candidate: $candidate.clone(),
2329                                                                 fee_msat: 0,
2330                                                                 next_hops_fee_msat: u64::max_value(),
2331                                                                 hop_use_fee_msat: u64::max_value(),
2332                                                                 total_fee_msat: u64::max_value(),
2333                                                                 path_htlc_minimum_msat,
2334                                                                 path_penalty_msat: u64::max_value(),
2335                                                                 was_processed: false,
2336                                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2337                                                                 value_contribution_msat,
2338                                                         }
2339                                                 });
2340
2341                                                 #[allow(unused_mut)] // We only use the mut in cfg(test)
2342                                                 let mut should_process = !old_entry.was_processed;
2343                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2344                                                 {
2345                                                         // In test/fuzzing builds, we do extra checks to make sure the skipping
2346                                                         // of already-seen nodes only happens in cases we expect (see below).
2347                                                         if !should_process { should_process = true; }
2348                                                 }
2349
2350                                                 if should_process {
2351                                                         let mut hop_use_fee_msat = 0;
2352                                                         let mut total_fee_msat: u64 = $next_hops_fee_msat;
2353
2354                                                         // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2355                                                         // will have the same effective-fee
2356                                                         if src_node_id != our_node_id {
2357                                                                 // Note that `u64::max_value` means we'll always fail the
2358                                                                 // `old_entry.total_fee_msat > total_fee_msat` check below
2359                                                                 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
2360                                                                 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2361                                                         }
2362
2363                                                         // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2364                                                         if total_fee_msat > max_total_routing_fee_msat {
2365                                                                 if should_log_candidate {
2366                                                                         log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
2367
2368                                                                         if let Some(_) = first_hop_details {
2369                                                                                 log_trace!(logger,
2370                                                                                         "First hop candidate routing fee: {}. Limit: {}",
2371                                                                                         total_fee_msat,
2372                                                                                         max_total_routing_fee_msat,
2373                                                                                 );
2374                                                                         }
2375                                                                 }
2376                                                                 num_ignored_total_fee_limit += 1;
2377                                                         } else {
2378                                                                 let channel_usage = ChannelUsage {
2379                                                                         amount_msat: amount_to_transfer_over_msat,
2380                                                                         inflight_htlc_msat: used_liquidity_msat,
2381                                                                         effective_capacity,
2382                                                                 };
2383                                                                 let channel_penalty_msat =
2384                                                                         scorer.channel_penalty_msat($candidate,
2385                                                                                 channel_usage,
2386                                                                                 score_params);
2387                                                                 let path_penalty_msat = $next_hops_path_penalty_msat
2388                                                                         .saturating_add(channel_penalty_msat);
2389
2390                                                                 // Update the way of reaching $candidate.source()
2391                                                                 // with the given short_channel_id (from $candidate.target()),
2392                                                                 // if this way is cheaper than the already known
2393                                                                 // (considering the cost to "reach" this channel from the route destination,
2394                                                                 // the cost of using this channel,
2395                                                                 // and the cost of routing to the source node of this channel).
2396                                                                 // Also, consider that htlc_minimum_msat_difference, because we might end up
2397                                                                 // paying it. Consider the following exploit:
2398                                                                 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2399                                                                 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2400                                                                 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2401                                                                 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2402                                                                 // to this channel.
2403                                                                 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2404                                                                 // but it may require additional tracking - we don't want to double-count
2405                                                                 // the fees included in $next_hops_path_htlc_minimum_msat, but also
2406                                                                 // can't use something that may decrease on future hops.
2407                                                                 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2408                                                                         .saturating_add(old_entry.path_penalty_msat);
2409                                                                 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2410                                                                         .saturating_add(path_penalty_msat);
2411
2412                                                                 if !old_entry.was_processed && new_cost < old_cost {
2413                                                                         let new_graph_node = RouteGraphNode {
2414                                                                                 node_id: src_node_id,
2415                                                                                 score: cmp::max(total_fee_msat, path_htlc_minimum_msat).saturating_add(path_penalty_msat),
2416                                                                                 total_cltv_delta: hop_total_cltv_delta,
2417                                                                                 value_contribution_msat,
2418                                                                                 path_length_to_node,
2419                                                                         };
2420                                                                         targets.push(new_graph_node);
2421                                                                         old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2422                                                                         old_entry.hop_use_fee_msat = hop_use_fee_msat;
2423                                                                         old_entry.total_fee_msat = total_fee_msat;
2424                                                                         old_entry.candidate = $candidate.clone();
2425                                                                         old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2426                                                                         old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2427                                                                         old_entry.path_penalty_msat = path_penalty_msat;
2428                                                                         #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2429                                                                         {
2430                                                                                 old_entry.value_contribution_msat = value_contribution_msat;
2431                                                                         }
2432                                                                         hop_contribution_amt_msat = Some(value_contribution_msat);
2433                                                                 } else if old_entry.was_processed && new_cost < old_cost {
2434                                                                         #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2435                                                                         {
2436                                                                                 // If we're skipping processing a node which was previously
2437                                                                                 // processed even though we found another path to it with a
2438                                                                                 // cheaper fee, check that it was because the second path we
2439                                                                                 // found (which we are processing now) has a lower value
2440                                                                                 // contribution due to an HTLC minimum limit.
2441                                                                                 //
2442                                                                                 // e.g. take a graph with two paths from node 1 to node 2, one
2443                                                                                 // through channel A, and one through channel B. Channel A and
2444                                                                                 // B are both in the to-process heap, with their scores set by
2445                                                                                 // a higher htlc_minimum than fee.
2446                                                                                 // Channel A is processed first, and the channels onwards from
2447                                                                                 // node 1 are added to the to-process heap. Thereafter, we pop
2448                                                                                 // Channel B off of the heap, note that it has a much more
2449                                                                                 // restrictive htlc_maximum_msat, and recalculate the fees for
2450                                                                                 // all of node 1's channels using the new, reduced, amount.
2451                                                                                 //
2452                                                                                 // This would be bogus - we'd be selecting a higher-fee path
2453                                                                                 // with a lower htlc_maximum_msat instead of the one we'd
2454                                                                                 // already decided to use.
2455                                                                                 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2456                                                                                 debug_assert!(
2457                                                                                         value_contribution_msat + path_penalty_msat <
2458                                                                                         old_entry.value_contribution_msat + old_entry.path_penalty_msat
2459                                                                                 );
2460                                                                         }
2461                                                                 }
2462                                                         }
2463                                                 }
2464                                         } else {
2465                                                 if should_log_candidate {
2466                                                         log_trace!(logger,
2467                                                                 "Ignoring {} due to its htlc_minimum_msat limit.",
2468                                                                 LoggedCandidateHop(&$candidate));
2469
2470                                                         if let Some(details) = first_hop_details {
2471                                                                 log_trace!(logger,
2472                                                                         "First hop candidate next_outbound_htlc_minimum_msat: {}",
2473                                                                         details.next_outbound_htlc_minimum_msat,
2474                                                                 );
2475                                                         }
2476                                                 }
2477                                                 num_ignored_htlc_minimum_msat_limit += 1;
2478                                         }
2479                                 }
2480                         }
2481                         hop_contribution_amt_msat
2482                 } }
2483         }
2484
2485         let default_node_features = default_node_features();
2486
2487         // Find ways (channels with destination) to reach a given node and store them
2488         // in the corresponding data structures (routing graph etc).
2489         // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2490         // meaning how much will be paid in fees after this node (to the best of our knowledge).
2491         // This data can later be helpful to optimize routing (pay lower fees).
2492         macro_rules! add_entries_to_cheapest_to_target_node {
2493                 ( $node: expr, $node_id: expr, $next_hops_value_contribution: expr,
2494                   $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2495                         let fee_to_target_msat;
2496                         let next_hops_path_htlc_minimum_msat;
2497                         let next_hops_path_penalty_msat;
2498                         let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2499                                 let was_processed = elem.was_processed;
2500                                 elem.was_processed = true;
2501                                 fee_to_target_msat = elem.total_fee_msat;
2502                                 next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2503                                 next_hops_path_penalty_msat = elem.path_penalty_msat;
2504                                 was_processed
2505                         } else {
2506                                 // Entries are added to dist in add_entry!() when there is a channel from a node.
2507                                 // Because there are no channels from payee, it will not have a dist entry at this point.
2508                                 // If we're processing any other node, it is always be the result of a channel from it.
2509                                 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2510                                 fee_to_target_msat = 0;
2511                                 next_hops_path_htlc_minimum_msat = 0;
2512                                 next_hops_path_penalty_msat = 0;
2513                                 false
2514                         };
2515
2516                         if !skip_node {
2517                                 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2518                                         for details in first_channels {
2519                                                 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2520                                                         details, payer_node_id: &our_node_id,
2521                                                 });
2522                                                 add_entry!(&candidate, fee_to_target_msat,
2523                                                         $next_hops_value_contribution,
2524                                                         next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2525                                                         $next_hops_cltv_delta, $next_hops_path_length);
2526                                         }
2527                                 }
2528
2529                                 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2530                                         &node_info.features()
2531                                 } else {
2532                                         &default_node_features
2533                                 };
2534
2535                                 if !features.requires_unknown_bits() {
2536                                         for chan_id in $node.channels.iter() {
2537                                                 let chan = network_channels.get(chan_id).unwrap();
2538                                                 if !chan.features.requires_unknown_bits() {
2539                                                         if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2540                                                                 if first_hops.is_none() || *source != our_node_id {
2541                                                                         if directed_channel.direction().enabled {
2542                                                                                 let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2543                                                                                         info: directed_channel,
2544                                                                                         short_channel_id: *chan_id,
2545                                                                                 });
2546                                                                                 add_entry!(&candidate,
2547                                                                                         fee_to_target_msat,
2548                                                                                         $next_hops_value_contribution,
2549                                                                                         next_hops_path_htlc_minimum_msat,
2550                                                                                         next_hops_path_penalty_msat,
2551                                                                                         $next_hops_cltv_delta, $next_hops_path_length);
2552                                                                         }
2553                                                                 }
2554                                                         }
2555                                                 }
2556                                         }
2557                                 }
2558                         }
2559                 };
2560         }
2561
2562         let mut payment_paths = Vec::<PaymentPath>::new();
2563
2564         // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2565         'paths_collection: loop {
2566                 // For every new path, start from scratch, except for used_liquidities, which
2567                 // helps to avoid reusing previously selected paths in future iterations.
2568                 targets.clear();
2569                 dist.clear();
2570                 hit_minimum_limit = false;
2571
2572                 // If first hop is a private channel and the only way to reach the payee, this is the only
2573                 // place where it could be added.
2574                 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2575                         for details in first_channels {
2576                                 let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2577                                         details, payer_node_id: &our_node_id,
2578                                 });
2579                                 let added = add_entry!(&candidate, 0, path_value_msat,
2580                                                                         0, 0u64, 0, 0).is_some();
2581                                 log_trace!(logger, "{} direct route to payee via {}",
2582                                                 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2583                         }
2584                 }));
2585
2586                 // Add the payee as a target, so that the payee-to-payer
2587                 // search algorithm knows what to start with.
2588                 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2589                         // The payee is not in our network graph, so nothing to add here.
2590                         // There is still a chance of reaching them via last_hops though,
2591                         // so don't yet fail the payment here.
2592                         // If not, targets.pop() will not even let us enter the loop in step 2.
2593                         None => {},
2594                         Some(node) => {
2595                                 add_entries_to_cheapest_to_target_node!(node, payee, path_value_msat, 0, 0);
2596                         },
2597                 });
2598
2599                 // Step (2).
2600                 // If a caller provided us with last hops, add them to routing targets. Since this happens
2601                 // earlier than general path finding, they will be somewhat prioritized, although currently
2602                 // it matters only if the fees are exactly the same.
2603                 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2604                         // Only add the hops in this route to our candidate set if either
2605                         // we have a direct channel to the first hop or the first hop is
2606                         // in the regular network graph.
2607                         let source_node_id = match introduction_node_id_cache[hint_idx] {
2608                                 Some(node_id) => node_id,
2609                                 None => match &hint.1.introduction_node {
2610                                         IntroductionNode::NodeId(pubkey) => {
2611                                                 let node_id = NodeId::from_pubkey(&pubkey);
2612                                                 match first_hop_targets.get_key_value(&node_id).map(|(key, _)| key) {
2613                                                         Some(node_id) => node_id,
2614                                                         None => continue,
2615                                                 }
2616                                         },
2617                                         IntroductionNode::DirectedShortChannelId(direction, scid) => {
2618                                                 let first_hop = first_hop_targets.iter().find(|(_, channels)|
2619                                                         channels
2620                                                                 .iter()
2621                                                                 .any(|details| Some(*scid) == details.get_outbound_payment_scid())
2622                                                 );
2623                                                 match first_hop {
2624                                                         Some((counterparty_node_id, _)) => {
2625                                                                 direction.select_node_id(&our_node_id, counterparty_node_id)
2626                                                         },
2627                                                         None => continue,
2628                                                 }
2629                                         },
2630                                 },
2631                         };
2632                         if our_node_id == *source_node_id { continue }
2633                         let candidate = if hint.1.blinded_hops.len() == 1 {
2634                                 CandidateRouteHop::OneHopBlinded(
2635                                         OneHopBlindedPathCandidate { source_node_id, hint, hint_idx }
2636                                 )
2637                         } else {
2638                                 CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_id, hint, hint_idx })
2639                         };
2640                         let mut path_contribution_msat = path_value_msat;
2641                         if let Some(hop_used_msat) = add_entry!(&candidate,
2642                                 0, path_contribution_msat, 0, 0_u64, 0, 0)
2643                         {
2644                                 path_contribution_msat = hop_used_msat;
2645                         } else { continue }
2646                         if let Some(first_channels) = first_hop_targets.get(source_node_id) {
2647                                 let mut first_channels = first_channels.clone();
2648                                 sort_first_hop_channels(
2649                                         &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2650                                 );
2651                                 for details in first_channels {
2652                                         let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2653                                                 details, payer_node_id: &our_node_id,
2654                                         });
2655                                         let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2656                                                 Some(fee) => fee,
2657                                                 None => continue
2658                                         };
2659                                         let path_min = candidate.htlc_minimum_msat().saturating_add(
2660                                                 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2661                                         add_entry!(&first_hop_candidate, blinded_path_fee, path_contribution_msat, path_min,
2662                                                 0_u64, candidate.cltv_expiry_delta(), 0);
2663                                 }
2664                         }
2665                 }
2666                 for route in payment_params.payee.unblinded_route_hints().iter()
2667                         .filter(|route| !route.0.is_empty())
2668                 {
2669                         let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2670                         let first_hop_src_is_reachable =
2671                                 // Only add the hops in this route to our candidate set if either we are part of
2672                                 // the first hop, we have a direct channel to the first hop, or the first hop is in
2673                                 // the regular network graph.
2674                                 our_node_id == first_hop_src_id ||
2675                                 first_hop_targets.get(&first_hop_src_id).is_some() ||
2676                                 network_nodes.get(&first_hop_src_id).is_some();
2677                         if first_hop_src_is_reachable {
2678                                 // We start building the path from reverse, i.e., from payee
2679                                 // to the first RouteHintHop in the path.
2680                                 let hop_iter = route.0.iter().rev();
2681                                 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2682                                         route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2683                                 let mut hop_used = true;
2684                                 let mut aggregate_next_hops_fee_msat: u64 = 0;
2685                                 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2686                                 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2687                                 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2688                                 let mut aggregate_next_hops_path_length: u8 = 0;
2689                                 let mut aggregate_path_contribution_msat = path_value_msat;
2690
2691                                 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2692                                         let target = private_hop_key_cache.get(prev_hop_id).unwrap();
2693
2694                                         if let Some(first_channels) = first_hop_targets.get(target) {
2695                                                 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2696                                                         log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2697                                                                 hop.short_channel_id);
2698                                                         break;
2699                                                 }
2700                                         }
2701
2702                                         let candidate = network_channels
2703                                                 .get(&hop.short_channel_id)
2704                                                 .and_then(|channel| channel.as_directed_to(target))
2705                                                 .map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2706                                                         info,
2707                                                         short_channel_id: hop.short_channel_id,
2708                                                 }))
2709                                                 .unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: hop, target_node_id: target }));
2710
2711                                         if let Some(hop_used_msat) = add_entry!(&candidate,
2712                                                 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2713                                                 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2714                                                 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2715                                         {
2716                                                 aggregate_path_contribution_msat = hop_used_msat;
2717                                         } else {
2718                                                 // If this hop was not used then there is no use checking the preceding
2719                                                 // hops in the RouteHint. We can break by just searching for a direct
2720                                                 // channel between last checked hop and first_hop_targets.
2721                                                 hop_used = false;
2722                                         }
2723
2724                                         let used_liquidity_msat = used_liquidities
2725                                                 .get(&candidate.id()).copied()
2726                                                 .unwrap_or(0);
2727                                         let channel_usage = ChannelUsage {
2728                                                 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2729                                                 inflight_htlc_msat: used_liquidity_msat,
2730                                                 effective_capacity: candidate.effective_capacity(),
2731                                         };
2732                                         let channel_penalty_msat = scorer.channel_penalty_msat(
2733                                                 &candidate, channel_usage, score_params
2734                                         );
2735                                         aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2736                                                 .saturating_add(channel_penalty_msat);
2737
2738                                         aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2739                                                 .saturating_add(hop.cltv_expiry_delta as u32);
2740
2741                                         aggregate_next_hops_path_length = aggregate_next_hops_path_length
2742                                                 .saturating_add(1);
2743
2744                                         // Searching for a direct channel between last checked hop and first_hop_targets
2745                                         if let Some(first_channels) = first_hop_targets.get(target) {
2746                                                 let mut first_channels = first_channels.clone();
2747                                                 sort_first_hop_channels(
2748                                                         &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2749                                                 );
2750                                                 for details in first_channels {
2751                                                         let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2752                                                                 details, payer_node_id: &our_node_id,
2753                                                         });
2754                                                         add_entry!(&first_hop_candidate,
2755                                                                 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2756                                                                 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2757                                                                 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2758                                                 }
2759                                         }
2760
2761                                         if !hop_used {
2762                                                 break;
2763                                         }
2764
2765                                         // In the next values of the iterator, the aggregate fees already reflects
2766                                         // the sum of value sent from payer (final_value_msat) and routing fees
2767                                         // for the last node in the RouteHint. We need to just add the fees to
2768                                         // route through the current node so that the preceding node (next iteration)
2769                                         // can use it.
2770                                         let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2771                                                 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2772                                         aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2773
2774                                         // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2775                                         // this route hint's source node to forward said min over this channel.
2776                                         aggregate_next_hops_path_htlc_minimum_msat = {
2777                                                 let curr_htlc_min = cmp::max(
2778                                                         candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2779                                                 );
2780                                                 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2781                                                 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2782                                         };
2783
2784                                         if idx == route.0.len() - 1 {
2785                                                 // The last hop in this iterator is the first hop in
2786                                                 // overall RouteHint.
2787                                                 // If this hop connects to a node with which we have a direct channel,
2788                                                 // ignore the network graph and, if the last hop was added, add our
2789                                                 // direct channel to the candidate set.
2790                                                 //
2791                                                 // Note that we *must* check if the last hop was added as `add_entry`
2792                                                 // always assumes that the third argument is a node to which we have a
2793                                                 // path.
2794                                                 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
2795                                                         let mut first_channels = first_channels.clone();
2796                                                         sort_first_hop_channels(
2797                                                                 &mut first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
2798                                                         );
2799                                                         for details in first_channels {
2800                                                                 let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2801                                                                         details, payer_node_id: &our_node_id,
2802                                                                 });
2803                                                                 add_entry!(&first_hop_candidate,
2804                                                                         aggregate_next_hops_fee_msat,
2805                                                                         aggregate_path_contribution_msat,
2806                                                                         aggregate_next_hops_path_htlc_minimum_msat,
2807                                                                         aggregate_next_hops_path_penalty_msat,
2808                                                                         aggregate_next_hops_cltv_delta,
2809                                                                         aggregate_next_hops_path_length);
2810                                                         }
2811                                                 }
2812                                         }
2813                                 }
2814                         }
2815                 }
2816
2817                 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2818
2819                 // At this point, targets are filled with the data from first and
2820                 // last hops communicated by the caller, and the payment receiver.
2821                 let mut found_new_path = false;
2822
2823                 // Step (3).
2824                 // If this loop terminates due the exhaustion of targets, two situations are possible:
2825                 // - not enough outgoing liquidity:
2826                 //   0 < already_collected_value_msat < final_value_msat
2827                 // - enough outgoing liquidity:
2828                 //   final_value_msat <= already_collected_value_msat < recommended_value_msat
2829                 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2830                 // paths_collection will be stopped because found_new_path==false.
2831                 // This is not necessarily a routing failure.
2832                 'path_construction: while let Some(RouteGraphNode { node_id, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
2833
2834                         // Since we're going payee-to-payer, hitting our node as a target means we should stop
2835                         // traversing the graph and arrange the path out of what we found.
2836                         if node_id == our_node_id {
2837                                 let mut new_entry = dist.remove(&our_node_id).unwrap();
2838                                 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2839
2840                                 'path_walk: loop {
2841                                         let mut features_set = false;
2842                                         let target = ordered_hops.last().unwrap().0.candidate.target().unwrap_or(maybe_dummy_payee_node_id);
2843                                         if let Some(first_channels) = first_hop_targets.get(&target) {
2844                                                 for details in first_channels {
2845                                                         if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
2846                                                                 = ordered_hops.last().unwrap().0.candidate
2847                                                         {
2848                                                                 if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
2849                                                                         ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2850                                                                         features_set = true;
2851                                                                         break;
2852                                                                 }
2853                                                         }
2854                                                 }
2855                                         }
2856                                         if !features_set {
2857                                                 if let Some(node) = network_nodes.get(&target) {
2858                                                         if let Some(node_info) = node.announcement_info.as_ref() {
2859                                                                 ordered_hops.last_mut().unwrap().1 = node_info.features().clone();
2860                                                         } else {
2861                                                                 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2862                                                         }
2863                                                 } else {
2864                                                         // We can fill in features for everything except hops which were
2865                                                         // provided via the invoice we're paying. We could guess based on the
2866                                                         // recipient's features but for now we simply avoid guessing at all.
2867                                                 }
2868                                         }
2869
2870                                         // Means we successfully traversed from the payer to the payee, now
2871                                         // save this path for the payment route. Also, update the liquidity
2872                                         // remaining on the used hops, so that we take them into account
2873                                         // while looking for more paths.
2874                                         if target == maybe_dummy_payee_node_id {
2875                                                 break 'path_walk;
2876                                         }
2877
2878                                         new_entry = match dist.remove(&target) {
2879                                                 Some(payment_hop) => payment_hop,
2880                                                 // We can't arrive at None because, if we ever add an entry to targets,
2881                                                 // we also fill in the entry in dist (see add_entry!).
2882                                                 None => unreachable!(),
2883                                         };
2884                                         // We "propagate" the fees one hop backward (topologically) here,
2885                                         // so that fees paid for a HTLC forwarding on the current channel are
2886                                         // associated with the previous channel (where they will be subtracted).
2887                                         ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2888                                         ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2889                                 }
2890                                 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2891                                 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2892
2893                                 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2894                                         ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2895
2896                                 let mut payment_path = PaymentPath {hops: ordered_hops};
2897
2898                                 // We could have possibly constructed a slightly inconsistent path: since we reduce
2899                                 // value being transferred along the way, we could have violated htlc_minimum_msat
2900                                 // on some channels we already passed (assuming dest->source direction). Here, we
2901                                 // recompute the fees again, so that if that's the case, we match the currently
2902                                 // underpaid htlc_minimum_msat with fees.
2903                                 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2904                                 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2905                                 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2906
2907                                 // Since a path allows to transfer as much value as
2908                                 // the smallest channel it has ("bottleneck"), we should recompute
2909                                 // the fees so sender HTLC don't overpay fees when traversing
2910                                 // larger channels than the bottleneck. This may happen because
2911                                 // when we were selecting those channels we were not aware how much value
2912                                 // this path will transfer, and the relative fee for them
2913                                 // might have been computed considering a larger value.
2914                                 // Remember that we used these channels so that we don't rely
2915                                 // on the same liquidity in future paths.
2916                                 let mut prevented_redundant_path_selection = false;
2917                                 for (hop, _) in payment_path.hops.iter() {
2918                                         let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2919                                         let used_liquidity_msat = used_liquidities
2920                                                 .entry(hop.candidate.id())
2921                                                 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2922                                                 .or_insert(spent_on_hop_msat);
2923                                         let hop_capacity = hop.candidate.effective_capacity();
2924                                         let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2925                                         if *used_liquidity_msat == hop_max_msat {
2926                                                 // If this path used all of this channel's available liquidity, we know
2927                                                 // this path will not be selected again in the next loop iteration.
2928                                                 prevented_redundant_path_selection = true;
2929                                         }
2930                                         debug_assert!(*used_liquidity_msat <= hop_max_msat);
2931                                 }
2932                                 if !prevented_redundant_path_selection {
2933                                         // If we weren't capped by hitting a liquidity limit on a channel in the path,
2934                                         // we'll probably end up picking the same path again on the next iteration.
2935                                         // Decrease the available liquidity of a hop in the middle of the path.
2936                                         let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2937                                         let exhausted = u64::max_value();
2938                                         log_trace!(logger,
2939                                                 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2940                                                 LoggedCandidateHop(victim_candidate));
2941                                         if let Some(scid) = victim_candidate.short_channel_id() {
2942                                                 *used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
2943                                                 *used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
2944                                         }
2945                                 }
2946
2947                                 // Track the total amount all our collected paths allow to send so that we know
2948                                 // when to stop looking for more paths
2949                                 already_collected_value_msat += value_contribution_msat;
2950
2951                                 payment_paths.push(payment_path);
2952                                 found_new_path = true;
2953                                 break 'path_construction;
2954                         }
2955
2956                         // If we found a path back to the payee, we shouldn't try to process it again. This is
2957                         // the equivalent of the `elem.was_processed` check in
2958                         // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2959                         if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2960
2961                         // Otherwise, since the current target node is not us,
2962                         // keep "unrolling" the payment graph from payee to payer by
2963                         // finding a way to reach the current target from the payer side.
2964                         match network_nodes.get(&node_id) {
2965                                 None => {},
2966                                 Some(node) => {
2967                                         add_entries_to_cheapest_to_target_node!(node, node_id,
2968                                                 value_contribution_msat,
2969                                                 total_cltv_delta, path_length_to_node);
2970                                 },
2971                         }
2972                 }
2973
2974                 if !allow_mpp {
2975                         if !found_new_path && channel_saturation_pow_half != 0 {
2976                                 channel_saturation_pow_half = 0;
2977                                 continue 'paths_collection;
2978                         }
2979                         // If we don't support MPP, no use trying to gather more value ever.
2980                         break 'paths_collection;
2981                 }
2982
2983                 // Step (4).
2984                 // Stop either when the recommended value is reached or if no new path was found in this
2985                 // iteration.
2986                 // In the latter case, making another path finding attempt won't help,
2987                 // because we deterministically terminated the search due to low liquidity.
2988                 if !found_new_path && channel_saturation_pow_half != 0 {
2989                         channel_saturation_pow_half = 0;
2990                 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2991                         log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2992                         path_value_msat = recommended_value_msat;
2993                 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2994                         log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2995                                 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2996                         break 'paths_collection;
2997                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2998                         // Further, if this was our first walk of the graph, and we weren't limited by an
2999                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
3000                         // limited by an htlc_minimum_msat value, find another path with a higher value,
3001                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
3002                         // still keeping a lower total fee than this path.
3003                         if !hit_minimum_limit {
3004                                 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
3005                                 break 'paths_collection;
3006                         }
3007                         log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher value to meet htlc_minimum_msat limit.");
3008                         path_value_msat = recommended_value_msat;
3009                 }
3010         }
3011
3012         let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
3013                 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
3014                 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
3015                 num_ignored_total_fee_limit;
3016         if num_ignored_total > 0 {
3017                 log_trace!(logger,
3018                         "Ignored {} candidate hops due to insufficient value contribution, {} due to path length limit, {} due to CLTV delta limit, {} due to previous payment failure, {} due to htlc_minimum_msat limit, {} to avoid overpaying, {} due to maximum total fee limit. Total: {} ignored candidates.",
3019                         num_ignored_value_contribution, num_ignored_path_length_limit,
3020                         num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3021                         num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3022                         num_ignored_total_fee_limit, num_ignored_total);
3023         }
3024
3025         // Step (5).
3026         if payment_paths.len() == 0 {
3027                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3028         }
3029
3030         if already_collected_value_msat < final_value_msat {
3031                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3032         }
3033
3034         // Step (6).
3035         let mut selected_route = payment_paths;
3036
3037         debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3038         let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3039
3040         // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3041         // the value they contribute towards the payment amount.
3042         // We sort in descending order as we will remove from the front in `retain`, next.
3043         selected_route.sort_unstable_by(|a, b|
3044                 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
3045                         .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
3046         );
3047
3048         // We should make sure that at least 1 path left.
3049         let mut paths_left = selected_route.len();
3050         selected_route.retain(|path| {
3051                 if paths_left == 1 {
3052                         return true
3053                 }
3054                 let path_value_msat = path.get_value_msat();
3055                 if path_value_msat <= overpaid_value_msat {
3056                         overpaid_value_msat -= path_value_msat;
3057                         paths_left -= 1;
3058                         return false;
3059                 }
3060                 true
3061         });
3062         debug_assert!(selected_route.len() > 0);
3063
3064         if overpaid_value_msat != 0 {
3065                 // Step (7).
3066                 // Now, subtract the remaining overpaid value from the most-expensive path.
3067                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3068                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
3069                 selected_route.sort_unstable_by(|a, b| {
3070                         let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3071                         let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3072                         a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3073                 });
3074                 let expensive_payment_path = selected_route.first_mut().unwrap();
3075
3076                 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3077                 // can't go negative.
3078                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3079                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3080         }
3081
3082         // Step (8).
3083         // Sort by the path itself and combine redundant paths.
3084         // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3085         // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3086         // across nodes.
3087         selected_route.sort_unstable_by_key(|path| {
3088                 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3089                 debug_assert!(path.hops.len() <= key.len());
3090                 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3091                         *key = scid;
3092                 }
3093                 key
3094         });
3095         for idx in 0..(selected_route.len() - 1) {
3096                 if idx + 1 >= selected_route.len() { break; }
3097                 if iter_equal(selected_route[idx    ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3098                               selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3099                         let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3100                         selected_route[idx].update_value_and_recompute_fees(new_value);
3101                         selected_route.remove(idx + 1);
3102                 }
3103         }
3104
3105         let mut paths = Vec::new();
3106         for payment_path in selected_route {
3107                 let mut hops = Vec::with_capacity(payment_path.hops.len());
3108                 for (hop, node_features) in payment_path.hops.iter()
3109                         .filter(|(h, _)| h.candidate.short_channel_id().is_some())
3110                 {
3111                         let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3112                         let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3113                                 // If we sourced the hop from the graph we're sure the target node is announced.
3114                                 true
3115                         } else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3116                                 // If this is a first hop we also know if it's announced.
3117                                 first_hop.details.is_public
3118                         } else {
3119                                 // If we sourced it any other way, we double-check the network graph to see if
3120                                 // there are announced channels between the endpoints. If so, the hop might be
3121                                 // referring to any of the announced channels, as its `short_channel_id` might be
3122                                 // an alias, in which case we don't take any chances here.
3123                                 network_graph.node(&target).map_or(false, |hop_node|
3124                                         hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3125                                                         .map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3126                                 )
3127                         };
3128
3129                         hops.push(RouteHop {
3130                                 pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3131                                 node_features: node_features.clone(),
3132                                 short_channel_id: hop.candidate.short_channel_id().unwrap(),
3133                                 channel_features: hop.candidate.features(),
3134                                 fee_msat: hop.fee_msat,
3135                                 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3136                                 maybe_announced_channel,
3137                         });
3138                 }
3139                 let mut final_cltv_delta = final_cltv_expiry_delta;
3140                 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3141                         if let Some(blinded_path) = h.candidate.blinded_path() {
3142                                 final_cltv_delta = h.candidate.cltv_expiry_delta();
3143                                 Some(BlindedTail {
3144                                         hops: blinded_path.blinded_hops.clone(),
3145                                         blinding_point: blinded_path.blinding_point,
3146                                         excess_final_cltv_expiry_delta: 0,
3147                                         final_value_msat: h.fee_msat,
3148                                 })
3149                         } else { None }
3150                 });
3151                 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3152                 // applicable for the previous hop.
3153                 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3154                         core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3155                 });
3156
3157                 paths.push(Path { hops, blinded_tail });
3158         }
3159         // Make sure we would never create a route with more paths than we allow.
3160         debug_assert!(paths.len() <= payment_params.max_path_count.into());
3161
3162         if let Some(node_features) = payment_params.payee.node_features() {
3163                 for path in paths.iter_mut() {
3164                         path.hops.last_mut().unwrap().node_features = node_features.clone();
3165                 }
3166         }
3167
3168         let route = Route { paths, route_params: Some(route_params.clone()) };
3169
3170         // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3171         if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3172                 if route.get_total_fees() > max_total_routing_fee_msat {
3173                         return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3174                                 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3175                 }
3176         }
3177
3178         log_info!(logger, "Got route: {}", log_route!(route));
3179         Ok(route)
3180 }
3181
3182 // When an adversarial intermediary node observes a payment, it may be able to infer its
3183 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3184 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3185 // payment path by adding a randomized 'shadow route' offset to the final hop.
3186 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3187         network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3188 ) {
3189         let network_channels = network_graph.channels();
3190         let network_nodes = network_graph.nodes();
3191
3192         for path in route.paths.iter_mut() {
3193                 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3194
3195                 // Remember the last three nodes of the random walk and avoid looping back on them.
3196                 // Init with the last three nodes from the actual path, if possible.
3197                 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3198                         NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3199                         NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3200
3201                 // Choose the last publicly known node as the starting point for the random walk.
3202                 let mut cur_hop: Option<NodeId> = None;
3203                 let mut path_nonce = [0u8; 12];
3204                 if let Some(starting_hop) = path.hops.iter().rev()
3205                         .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3206                                 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3207                                 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3208                 }
3209
3210                 // Init PRNG with the path-dependant nonce, which is static for private paths.
3211                 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3212                 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3213
3214                 // Pick a random path length in [1 .. 3]
3215                 prng.process_in_place(&mut random_path_bytes);
3216                 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3217
3218                 for random_hop in 0..random_walk_length {
3219                         // If we don't find a suitable offset in the public network graph, we default to
3220                         // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3221                         let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3222
3223                         if let Some(cur_node_id) = cur_hop {
3224                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3225                                         // Randomly choose the next unvisited hop.
3226                                         prng.process_in_place(&mut random_path_bytes);
3227                                         if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3228                                                 .checked_rem(cur_node.channels.len())
3229                                                 .and_then(|index| cur_node.channels.get(index))
3230                                                 .and_then(|id| network_channels.get(id)) {
3231                                                         random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3232                                                                 if !nodes_to_avoid.iter().any(|x| x == next_id) {
3233                                                                         nodes_to_avoid[random_hop] = *next_id;
3234                                                                         random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3235                                                                         cur_hop = Some(*next_id);
3236                                                                 }
3237                                                         });
3238                                                 }
3239                                 }
3240                         }
3241
3242                         shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3243                                 .checked_add(random_hop_offset)
3244                                 .unwrap_or(shadow_ctlv_expiry_delta_offset);
3245                 }
3246
3247                 // Limit the total offset to reduce the worst-case locked liquidity timevalue
3248                 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3249                 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3250
3251                 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3252                 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3253                 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3254                 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3255                 max_path_offset = cmp::max(
3256                         max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3257                         max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3258                 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3259
3260                 // Add 'shadow' CLTV offset to the final hop
3261                 if let Some(tail) = path.blinded_tail.as_mut() {
3262                         tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3263                                 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3264                 }
3265                 if let Some(last_hop) = path.hops.last_mut() {
3266                         last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3267                                 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3268                 }
3269         }
3270 }
3271
3272 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3273 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3274 ///
3275 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3276 pub fn build_route_from_hops<L: Deref, GL: Deref>(
3277         our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3278         network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3279 ) -> Result<Route, LightningError>
3280 where L::Target: Logger, GL::Target: Logger {
3281         let graph_lock = network_graph.read_only();
3282         let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3283                 &graph_lock, logger, random_seed_bytes)?;
3284         add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3285         Ok(route)
3286 }
3287
3288 fn build_route_from_hops_internal<L: Deref>(
3289         our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3290         network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3291 ) -> Result<Route, LightningError> where L::Target: Logger {
3292
3293         struct HopScorer {
3294                 our_node_id: NodeId,
3295                 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3296         }
3297
3298         impl ScoreLookUp for HopScorer {
3299                 type ScoreParams = ();
3300                 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3301                         _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3302                 {
3303                         let mut cur_id = self.our_node_id;
3304                         for i in 0..self.hop_ids.len() {
3305                                 if let Some(next_id) = self.hop_ids[i] {
3306                                         if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3307                                                 return 0;
3308                                         }
3309                                         cur_id = next_id;
3310                                 } else {
3311                                         break;
3312                                 }
3313                         }
3314                         u64::max_value()
3315                 }
3316         }
3317
3318         impl<'a> Writeable for HopScorer {
3319                 #[inline]
3320                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3321                         unreachable!();
3322                 }
3323         }
3324
3325         if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3326                 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3327         }
3328
3329         let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3330         let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3331         for i in 0..hops.len() {
3332                 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3333         }
3334
3335         let scorer = HopScorer { our_node_id, hop_ids };
3336
3337         get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3338 }
3339
3340 #[cfg(test)]
3341 mod tests {
3342         use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode};
3343         use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3344         use crate::routing::utxo::UtxoResult;
3345         use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3346                 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3347                 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3348         use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3349         use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3350         use crate::chain::transaction::OutPoint;
3351         use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState};
3352         use crate::ln::types::ChannelId;
3353         use crate::ln::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3354         use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3355         use crate::ln::channelmanager;
3356         use crate::offers::invoice::BlindedPayInfo;
3357         use crate::util::config::UserConfig;
3358         use crate::util::test_utils as ln_test_utils;
3359         use crate::crypto::chacha20::ChaCha20;
3360         use crate::util::ser::{Readable, Writeable};
3361         #[cfg(c_bindings)]
3362         use crate::util::ser::Writer;
3363
3364         use bitcoin::amount::Amount;
3365         use bitcoin::hashes::Hash;
3366         use bitcoin::network::Network;
3367         use bitcoin::blockdata::constants::ChainHash;
3368         use bitcoin::blockdata::script::Builder;
3369         use bitcoin::blockdata::opcodes;
3370         use bitcoin::blockdata::transaction::TxOut;
3371         use bitcoin::hashes::hex::FromHex;
3372         use bitcoin::secp256k1::{PublicKey,SecretKey};
3373         use bitcoin::secp256k1::Secp256k1;
3374
3375         use crate::io::Cursor;
3376         use crate::prelude::*;
3377         use crate::sync::Arc;
3378
3379         fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3380                         features: InitFeatures, outbound_capacity_msat: u64) -> ChannelDetails {
3381                 ChannelDetails {
3382                         channel_id: ChannelId::new_zero(),
3383                         counterparty: ChannelCounterparty {
3384                                 features,
3385                                 node_id,
3386                                 unspendable_punishment_reserve: 0,
3387                                 forwarding_info: None,
3388                                 outbound_htlc_minimum_msat: None,
3389                                 outbound_htlc_maximum_msat: None,
3390                         },
3391                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3392                         channel_type: None,
3393                         short_channel_id,
3394                         outbound_scid_alias: None,
3395                         inbound_scid_alias: None,
3396                         channel_value_satoshis: 0,
3397                         user_channel_id: 0,
3398                         balance_msat: 0,
3399                         outbound_capacity_msat,
3400                         next_outbound_htlc_limit_msat: outbound_capacity_msat,
3401                         next_outbound_htlc_minimum_msat: 0,
3402                         inbound_capacity_msat: 42,
3403                         unspendable_punishment_reserve: None,
3404                         confirmations_required: None,
3405                         confirmations: None,
3406                         force_close_spend_delay: None,
3407                         is_outbound: true, is_channel_ready: true,
3408                         is_usable: true, is_public: true,
3409                         inbound_htlc_minimum_msat: None,
3410                         inbound_htlc_maximum_msat: None,
3411                         config: None,
3412                         feerate_sat_per_1000_weight: None,
3413                         channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
3414                         pending_inbound_htlcs: Vec::new(),
3415                         pending_outbound_htlcs: Vec::new(),
3416                 }
3417         }
3418
3419         #[test]
3420         fn simple_route_test() {
3421                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3422                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3423                 let mut payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3424                 let scorer = ln_test_utils::TestScorer::new();
3425                 let random_seed_bytes = [42; 32];
3426
3427                 // Simple route to 2 via 1
3428
3429                 let route_params = RouteParameters::from_payment_params_and_value(
3430                         payment_params.clone(), 0);
3431                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3432                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3433                         &Default::default(), &random_seed_bytes) {
3434                                 assert_eq!(err, "Cannot send a payment of 0 msat");
3435                 } else { panic!(); }
3436
3437                 payment_params.max_path_length = 2;
3438                 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3439                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3440                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3441                 assert_eq!(route.paths[0].hops.len(), 2);
3442
3443                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3444                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3445                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3446                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3447                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3448                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3449
3450                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3451                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3452                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3453                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3454                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3455                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3456
3457                 route_params.payment_params.max_path_length = 1;
3458                 get_route(&our_id, &route_params, &network_graph.read_only(), None,
3459                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
3460         }
3461
3462         #[test]
3463         fn invalid_first_hop_test() {
3464                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3465                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3466                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3467                 let scorer = ln_test_utils::TestScorer::new();
3468                 let random_seed_bytes = [42; 32];
3469
3470                 // Simple route to 2 via 1
3471
3472                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3473
3474                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3475                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3476                         &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3477                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3478                                 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3479                 } else { panic!(); }
3480
3481                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3482                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3483                 assert_eq!(route.paths[0].hops.len(), 2);
3484         }
3485
3486         #[test]
3487         fn htlc_minimum_test() {
3488                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3489                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3490                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3491                 let scorer = ln_test_utils::TestScorer::new();
3492                 let random_seed_bytes = [42; 32];
3493
3494                 // Simple route to 2 via 1
3495
3496                 // Disable other paths
3497                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3498                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3499                         short_channel_id: 12,
3500                         timestamp: 2,
3501                         flags: 2, // to disable
3502                         cltv_expiry_delta: 0,
3503                         htlc_minimum_msat: 0,
3504                         htlc_maximum_msat: MAX_VALUE_MSAT,
3505                         fee_base_msat: 0,
3506                         fee_proportional_millionths: 0,
3507                         excess_data: Vec::new()
3508                 });
3509                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3510                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3511                         short_channel_id: 3,
3512                         timestamp: 2,
3513                         flags: 2, // to disable
3514                         cltv_expiry_delta: 0,
3515                         htlc_minimum_msat: 0,
3516                         htlc_maximum_msat: MAX_VALUE_MSAT,
3517                         fee_base_msat: 0,
3518                         fee_proportional_millionths: 0,
3519                         excess_data: Vec::new()
3520                 });
3521                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3522                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3523                         short_channel_id: 13,
3524                         timestamp: 2,
3525                         flags: 2, // to disable
3526                         cltv_expiry_delta: 0,
3527                         htlc_minimum_msat: 0,
3528                         htlc_maximum_msat: MAX_VALUE_MSAT,
3529                         fee_base_msat: 0,
3530                         fee_proportional_millionths: 0,
3531                         excess_data: Vec::new()
3532                 });
3533                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3534                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3535                         short_channel_id: 6,
3536                         timestamp: 2,
3537                         flags: 2, // to disable
3538                         cltv_expiry_delta: 0,
3539                         htlc_minimum_msat: 0,
3540                         htlc_maximum_msat: MAX_VALUE_MSAT,
3541                         fee_base_msat: 0,
3542                         fee_proportional_millionths: 0,
3543                         excess_data: Vec::new()
3544                 });
3545                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3546                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3547                         short_channel_id: 7,
3548                         timestamp: 2,
3549                         flags: 2, // to disable
3550                         cltv_expiry_delta: 0,
3551                         htlc_minimum_msat: 0,
3552                         htlc_maximum_msat: MAX_VALUE_MSAT,
3553                         fee_base_msat: 0,
3554                         fee_proportional_millionths: 0,
3555                         excess_data: Vec::new()
3556                 });
3557
3558                 // Check against amount_to_transfer_over_msat.
3559                 // Set minimal HTLC of 200_000_000 msat.
3560                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3561                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3562                         short_channel_id: 2,
3563                         timestamp: 3,
3564                         flags: 0,
3565                         cltv_expiry_delta: 0,
3566                         htlc_minimum_msat: 200_000_000,
3567                         htlc_maximum_msat: MAX_VALUE_MSAT,
3568                         fee_base_msat: 0,
3569                         fee_proportional_millionths: 0,
3570                         excess_data: Vec::new()
3571                 });
3572
3573                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3574                 // be used.
3575                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3576                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3577                         short_channel_id: 4,
3578                         timestamp: 3,
3579                         flags: 0,
3580                         cltv_expiry_delta: 0,
3581                         htlc_minimum_msat: 0,
3582                         htlc_maximum_msat: 199_999_999,
3583                         fee_base_msat: 0,
3584                         fee_proportional_millionths: 0,
3585                         excess_data: Vec::new()
3586                 });
3587
3588                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3589                 let route_params = RouteParameters::from_payment_params_and_value(
3590                         payment_params, 199_999_999);
3591                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3592                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3593                         &Default::default(), &random_seed_bytes) {
3594                                 assert_eq!(err, "Failed to find a path to the given destination");
3595                 } else { panic!(); }
3596
3597                 // Lift the restriction on the first hop.
3598                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3599                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3600                         short_channel_id: 2,
3601                         timestamp: 4,
3602                         flags: 0,
3603                         cltv_expiry_delta: 0,
3604                         htlc_minimum_msat: 0,
3605                         htlc_maximum_msat: MAX_VALUE_MSAT,
3606                         fee_base_msat: 0,
3607                         fee_proportional_millionths: 0,
3608                         excess_data: Vec::new()
3609                 });
3610
3611                 // A payment above the minimum should pass
3612                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3613                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3614                 assert_eq!(route.paths[0].hops.len(), 2);
3615         }
3616
3617         #[test]
3618         fn htlc_minimum_overpay_test() {
3619                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3620                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3621                 let config = UserConfig::default();
3622                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3623                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3624                         .unwrap();
3625                 let scorer = ln_test_utils::TestScorer::new();
3626                 let random_seed_bytes = [42; 32];
3627
3628                 // A route to node#2 via two paths.
3629                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3630                 // Thus, they can't send 60 without overpaying.
3631                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3632                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3633                         short_channel_id: 2,
3634                         timestamp: 2,
3635                         flags: 0,
3636                         cltv_expiry_delta: 0,
3637                         htlc_minimum_msat: 35_000,
3638                         htlc_maximum_msat: 40_000,
3639                         fee_base_msat: 0,
3640                         fee_proportional_millionths: 0,
3641                         excess_data: Vec::new()
3642                 });
3643                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3644                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3645                         short_channel_id: 12,
3646                         timestamp: 3,
3647                         flags: 0,
3648                         cltv_expiry_delta: 0,
3649                         htlc_minimum_msat: 35_000,
3650                         htlc_maximum_msat: 40_000,
3651                         fee_base_msat: 0,
3652                         fee_proportional_millionths: 0,
3653                         excess_data: Vec::new()
3654                 });
3655
3656                 // Make 0 fee.
3657                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3658                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3659                         short_channel_id: 13,
3660                         timestamp: 2,
3661                         flags: 0,
3662                         cltv_expiry_delta: 0,
3663                         htlc_minimum_msat: 0,
3664                         htlc_maximum_msat: MAX_VALUE_MSAT,
3665                         fee_base_msat: 0,
3666                         fee_proportional_millionths: 0,
3667                         excess_data: Vec::new()
3668                 });
3669                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3670                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3671                         short_channel_id: 4,
3672                         timestamp: 2,
3673                         flags: 0,
3674                         cltv_expiry_delta: 0,
3675                         htlc_minimum_msat: 0,
3676                         htlc_maximum_msat: MAX_VALUE_MSAT,
3677                         fee_base_msat: 0,
3678                         fee_proportional_millionths: 0,
3679                         excess_data: Vec::new()
3680                 });
3681
3682                 // Disable other paths
3683                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3684                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3685                         short_channel_id: 1,
3686                         timestamp: 3,
3687                         flags: 2, // to disable
3688                         cltv_expiry_delta: 0,
3689                         htlc_minimum_msat: 0,
3690                         htlc_maximum_msat: MAX_VALUE_MSAT,
3691                         fee_base_msat: 0,
3692                         fee_proportional_millionths: 0,
3693                         excess_data: Vec::new()
3694                 });
3695
3696                 let mut route_params = RouteParameters::from_payment_params_and_value(
3697                         payment_params.clone(), 60_000);
3698                 route_params.max_total_routing_fee_msat = Some(15_000);
3699                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3700                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3701                 // Overpay fees to hit htlc_minimum_msat.
3702                 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3703                 // TODO: this could be better balanced to overpay 10k and not 15k.
3704                 assert_eq!(overpaid_fees, 15_000);
3705
3706                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3707                 // while taking even more fee to match htlc_minimum_msat.
3708                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3709                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3710                         short_channel_id: 12,
3711                         timestamp: 4,
3712                         flags: 0,
3713                         cltv_expiry_delta: 0,
3714                         htlc_minimum_msat: 65_000,
3715                         htlc_maximum_msat: 80_000,
3716                         fee_base_msat: 0,
3717                         fee_proportional_millionths: 0,
3718                         excess_data: Vec::new()
3719                 });
3720                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3721                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3722                         short_channel_id: 2,
3723                         timestamp: 3,
3724                         flags: 0,
3725                         cltv_expiry_delta: 0,
3726                         htlc_minimum_msat: 0,
3727                         htlc_maximum_msat: MAX_VALUE_MSAT,
3728                         fee_base_msat: 0,
3729                         fee_proportional_millionths: 0,
3730                         excess_data: Vec::new()
3731                 });
3732                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3733                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3734                         short_channel_id: 4,
3735                         timestamp: 4,
3736                         flags: 0,
3737                         cltv_expiry_delta: 0,
3738                         htlc_minimum_msat: 0,
3739                         htlc_maximum_msat: MAX_VALUE_MSAT,
3740                         fee_base_msat: 0,
3741                         fee_proportional_millionths: 100_000,
3742                         excess_data: Vec::new()
3743                 });
3744
3745                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3746                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3747                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3748                 assert_eq!(route.paths.len(), 1);
3749                 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3750                 let fees = route.paths[0].hops[0].fee_msat;
3751                 assert_eq!(fees, 5_000);
3752
3753                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3754                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3755                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3756                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3757                 // the other channel.
3758                 assert_eq!(route.paths.len(), 1);
3759                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3760                 let fees = route.paths[0].hops[0].fee_msat;
3761                 assert_eq!(fees, 5_000);
3762         }
3763
3764         #[test]
3765         fn htlc_minimum_recipient_overpay_test() {
3766                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3767                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3768                 let config = UserConfig::default();
3769                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3770                 let scorer = ln_test_utils::TestScorer::new();
3771                 let random_seed_bytes = [42; 32];
3772
3773                 // Route to node2 over a single path which requires overpaying the recipient themselves.
3774
3775                 // First disable all paths except the us -> node1 -> node2 path
3776                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3777                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3778                         short_channel_id: 13,
3779                         timestamp: 2,
3780                         flags: 3,
3781                         cltv_expiry_delta: 0,
3782                         htlc_minimum_msat: 0,
3783                         htlc_maximum_msat: 0,
3784                         fee_base_msat: 0,
3785                         fee_proportional_millionths: 0,
3786                         excess_data: Vec::new()
3787                 });
3788
3789                 // Set channel 4 to free but with a high htlc_minimum_msat
3790                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3791                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3792                         short_channel_id: 4,
3793                         timestamp: 2,
3794                         flags: 0,
3795                         cltv_expiry_delta: 0,
3796                         htlc_minimum_msat: 15_000,
3797                         htlc_maximum_msat: MAX_VALUE_MSAT,
3798                         fee_base_msat: 0,
3799                         fee_proportional_millionths: 0,
3800                         excess_data: Vec::new()
3801                 });
3802
3803                 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3804                 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3805                 // what we try to find a route for, so this test only just happens to work out to exactly
3806                 // the fee limit.
3807                 let mut route_params = RouteParameters::from_payment_params_and_value(
3808                         payment_params.clone(), 5_000);
3809                 route_params.max_total_routing_fee_msat = Some(9_999);
3810                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3811                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3812                         &Default::default(), &random_seed_bytes) {
3813                                 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3814                 } else { panic!(); }
3815
3816                 let mut route_params = RouteParameters::from_payment_params_and_value(
3817                         payment_params.clone(), 5_000);
3818                 route_params.max_total_routing_fee_msat = Some(10_000);
3819                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3820                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3821                 assert_eq!(route.get_total_fees(), 10_000);
3822         }
3823
3824         #[test]
3825         fn disable_channels_test() {
3826                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3827                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3828                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3829                 let scorer = ln_test_utils::TestScorer::new();
3830                 let random_seed_bytes = [42; 32];
3831
3832                 // // Disable channels 4 and 12 by flags=2
3833                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3834                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3835                         short_channel_id: 4,
3836                         timestamp: 2,
3837                         flags: 2, // to disable
3838                         cltv_expiry_delta: 0,
3839                         htlc_minimum_msat: 0,
3840                         htlc_maximum_msat: MAX_VALUE_MSAT,
3841                         fee_base_msat: 0,
3842                         fee_proportional_millionths: 0,
3843                         excess_data: Vec::new()
3844                 });
3845                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3846                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3847                         short_channel_id: 12,
3848                         timestamp: 2,
3849                         flags: 2, // to disable
3850                         cltv_expiry_delta: 0,
3851                         htlc_minimum_msat: 0,
3852                         htlc_maximum_msat: MAX_VALUE_MSAT,
3853                         fee_base_msat: 0,
3854                         fee_proportional_millionths: 0,
3855                         excess_data: Vec::new()
3856                 });
3857
3858                 // If all the channels require some features we don't understand, route should fail
3859                 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3860                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3861                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3862                         &Default::default(), &random_seed_bytes) {
3863                                 assert_eq!(err, "Failed to find a path to the given destination");
3864                 } else { panic!(); }
3865
3866                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3867                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3868                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3869                 route_params.payment_params.max_path_length = 2;
3870                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3871                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3872                         &Default::default(), &random_seed_bytes).unwrap();
3873                 assert_eq!(route.paths[0].hops.len(), 2);
3874
3875                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3876                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3877                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3878                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3879                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3880                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3881
3882                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3883                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3884                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3885                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3886                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3887                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3888         }
3889
3890         #[test]
3891         fn disable_node_test() {
3892                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3893                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3894                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3895                 let scorer = ln_test_utils::TestScorer::new();
3896                 let random_seed_bytes = [42; 32];
3897
3898                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3899                 let mut unknown_features = NodeFeatures::empty();
3900                 unknown_features.set_unknown_feature_required();
3901                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3902                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3903                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3904
3905                 // If all nodes require some features we don't understand, route should fail
3906                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3907                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3908                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3909                         &Default::default(), &random_seed_bytes) {
3910                                 assert_eq!(err, "Failed to find a path to the given destination");
3911                 } else { panic!(); }
3912
3913                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3914                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3915                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3916                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3917                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3918                         &Default::default(), &random_seed_bytes).unwrap();
3919                 assert_eq!(route.paths[0].hops.len(), 2);
3920
3921                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3922                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3923                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3924                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3925                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3926                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3927
3928                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3929                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3930                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3931                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3932                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3933                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3934
3935                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3936                 // naively) assume that the user checked the feature bits on the invoice, which override
3937                 // the node_announcement.
3938         }
3939
3940         #[test]
3941         fn our_chans_test() {
3942                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3943                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3944                 let scorer = ln_test_utils::TestScorer::new();
3945                 let random_seed_bytes = [42; 32];
3946
3947                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3948                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3949                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3950                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3951                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3952                 assert_eq!(route.paths[0].hops.len(), 3);
3953
3954                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3955                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3956                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3957                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3958                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3959                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3960
3961                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3962                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3963                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3964                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3965                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3966                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3967
3968                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3969                 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3970                 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3971                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3972                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3973                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3974
3975                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3976                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3977                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3978                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3979                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3980                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3981                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3982                         &Default::default(), &random_seed_bytes).unwrap();
3983                 assert_eq!(route.paths[0].hops.len(), 2);
3984
3985                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3986                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3987                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3988                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3989                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3990                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3991
3992                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3993                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3994                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3995                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3996                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3997                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3998         }
3999
4000         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4001                 let zero_fees = RoutingFees {
4002                         base_msat: 0,
4003                         proportional_millionths: 0,
4004                 };
4005                 vec![RouteHint(vec![RouteHintHop {
4006                         src_node_id: nodes[3],
4007                         short_channel_id: 8,
4008                         fees: zero_fees,
4009                         cltv_expiry_delta: (8 << 4) | 1,
4010                         htlc_minimum_msat: None,
4011                         htlc_maximum_msat: None,
4012                 }
4013                 ]), RouteHint(vec![RouteHintHop {
4014                         src_node_id: nodes[4],
4015                         short_channel_id: 9,
4016                         fees: RoutingFees {
4017                                 base_msat: 1001,
4018                                 proportional_millionths: 0,
4019                         },
4020                         cltv_expiry_delta: (9 << 4) | 1,
4021                         htlc_minimum_msat: None,
4022                         htlc_maximum_msat: None,
4023                 }]), RouteHint(vec![RouteHintHop {
4024                         src_node_id: nodes[5],
4025                         short_channel_id: 10,
4026                         fees: zero_fees,
4027                         cltv_expiry_delta: (10 << 4) | 1,
4028                         htlc_minimum_msat: None,
4029                         htlc_maximum_msat: None,
4030                 }])]
4031         }
4032
4033         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4034                 let zero_fees = RoutingFees {
4035                         base_msat: 0,
4036                         proportional_millionths: 0,
4037                 };
4038                 vec![RouteHint(vec![RouteHintHop {
4039                         src_node_id: nodes[2],
4040                         short_channel_id: 5,
4041                         fees: RoutingFees {
4042                                 base_msat: 100,
4043                                 proportional_millionths: 0,
4044                         },
4045                         cltv_expiry_delta: (5 << 4) | 1,
4046                         htlc_minimum_msat: None,
4047                         htlc_maximum_msat: None,
4048                 }, RouteHintHop {
4049                         src_node_id: nodes[3],
4050                         short_channel_id: 8,
4051                         fees: zero_fees,
4052                         cltv_expiry_delta: (8 << 4) | 1,
4053                         htlc_minimum_msat: None,
4054                         htlc_maximum_msat: None,
4055                 }
4056                 ]), RouteHint(vec![RouteHintHop {
4057                         src_node_id: nodes[4],
4058                         short_channel_id: 9,
4059                         fees: RoutingFees {
4060                                 base_msat: 1001,
4061                                 proportional_millionths: 0,
4062                         },
4063                         cltv_expiry_delta: (9 << 4) | 1,
4064                         htlc_minimum_msat: None,
4065                         htlc_maximum_msat: None,
4066                 }]), RouteHint(vec![RouteHintHop {
4067                         src_node_id: nodes[5],
4068                         short_channel_id: 10,
4069                         fees: zero_fees,
4070                         cltv_expiry_delta: (10 << 4) | 1,
4071                         htlc_minimum_msat: None,
4072                         htlc_maximum_msat: None,
4073                 }])]
4074         }
4075
4076         #[test]
4077         fn partial_route_hint_test() {
4078                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4079                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4080                 let scorer = ln_test_utils::TestScorer::new();
4081                 let random_seed_bytes = [42; 32];
4082
4083                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
4084                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
4085                 // RouteHint may be partially used by the algo to build the best path.
4086
4087                 // First check that last hop can't have its source as the payee.
4088                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
4089                         src_node_id: nodes[6],
4090                         short_channel_id: 8,
4091                         fees: RoutingFees {
4092                                 base_msat: 1000,
4093                                 proportional_millionths: 0,
4094                         },
4095                         cltv_expiry_delta: (8 << 4) | 1,
4096                         htlc_minimum_msat: None,
4097                         htlc_maximum_msat: None,
4098                 }]);
4099
4100                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4101                 invalid_last_hops.push(invalid_last_hop);
4102                 {
4103                         let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4104                                 .with_route_hints(invalid_last_hops).unwrap();
4105                         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4106                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4107                                 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4108                                 &Default::default(), &random_seed_bytes) {
4109                                         assert_eq!(err, "Route hint cannot have the payee as the source.");
4110                         } else { panic!(); }
4111                 }
4112
4113                 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4114                         .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4115                 payment_params.max_path_length = 5;
4116                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4117                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4118                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4119                 assert_eq!(route.paths[0].hops.len(), 5);
4120
4121                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4122                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4123                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4124                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4125                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4126                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4127
4128                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4129                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4130                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4131                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4132                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4133                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4134
4135                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4136                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4137                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4138                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4139                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4140                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4141
4142                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4143                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4144                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4145                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4146                 // If we have a peer in the node map, we'll use their features here since we don't have
4147                 // a way of figuring out their features from the invoice:
4148                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4149                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4150
4151                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4152                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4153                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4154                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4155                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4156                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4157         }
4158
4159         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4160                 let zero_fees = RoutingFees {
4161                         base_msat: 0,
4162                         proportional_millionths: 0,
4163                 };
4164                 vec![RouteHint(vec![RouteHintHop {
4165                         src_node_id: nodes[3],
4166                         short_channel_id: 8,
4167                         fees: zero_fees,
4168                         cltv_expiry_delta: (8 << 4) | 1,
4169                         htlc_minimum_msat: None,
4170                         htlc_maximum_msat: None,
4171                 }]), RouteHint(vec![
4172
4173                 ]), RouteHint(vec![RouteHintHop {
4174                         src_node_id: nodes[5],
4175                         short_channel_id: 10,
4176                         fees: zero_fees,
4177                         cltv_expiry_delta: (10 << 4) | 1,
4178                         htlc_minimum_msat: None,
4179                         htlc_maximum_msat: None,
4180                 }])]
4181         }
4182
4183         #[test]
4184         fn ignores_empty_last_hops_test() {
4185                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4186                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4187                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4188                 let scorer = ln_test_utils::TestScorer::new();
4189                 let random_seed_bytes = [42; 32];
4190
4191                 // Test handling of an empty RouteHint passed in Invoice.
4192                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4193                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4194                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4195                 assert_eq!(route.paths[0].hops.len(), 5);
4196
4197                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4198                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4199                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4200                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4201                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4202                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4203
4204                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4205                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4206                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4207                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4208                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4209                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4210
4211                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4212                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4213                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4214                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4215                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4216                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4217
4218                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4219                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4220                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4221                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4222                 // If we have a peer in the node map, we'll use their features here since we don't have
4223                 // a way of figuring out their features from the invoice:
4224                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4225                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4226
4227                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4228                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4229                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4230                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4231                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4232                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4233         }
4234
4235         /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4236         /// and 0xff01.
4237         fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4238                 let zero_fees = RoutingFees {
4239                         base_msat: 0,
4240                         proportional_millionths: 0,
4241                 };
4242                 vec![RouteHint(vec![RouteHintHop {
4243                         src_node_id: hint_hops[0],
4244                         short_channel_id: 0xff00,
4245                         fees: RoutingFees {
4246                                 base_msat: 100,
4247                                 proportional_millionths: 0,
4248                         },
4249                         cltv_expiry_delta: (5 << 4) | 1,
4250                         htlc_minimum_msat: None,
4251                         htlc_maximum_msat: None,
4252                 }, RouteHintHop {
4253                         src_node_id: hint_hops[1],
4254                         short_channel_id: 0xff01,
4255                         fees: zero_fees,
4256                         cltv_expiry_delta: (8 << 4) | 1,
4257                         htlc_minimum_msat: None,
4258                         htlc_maximum_msat: None,
4259                 }])]
4260         }
4261
4262         #[test]
4263         fn multi_hint_last_hops_test() {
4264                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4265                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4266                 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4267                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4268                 let scorer = ln_test_utils::TestScorer::new();
4269                 let random_seed_bytes = [42; 32];
4270
4271                 // Test through channels 2, 3, 0xff00, 0xff01.
4272                 // Test shows that multi-hop route hints are considered and factored correctly into the
4273                 // max path length.
4274
4275                 // Disabling channels 6 & 7 by flags=2
4276                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4277                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4278                         short_channel_id: 6,
4279                         timestamp: 2,
4280                         flags: 2, // to disable
4281                         cltv_expiry_delta: 0,
4282                         htlc_minimum_msat: 0,
4283                         htlc_maximum_msat: MAX_VALUE_MSAT,
4284                         fee_base_msat: 0,
4285                         fee_proportional_millionths: 0,
4286                         excess_data: Vec::new()
4287                 });
4288                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4289                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4290                         short_channel_id: 7,
4291                         timestamp: 2,
4292                         flags: 2, // to disable
4293                         cltv_expiry_delta: 0,
4294                         htlc_minimum_msat: 0,
4295                         htlc_maximum_msat: MAX_VALUE_MSAT,
4296                         fee_base_msat: 0,
4297                         fee_proportional_millionths: 0,
4298                         excess_data: Vec::new()
4299                 });
4300
4301                 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4302                 route_params.payment_params.max_path_length = 4;
4303                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4304                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4305                 assert_eq!(route.paths[0].hops.len(), 4);
4306
4307                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4308                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4309                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4310                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4311                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4312                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4313
4314                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4315                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4316                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4317                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4318                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4319                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4320
4321                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4322                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4323                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4324                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4325                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4326                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4327
4328                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4329                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4330                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4331                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4332                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4333                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4334                 route_params.payment_params.max_path_length = 3;
4335                 get_route(&our_id, &route_params, &network_graph.read_only(), None,
4336                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
4337         }
4338
4339         #[test]
4340         fn private_multi_hint_last_hops_test() {
4341                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4342                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4343
4344                 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4345                 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4346
4347                 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4348                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4349                 let scorer = ln_test_utils::TestScorer::new();
4350                 // Test through channels 2, 3, 0xff00, 0xff01.
4351                 // Test shows that multiple hop hints are considered.
4352
4353                 // Disabling channels 6 & 7 by flags=2
4354                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4355                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4356                         short_channel_id: 6,
4357                         timestamp: 2,
4358                         flags: 2, // to disable
4359                         cltv_expiry_delta: 0,
4360                         htlc_minimum_msat: 0,
4361                         htlc_maximum_msat: MAX_VALUE_MSAT,
4362                         fee_base_msat: 0,
4363                         fee_proportional_millionths: 0,
4364                         excess_data: Vec::new()
4365                 });
4366                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4367                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4368                         short_channel_id: 7,
4369                         timestamp: 2,
4370                         flags: 2, // to disable
4371                         cltv_expiry_delta: 0,
4372                         htlc_minimum_msat: 0,
4373                         htlc_maximum_msat: MAX_VALUE_MSAT,
4374                         fee_base_msat: 0,
4375                         fee_proportional_millionths: 0,
4376                         excess_data: Vec::new()
4377                 });
4378
4379                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4380                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4381                         Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4382                 assert_eq!(route.paths[0].hops.len(), 4);
4383
4384                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4385                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4386                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4387                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4388                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4389                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4390
4391                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4392                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4393                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4394                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4395                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4396                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4397
4398                 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4399                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4400                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4401                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4402                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4403                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4404
4405                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4406                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4407                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4408                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4409                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4410                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4411         }
4412
4413         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4414                 let zero_fees = RoutingFees {
4415                         base_msat: 0,
4416                         proportional_millionths: 0,
4417                 };
4418                 vec![RouteHint(vec![RouteHintHop {
4419                         src_node_id: nodes[4],
4420                         short_channel_id: 11,
4421                         fees: zero_fees,
4422                         cltv_expiry_delta: (11 << 4) | 1,
4423                         htlc_minimum_msat: None,
4424                         htlc_maximum_msat: None,
4425                 }, RouteHintHop {
4426                         src_node_id: nodes[3],
4427                         short_channel_id: 8,
4428                         fees: zero_fees,
4429                         cltv_expiry_delta: (8 << 4) | 1,
4430                         htlc_minimum_msat: None,
4431                         htlc_maximum_msat: None,
4432                 }]), RouteHint(vec![RouteHintHop {
4433                         src_node_id: nodes[4],
4434                         short_channel_id: 9,
4435                         fees: RoutingFees {
4436                                 base_msat: 1001,
4437                                 proportional_millionths: 0,
4438                         },
4439                         cltv_expiry_delta: (9 << 4) | 1,
4440                         htlc_minimum_msat: None,
4441                         htlc_maximum_msat: None,
4442                 }]), RouteHint(vec![RouteHintHop {
4443                         src_node_id: nodes[5],
4444                         short_channel_id: 10,
4445                         fees: zero_fees,
4446                         cltv_expiry_delta: (10 << 4) | 1,
4447                         htlc_minimum_msat: None,
4448                         htlc_maximum_msat: None,
4449                 }])]
4450         }
4451
4452         #[test]
4453         fn last_hops_with_public_channel_test() {
4454                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4455                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4456                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4457                 let scorer = ln_test_utils::TestScorer::new();
4458                 let random_seed_bytes = [42; 32];
4459
4460                 // This test shows that public routes can be present in the invoice
4461                 // which would be handled in the same manner.
4462
4463                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4464                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4465                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4466                 assert_eq!(route.paths[0].hops.len(), 5);
4467
4468                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4469                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4470                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4471                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4472                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4473                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4474
4475                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4476                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4477                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4478                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4479                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4480                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4481
4482                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4483                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4484                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4485                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4486                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4487                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4488
4489                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4490                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4491                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4492                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4493                 // If we have a peer in the node map, we'll use their features here since we don't have
4494                 // a way of figuring out their features from the invoice:
4495                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4496                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4497
4498                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4499                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4500                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4501                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4502                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4503                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4504         }
4505
4506         #[test]
4507         fn our_chans_last_hop_connect_test() {
4508                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4509                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4510                 let scorer = ln_test_utils::TestScorer::new();
4511                 let random_seed_bytes = [42; 32];
4512
4513                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4514                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4515                 let mut last_hops = last_hops(&nodes);
4516                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4517                         .with_route_hints(last_hops.clone()).unwrap();
4518                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4519                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4520                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4521                         &Default::default(), &random_seed_bytes).unwrap();
4522                 assert_eq!(route.paths[0].hops.len(), 2);
4523
4524                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4525                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4526                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4527                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4528                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4529                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4530
4531                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4532                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4533                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4534                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4535                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4536                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4537
4538                 last_hops[0].0[0].fees.base_msat = 1000;
4539
4540                 // Revert to via 6 as the fee on 8 goes up
4541                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4542                         .with_route_hints(last_hops).unwrap();
4543                 let route_params = RouteParameters::from_payment_params_and_value(
4544                         payment_params.clone(), 100);
4545                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4546                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4547                 assert_eq!(route.paths[0].hops.len(), 4);
4548
4549                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4550                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4551                 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4552                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4553                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4554                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4555
4556                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4557                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4558                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4559                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4560                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4561                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4562
4563                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4564                 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4565                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4566                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4567                 // If we have a peer in the node map, we'll use their features here since we don't have
4568                 // a way of figuring out their features from the invoice:
4569                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4570                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4571
4572                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4573                 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4574                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4575                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4576                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4577                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4578
4579                 // ...but still use 8 for larger payments as 6 has a variable feerate
4580                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4581                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4582                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4583                 assert_eq!(route.paths[0].hops.len(), 5);
4584
4585                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4586                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4587                 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4588                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4589                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4590                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4591
4592                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4593                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4594                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4595                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4596                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4597                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4598
4599                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4600                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4601                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4602                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4603                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4604                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4605
4606                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4607                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4608                 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4609                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4610                 // If we have a peer in the node map, we'll use their features here since we don't have
4611                 // a way of figuring out their features from the invoice:
4612                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4613                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4614
4615                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4616                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4617                 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4618                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4619                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4620                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4621         }
4622
4623         fn do_unannounced_path_test(last_hop_htlc_max: Option<u64>, last_hop_fee_prop: u32, outbound_capacity_msat: u64, route_val: u64) -> Result<Route, LightningError> {
4624                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4625                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4626                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4627
4628                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4629                 let last_hops = RouteHint(vec![RouteHintHop {
4630                         src_node_id: middle_node_id,
4631                         short_channel_id: 8,
4632                         fees: RoutingFees {
4633                                 base_msat: 1000,
4634                                 proportional_millionths: last_hop_fee_prop,
4635                         },
4636                         cltv_expiry_delta: (8 << 4) | 1,
4637                         htlc_minimum_msat: None,
4638                         htlc_maximum_msat: last_hop_htlc_max,
4639                 }]);
4640                 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4641                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4642                 let scorer = ln_test_utils::TestScorer::new();
4643                 let random_seed_bytes = [42; 32];
4644                 let logger = ln_test_utils::TestLogger::new();
4645                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4646                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4647                 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4648                                 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4649                                 &random_seed_bytes);
4650                 route
4651         }
4652
4653         #[test]
4654         fn unannounced_path_test() {
4655                 // We should be able to send a payment to a destination without any help of a routing graph
4656                 // if we have a channel with a common counterparty that appears in the first and last hop
4657                 // hints.
4658                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4659
4660                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4661                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4662                 assert_eq!(route.paths[0].hops.len(), 2);
4663
4664                 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4665                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4666                 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4667                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4668                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4669                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4670
4671                 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4672                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4673                 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4674                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4675                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4676                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4677         }
4678
4679         #[test]
4680         fn overflow_unannounced_path_test_liquidity_underflow() {
4681                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4682                 // the last-hop had a fee which overflowed a u64, we'd panic.
4683                 // This was due to us adding the first-hop from us unconditionally, causing us to think
4684                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4685                 // In this test, we previously hit a subtraction underflow due to having less available
4686                 // liquidity at the last hop than 0.
4687                 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 0, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
4688         }
4689
4690         #[test]
4691         fn overflow_unannounced_path_test_feerate_overflow() {
4692                 // This tests for the same case as above, except instead of hitting a subtraction
4693                 // underflow, we hit a case where the fee charged at a hop overflowed.
4694                 assert!(do_unannounced_path_test(Some(21_000_000_0000_0000_000), 50000, 21_000_000_0000_0000_000, 21_000_000_0000_0000_000).is_err());
4695         }
4696
4697         #[test]
4698         fn available_amount_while_routing_test() {
4699                 // Tests whether we choose the correct available channel amount while routing.
4700
4701                 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4702                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4703                 let scorer = ln_test_utils::TestScorer::new();
4704                 let random_seed_bytes = [42; 32];
4705                 let config = UserConfig::default();
4706                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4707                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4708                         .unwrap();
4709
4710                 // We will use a simple single-path route from
4711                 // our node to node2 via node0: channels {1, 3}.
4712
4713                 // First disable all other paths.
4714                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4715                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4716                         short_channel_id: 2,
4717                         timestamp: 2,
4718                         flags: 2,
4719                         cltv_expiry_delta: 0,
4720                         htlc_minimum_msat: 0,
4721                         htlc_maximum_msat: 100_000,
4722                         fee_base_msat: 0,
4723                         fee_proportional_millionths: 0,
4724                         excess_data: Vec::new()
4725                 });
4726                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4727                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4728                         short_channel_id: 12,
4729                         timestamp: 2,
4730                         flags: 2,
4731                         cltv_expiry_delta: 0,
4732                         htlc_minimum_msat: 0,
4733                         htlc_maximum_msat: 100_000,
4734                         fee_base_msat: 0,
4735                         fee_proportional_millionths: 0,
4736                         excess_data: Vec::new()
4737                 });
4738
4739                 // Make the first channel (#1) very permissive,
4740                 // and we will be testing all limits on the second channel.
4741                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4742                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4743                         short_channel_id: 1,
4744                         timestamp: 2,
4745                         flags: 0,
4746                         cltv_expiry_delta: 0,
4747                         htlc_minimum_msat: 0,
4748                         htlc_maximum_msat: 1_000_000_000,
4749                         fee_base_msat: 0,
4750                         fee_proportional_millionths: 0,
4751                         excess_data: Vec::new()
4752                 });
4753
4754                 // First, let's see if routing works if we have absolutely no idea about the available amount.
4755                 // In this case, it should be set to 250_000 sats.
4756                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4757                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4758                         short_channel_id: 3,
4759                         timestamp: 2,
4760                         flags: 0,
4761                         cltv_expiry_delta: 0,
4762                         htlc_minimum_msat: 0,
4763                         htlc_maximum_msat: 250_000_000,
4764                         fee_base_msat: 0,
4765                         fee_proportional_millionths: 0,
4766                         excess_data: Vec::new()
4767                 });
4768
4769                 {
4770                         // Attempt to route more than available results in a failure.
4771                         let route_params = RouteParameters::from_payment_params_and_value(
4772                                 payment_params.clone(), 250_000_001);
4773                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4774                                         &our_id, &route_params, &network_graph.read_only(), None,
4775                                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4776                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4777                         } else { panic!(); }
4778                 }
4779
4780                 {
4781                         // Now, attempt to route an exact amount we have should be fine.
4782                         let route_params = RouteParameters::from_payment_params_and_value(
4783                                 payment_params.clone(), 250_000_000);
4784                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4785                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4786                         assert_eq!(route.paths.len(), 1);
4787                         let path = route.paths.last().unwrap();
4788                         assert_eq!(path.hops.len(), 2);
4789                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4790                         assert_eq!(path.final_value_msat(), 250_000_000);
4791                 }
4792
4793                 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4794                 // Disable channel #1 and use another first hop.
4795                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4796                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4797                         short_channel_id: 1,
4798                         timestamp: 3,
4799                         flags: 2,
4800                         cltv_expiry_delta: 0,
4801                         htlc_minimum_msat: 0,
4802                         htlc_maximum_msat: 1_000_000_000,
4803                         fee_base_msat: 0,
4804                         fee_proportional_millionths: 0,
4805                         excess_data: Vec::new()
4806                 });
4807
4808                 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4809                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4810
4811                 {
4812                         // Attempt to route more than available results in a failure.
4813                         let route_params = RouteParameters::from_payment_params_and_value(
4814                                 payment_params.clone(), 200_000_001);
4815                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4816                                         &our_id, &route_params, &network_graph.read_only(),
4817                                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4818                                         &Default::default(), &random_seed_bytes) {
4819                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4820                         } else { panic!(); }
4821                 }
4822
4823                 {
4824                         // Now, attempt to route an exact amount we have should be fine.
4825                         let route_params = RouteParameters::from_payment_params_and_value(
4826                                 payment_params.clone(), 200_000_000);
4827                         let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4828                                 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4829                                 &Default::default(), &random_seed_bytes).unwrap();
4830                         assert_eq!(route.paths.len(), 1);
4831                         let path = route.paths.last().unwrap();
4832                         assert_eq!(path.hops.len(), 2);
4833                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4834                         assert_eq!(path.final_value_msat(), 200_000_000);
4835                 }
4836
4837                 // Enable channel #1 back.
4838                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4839                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4840                         short_channel_id: 1,
4841                         timestamp: 4,
4842                         flags: 0,
4843                         cltv_expiry_delta: 0,
4844                         htlc_minimum_msat: 0,
4845                         htlc_maximum_msat: 1_000_000_000,
4846                         fee_base_msat: 0,
4847                         fee_proportional_millionths: 0,
4848                         excess_data: Vec::new()
4849                 });
4850
4851
4852                 // Now let's see if routing works if we know only htlc_maximum_msat.
4853                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4854                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4855                         short_channel_id: 3,
4856                         timestamp: 3,
4857                         flags: 0,
4858                         cltv_expiry_delta: 0,
4859                         htlc_minimum_msat: 0,
4860                         htlc_maximum_msat: 15_000,
4861                         fee_base_msat: 0,
4862                         fee_proportional_millionths: 0,
4863                         excess_data: Vec::new()
4864                 });
4865
4866                 {
4867                         // Attempt to route more than available results in a failure.
4868                         let route_params = RouteParameters::from_payment_params_and_value(
4869                                 payment_params.clone(), 15_001);
4870                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4871                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4872                                         &scorer, &Default::default(), &random_seed_bytes) {
4873                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4874                         } else { panic!(); }
4875                 }
4876
4877                 {
4878                         // Now, attempt to route an exact amount we have should be fine.
4879                         let route_params = RouteParameters::from_payment_params_and_value(
4880                                 payment_params.clone(), 15_000);
4881                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4882                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4883                         assert_eq!(route.paths.len(), 1);
4884                         let path = route.paths.last().unwrap();
4885                         assert_eq!(path.hops.len(), 2);
4886                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4887                         assert_eq!(path.final_value_msat(), 15_000);
4888                 }
4889
4890                 // Now let's see if routing works if we know only capacity from the UTXO.
4891
4892                 // We can't change UTXO capacity on the fly, so we'll disable
4893                 // the existing channel and add another one with the capacity we need.
4894                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4895                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4896                         short_channel_id: 3,
4897                         timestamp: 4,
4898                         flags: 2,
4899                         cltv_expiry_delta: 0,
4900                         htlc_minimum_msat: 0,
4901                         htlc_maximum_msat: MAX_VALUE_MSAT,
4902                         fee_base_msat: 0,
4903                         fee_proportional_millionths: 0,
4904                         excess_data: Vec::new()
4905                 });
4906
4907                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4908                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4909                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4910                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4911                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_p2wsh();
4912
4913                 *chain_monitor.utxo_ret.lock().unwrap() =
4914                         UtxoResult::Sync(Ok(TxOut { value: Amount::from_sat(15), script_pubkey: good_script.clone() }));
4915                 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4916
4917                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4918                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4919                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4920                         short_channel_id: 333,
4921                         timestamp: 1,
4922                         flags: 0,
4923                         cltv_expiry_delta: (3 << 4) | 1,
4924                         htlc_minimum_msat: 0,
4925                         htlc_maximum_msat: 15_000,
4926                         fee_base_msat: 0,
4927                         fee_proportional_millionths: 0,
4928                         excess_data: Vec::new()
4929                 });
4930                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4931                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4932                         short_channel_id: 333,
4933                         timestamp: 1,
4934                         flags: 1,
4935                         cltv_expiry_delta: (3 << 4) | 2,
4936                         htlc_minimum_msat: 0,
4937                         htlc_maximum_msat: 15_000,
4938                         fee_base_msat: 100,
4939                         fee_proportional_millionths: 0,
4940                         excess_data: Vec::new()
4941                 });
4942
4943                 {
4944                         // Attempt to route more than available results in a failure.
4945                         let route_params = RouteParameters::from_payment_params_and_value(
4946                                 payment_params.clone(), 15_001);
4947                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4948                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4949                                         &scorer, &Default::default(), &random_seed_bytes) {
4950                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4951                         } else { panic!(); }
4952                 }
4953
4954                 {
4955                         // Now, attempt to route an exact amount we have should be fine.
4956                         let route_params = RouteParameters::from_payment_params_and_value(
4957                                 payment_params.clone(), 15_000);
4958                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4959                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4960                         assert_eq!(route.paths.len(), 1);
4961                         let path = route.paths.last().unwrap();
4962                         assert_eq!(path.hops.len(), 2);
4963                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4964                         assert_eq!(path.final_value_msat(), 15_000);
4965                 }
4966
4967                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4968                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4969                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4970                         short_channel_id: 333,
4971                         timestamp: 6,
4972                         flags: 0,
4973                         cltv_expiry_delta: 0,
4974                         htlc_minimum_msat: 0,
4975                         htlc_maximum_msat: 10_000,
4976                         fee_base_msat: 0,
4977                         fee_proportional_millionths: 0,
4978                         excess_data: Vec::new()
4979                 });
4980
4981                 {
4982                         // Attempt to route more than available results in a failure.
4983                         let route_params = RouteParameters::from_payment_params_and_value(
4984                                 payment_params.clone(), 10_001);
4985                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4986                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4987                                         &scorer, &Default::default(), &random_seed_bytes) {
4988                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4989                         } else { panic!(); }
4990                 }
4991
4992                 {
4993                         // Now, attempt to route an exact amount we have should be fine.
4994                         let route_params = RouteParameters::from_payment_params_and_value(
4995                                 payment_params.clone(), 10_000);
4996                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4997                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4998                         assert_eq!(route.paths.len(), 1);
4999                         let path = route.paths.last().unwrap();
5000                         assert_eq!(path.hops.len(), 2);
5001                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5002                         assert_eq!(path.final_value_msat(), 10_000);
5003                 }
5004         }
5005
5006         #[test]
5007         fn available_liquidity_last_hop_test() {
5008                 // Check that available liquidity properly limits the path even when only
5009                 // one of the latter hops is limited.
5010                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5011                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5012                 let scorer = ln_test_utils::TestScorer::new();
5013                 let random_seed_bytes = [42; 32];
5014                 let config = UserConfig::default();
5015                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5016                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5017                         .unwrap();
5018
5019                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5020                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5021                 // Total capacity: 50 sats.
5022
5023                 // Disable other potential paths.
5024                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5025                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5026                         short_channel_id: 2,
5027                         timestamp: 2,
5028                         flags: 2,
5029                         cltv_expiry_delta: 0,
5030                         htlc_minimum_msat: 0,
5031                         htlc_maximum_msat: 100_000,
5032                         fee_base_msat: 0,
5033                         fee_proportional_millionths: 0,
5034                         excess_data: Vec::new()
5035                 });
5036                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5037                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5038                         short_channel_id: 7,
5039                         timestamp: 2,
5040                         flags: 2,
5041                         cltv_expiry_delta: 0,
5042                         htlc_minimum_msat: 0,
5043                         htlc_maximum_msat: 100_000,
5044                         fee_base_msat: 0,
5045                         fee_proportional_millionths: 0,
5046                         excess_data: Vec::new()
5047                 });
5048
5049                 // Limit capacities
5050
5051                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5052                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5053                         short_channel_id: 12,
5054                         timestamp: 2,
5055                         flags: 0,
5056                         cltv_expiry_delta: 0,
5057                         htlc_minimum_msat: 0,
5058                         htlc_maximum_msat: 100_000,
5059                         fee_base_msat: 0,
5060                         fee_proportional_millionths: 0,
5061                         excess_data: Vec::new()
5062                 });
5063                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5064                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5065                         short_channel_id: 13,
5066                         timestamp: 2,
5067                         flags: 0,
5068                         cltv_expiry_delta: 0,
5069                         htlc_minimum_msat: 0,
5070                         htlc_maximum_msat: 100_000,
5071                         fee_base_msat: 0,
5072                         fee_proportional_millionths: 0,
5073                         excess_data: Vec::new()
5074                 });
5075
5076                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5077                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5078                         short_channel_id: 6,
5079                         timestamp: 2,
5080                         flags: 0,
5081                         cltv_expiry_delta: 0,
5082                         htlc_minimum_msat: 0,
5083                         htlc_maximum_msat: 50_000,
5084                         fee_base_msat: 0,
5085                         fee_proportional_millionths: 0,
5086                         excess_data: Vec::new()
5087                 });
5088                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5089                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5090                         short_channel_id: 11,
5091                         timestamp: 2,
5092                         flags: 0,
5093                         cltv_expiry_delta: 0,
5094                         htlc_minimum_msat: 0,
5095                         htlc_maximum_msat: 100_000,
5096                         fee_base_msat: 0,
5097                         fee_proportional_millionths: 0,
5098                         excess_data: Vec::new()
5099                 });
5100                 {
5101                         // Attempt to route more than available results in a failure.
5102                         let route_params = RouteParameters::from_payment_params_and_value(
5103                                 payment_params.clone(), 60_000);
5104                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5105                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5106                                         &scorer, &Default::default(), &random_seed_bytes) {
5107                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5108                         } else { panic!(); }
5109                 }
5110
5111                 {
5112                         // Now, attempt to route 49 sats (just a bit below the capacity).
5113                         let route_params = RouteParameters::from_payment_params_and_value(
5114                                 payment_params.clone(), 49_000);
5115                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5116                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5117                         assert_eq!(route.paths.len(), 1);
5118                         let mut total_amount_paid_msat = 0;
5119                         for path in &route.paths {
5120                                 assert_eq!(path.hops.len(), 4);
5121                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5122                                 total_amount_paid_msat += path.final_value_msat();
5123                         }
5124                         assert_eq!(total_amount_paid_msat, 49_000);
5125                 }
5126
5127                 {
5128                         // Attempt to route an exact amount is also fine
5129                         let route_params = RouteParameters::from_payment_params_and_value(
5130                                 payment_params, 50_000);
5131                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5132                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5133                         assert_eq!(route.paths.len(), 1);
5134                         let mut total_amount_paid_msat = 0;
5135                         for path in &route.paths {
5136                                 assert_eq!(path.hops.len(), 4);
5137                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5138                                 total_amount_paid_msat += path.final_value_msat();
5139                         }
5140                         assert_eq!(total_amount_paid_msat, 50_000);
5141                 }
5142         }
5143
5144         #[test]
5145         fn ignore_fee_first_hop_test() {
5146                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5147                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5148                 let scorer = ln_test_utils::TestScorer::new();
5149                 let random_seed_bytes = [42; 32];
5150                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5151
5152                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5153                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5154                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5155                         short_channel_id: 1,
5156                         timestamp: 2,
5157                         flags: 0,
5158                         cltv_expiry_delta: 0,
5159                         htlc_minimum_msat: 0,
5160                         htlc_maximum_msat: 100_000,
5161                         fee_base_msat: 1_000_000,
5162                         fee_proportional_millionths: 0,
5163                         excess_data: Vec::new()
5164                 });
5165                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5166                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5167                         short_channel_id: 3,
5168                         timestamp: 2,
5169                         flags: 0,
5170                         cltv_expiry_delta: 0,
5171                         htlc_minimum_msat: 0,
5172                         htlc_maximum_msat: 50_000,
5173                         fee_base_msat: 0,
5174                         fee_proportional_millionths: 0,
5175                         excess_data: Vec::new()
5176                 });
5177
5178                 {
5179                         let route_params = RouteParameters::from_payment_params_and_value(
5180                                 payment_params, 50_000);
5181                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5182                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5183                         assert_eq!(route.paths.len(), 1);
5184                         let mut total_amount_paid_msat = 0;
5185                         for path in &route.paths {
5186                                 assert_eq!(path.hops.len(), 2);
5187                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5188                                 total_amount_paid_msat += path.final_value_msat();
5189                         }
5190                         assert_eq!(total_amount_paid_msat, 50_000);
5191                 }
5192         }
5193
5194         #[test]
5195         fn simple_mpp_route_test() {
5196                 let (secp_ctx, _, _, _, _) = build_graph();
5197                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5198                 let config = UserConfig::default();
5199                 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5200                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5201                         .unwrap();
5202                 do_simple_mpp_route_test(clear_payment_params);
5203
5204                 // MPP to a 1-hop blinded path for nodes[2]
5205                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5206                 let blinded_path = BlindedPath {
5207                         introduction_node: IntroductionNode::NodeId(nodes[2]),
5208                         blinding_point: ln_test_utils::pubkey(42),
5209                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5210                 };
5211                 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5212                         fee_base_msat: 0,
5213                         fee_proportional_millionths: 0,
5214                         htlc_minimum_msat: 0,
5215                         htlc_maximum_msat: 0,
5216                         cltv_expiry_delta: 0,
5217                         features: BlindedHopFeatures::empty(),
5218                 };
5219                 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5220                         .with_bolt12_features(bolt12_features.clone()).unwrap();
5221                 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5222
5223                 // MPP to 3 2-hop blinded paths
5224                 let mut blinded_path_node_0 = blinded_path.clone();
5225                 blinded_path_node_0.introduction_node = IntroductionNode::NodeId(nodes[0]);
5226                 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5227                 let mut node_0_payinfo = blinded_payinfo.clone();
5228                 node_0_payinfo.htlc_maximum_msat = 50_000;
5229
5230                 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5231                 blinded_path_node_7.introduction_node = IntroductionNode::NodeId(nodes[7]);
5232                 let mut node_7_payinfo = blinded_payinfo.clone();
5233                 node_7_payinfo.htlc_maximum_msat = 60_000;
5234
5235                 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5236                 blinded_path_node_1.introduction_node = IntroductionNode::NodeId(nodes[1]);
5237                 let mut node_1_payinfo = blinded_payinfo.clone();
5238                 node_1_payinfo.htlc_maximum_msat = 180_000;
5239
5240                 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5241                         vec![
5242                                 (node_0_payinfo, blinded_path_node_0),
5243                                 (node_7_payinfo, blinded_path_node_7),
5244                                 (node_1_payinfo, blinded_path_node_1)
5245                         ])
5246                         .with_bolt12_features(bolt12_features).unwrap();
5247                 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5248         }
5249
5250
5251         fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5252                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5253                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5254                 let scorer = ln_test_utils::TestScorer::new();
5255                 let random_seed_bytes = [42; 32];
5256
5257                 // We need a route consisting of 3 paths:
5258                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5259                 // To achieve this, the amount being transferred should be around
5260                 // the total capacity of these 3 paths.
5261
5262                 // First, we set limits on these (previously unlimited) channels.
5263                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5264
5265                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5266                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5267                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5268                         short_channel_id: 1,
5269                         timestamp: 2,
5270                         flags: 0,
5271                         cltv_expiry_delta: 0,
5272                         htlc_minimum_msat: 0,
5273                         htlc_maximum_msat: 100_000,
5274                         fee_base_msat: 0,
5275                         fee_proportional_millionths: 0,
5276                         excess_data: Vec::new()
5277                 });
5278                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5279                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5280                         short_channel_id: 3,
5281                         timestamp: 2,
5282                         flags: 0,
5283                         cltv_expiry_delta: 0,
5284                         htlc_minimum_msat: 0,
5285                         htlc_maximum_msat: 50_000,
5286                         fee_base_msat: 0,
5287                         fee_proportional_millionths: 0,
5288                         excess_data: Vec::new()
5289                 });
5290
5291                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5292                 // (total limit 60).
5293                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5294                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5295                         short_channel_id: 12,
5296                         timestamp: 2,
5297                         flags: 0,
5298                         cltv_expiry_delta: 0,
5299                         htlc_minimum_msat: 0,
5300                         htlc_maximum_msat: 60_000,
5301                         fee_base_msat: 0,
5302                         fee_proportional_millionths: 0,
5303                         excess_data: Vec::new()
5304                 });
5305                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5306                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5307                         short_channel_id: 13,
5308                         timestamp: 2,
5309                         flags: 0,
5310                         cltv_expiry_delta: 0,
5311                         htlc_minimum_msat: 0,
5312                         htlc_maximum_msat: 60_000,
5313                         fee_base_msat: 0,
5314                         fee_proportional_millionths: 0,
5315                         excess_data: Vec::new()
5316                 });
5317
5318                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5319                 // (total capacity 180 sats).
5320                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5321                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5322                         short_channel_id: 2,
5323                         timestamp: 2,
5324                         flags: 0,
5325                         cltv_expiry_delta: 0,
5326                         htlc_minimum_msat: 0,
5327                         htlc_maximum_msat: 200_000,
5328                         fee_base_msat: 0,
5329                         fee_proportional_millionths: 0,
5330                         excess_data: Vec::new()
5331                 });
5332                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5333                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5334                         short_channel_id: 4,
5335                         timestamp: 2,
5336                         flags: 0,
5337                         cltv_expiry_delta: 0,
5338                         htlc_minimum_msat: 0,
5339                         htlc_maximum_msat: 180_000,
5340                         fee_base_msat: 0,
5341                         fee_proportional_millionths: 0,
5342                         excess_data: Vec::new()
5343                 });
5344
5345                 {
5346                         // Attempt to route more than available results in a failure.
5347                         let route_params = RouteParameters::from_payment_params_and_value(
5348                                 payment_params.clone(), 300_000);
5349                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5350                                 &our_id, &route_params, &network_graph.read_only(), None,
5351                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5352                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
5353                         } else { panic!(); }
5354                 }
5355
5356                 {
5357                         // Attempt to route while setting max_path_count to 0 results in a failure.
5358                         let zero_payment_params = payment_params.clone().with_max_path_count(0);
5359                         let route_params = RouteParameters::from_payment_params_and_value(
5360                                 zero_payment_params, 100);
5361                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5362                                 &our_id, &route_params, &network_graph.read_only(), None,
5363                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5364                                         assert_eq!(err, "Can't find a route with no paths allowed.");
5365                         } else { panic!(); }
5366                 }
5367
5368                 {
5369                         // Attempt to route while setting max_path_count to 3 results in a failure.
5370                         // This is the case because the minimal_value_contribution_msat would require each path
5371                         // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5372                         let fail_payment_params = payment_params.clone().with_max_path_count(3);
5373                         let route_params = RouteParameters::from_payment_params_and_value(
5374                                 fail_payment_params, 250_000);
5375                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5376                                 &our_id, &route_params, &network_graph.read_only(), None,
5377                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5378                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
5379                         } else { panic!(); }
5380                 }
5381
5382                 {
5383                         // Now, attempt to route 250 sats (just a bit below the capacity).
5384                         // Our algorithm should provide us with these 3 paths.
5385                         let route_params = RouteParameters::from_payment_params_and_value(
5386                                 payment_params.clone(), 250_000);
5387                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5388                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5389                         assert_eq!(route.paths.len(), 3);
5390                         let mut total_amount_paid_msat = 0;
5391                         for path in &route.paths {
5392                                 if let Some(bt) = &path.blinded_tail {
5393                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5394                                 } else {
5395                                         assert_eq!(path.hops.len(), 2);
5396                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5397                                 }
5398                                 total_amount_paid_msat += path.final_value_msat();
5399                         }
5400                         assert_eq!(total_amount_paid_msat, 250_000);
5401                 }
5402
5403                 {
5404                         // Attempt to route an exact amount is also fine
5405                         let route_params = RouteParameters::from_payment_params_and_value(
5406                                 payment_params.clone(), 290_000);
5407                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5408                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5409                         assert_eq!(route.paths.len(), 3);
5410                         let mut total_amount_paid_msat = 0;
5411                         for path in &route.paths {
5412                                 if payment_params.payee.blinded_route_hints().len() != 0 {
5413                                         assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5414                                 if let Some(bt) = &path.blinded_tail {
5415                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5416                                         if bt.hops.len() > 1 {
5417                                                 let network_graph = network_graph.read_only();
5418                                                 assert_eq!(
5419                                                         NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5420                                                         payment_params.payee.blinded_route_hints().iter()
5421                                                                 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5422                                                                 .and_then(|(_, p)| p.public_introduction_node_id(&network_graph))
5423                                                                 .copied()
5424                                                                 .unwrap()
5425                                                 );
5426                                         } else {
5427                                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5428                                         }
5429                                 } else {
5430                                         assert_eq!(path.hops.len(), 2);
5431                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5432                                 }
5433                                 total_amount_paid_msat += path.final_value_msat();
5434                         }
5435                         assert_eq!(total_amount_paid_msat, 290_000);
5436                 }
5437         }
5438
5439         #[test]
5440         fn long_mpp_route_test() {
5441                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5442                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5443                 let scorer = ln_test_utils::TestScorer::new();
5444                 let random_seed_bytes = [42; 32];
5445                 let config = UserConfig::default();
5446                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5447                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5448                         .unwrap();
5449
5450                 // We need a route consisting of 3 paths:
5451                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5452                 // Note that these paths overlap (channels 5, 12, 13).
5453                 // We will route 300 sats.
5454                 // Each path will have 100 sats capacity, those channels which
5455                 // are used twice will have 200 sats capacity.
5456
5457                 // Disable other potential paths.
5458                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5459                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5460                         short_channel_id: 2,
5461                         timestamp: 2,
5462                         flags: 2,
5463                         cltv_expiry_delta: 0,
5464                         htlc_minimum_msat: 0,
5465                         htlc_maximum_msat: 100_000,
5466                         fee_base_msat: 0,
5467                         fee_proportional_millionths: 0,
5468                         excess_data: Vec::new()
5469                 });
5470                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5471                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5472                         short_channel_id: 7,
5473                         timestamp: 2,
5474                         flags: 2,
5475                         cltv_expiry_delta: 0,
5476                         htlc_minimum_msat: 0,
5477                         htlc_maximum_msat: 100_000,
5478                         fee_base_msat: 0,
5479                         fee_proportional_millionths: 0,
5480                         excess_data: Vec::new()
5481                 });
5482
5483                 // Path via {node0, node2} is channels {1, 3, 5}.
5484                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5485                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5486                         short_channel_id: 1,
5487                         timestamp: 2,
5488                         flags: 0,
5489                         cltv_expiry_delta: 0,
5490                         htlc_minimum_msat: 0,
5491                         htlc_maximum_msat: 100_000,
5492                         fee_base_msat: 0,
5493                         fee_proportional_millionths: 0,
5494                         excess_data: Vec::new()
5495                 });
5496                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5497                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5498                         short_channel_id: 3,
5499                         timestamp: 2,
5500                         flags: 0,
5501                         cltv_expiry_delta: 0,
5502                         htlc_minimum_msat: 0,
5503                         htlc_maximum_msat: 100_000,
5504                         fee_base_msat: 0,
5505                         fee_proportional_millionths: 0,
5506                         excess_data: Vec::new()
5507                 });
5508
5509                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5510                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5511                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5512                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5513                         short_channel_id: 5,
5514                         timestamp: 2,
5515                         flags: 0,
5516                         cltv_expiry_delta: 0,
5517                         htlc_minimum_msat: 0,
5518                         htlc_maximum_msat: 200_000,
5519                         fee_base_msat: 0,
5520                         fee_proportional_millionths: 0,
5521                         excess_data: Vec::new()
5522                 });
5523                 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5524                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5525                         short_channel_id: 5,
5526                         timestamp: 2,
5527                         flags: 3, // disable direction 1
5528                         cltv_expiry_delta: 0,
5529                         htlc_minimum_msat: 0,
5530                         htlc_maximum_msat: 200_000,
5531                         fee_base_msat: 0,
5532                         fee_proportional_millionths: 0,
5533                         excess_data: Vec::new()
5534                 });
5535
5536                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5537                 // Add 100 sats to the capacities of {12, 13}, because these channels
5538                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5539                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5540                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5541                         short_channel_id: 12,
5542                         timestamp: 2,
5543                         flags: 0,
5544                         cltv_expiry_delta: 0,
5545                         htlc_minimum_msat: 0,
5546                         htlc_maximum_msat: 200_000,
5547                         fee_base_msat: 0,
5548                         fee_proportional_millionths: 0,
5549                         excess_data: Vec::new()
5550                 });
5551                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5552                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5553                         short_channel_id: 13,
5554                         timestamp: 2,
5555                         flags: 0,
5556                         cltv_expiry_delta: 0,
5557                         htlc_minimum_msat: 0,
5558                         htlc_maximum_msat: 200_000,
5559                         fee_base_msat: 0,
5560                         fee_proportional_millionths: 0,
5561                         excess_data: Vec::new()
5562                 });
5563
5564                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5565                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5566                         short_channel_id: 6,
5567                         timestamp: 2,
5568                         flags: 0,
5569                         cltv_expiry_delta: 0,
5570                         htlc_minimum_msat: 0,
5571                         htlc_maximum_msat: 100_000,
5572                         fee_base_msat: 0,
5573                         fee_proportional_millionths: 0,
5574                         excess_data: Vec::new()
5575                 });
5576                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5577                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5578                         short_channel_id: 11,
5579                         timestamp: 2,
5580                         flags: 0,
5581                         cltv_expiry_delta: 0,
5582                         htlc_minimum_msat: 0,
5583                         htlc_maximum_msat: 100_000,
5584                         fee_base_msat: 0,
5585                         fee_proportional_millionths: 0,
5586                         excess_data: Vec::new()
5587                 });
5588
5589                 // Path via {node7, node2} is channels {12, 13, 5}.
5590                 // We already limited them to 200 sats (they are used twice for 100 sats).
5591                 // Nothing to do here.
5592
5593                 {
5594                         // Attempt to route more than available results in a failure.
5595                         let route_params = RouteParameters::from_payment_params_and_value(
5596                                 payment_params.clone(), 350_000);
5597                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5598                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5599                                         &scorer, &Default::default(), &random_seed_bytes) {
5600                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5601                         } else { panic!(); }
5602                 }
5603
5604                 {
5605                         // Now, attempt to route 300 sats (exact amount we can route).
5606                         // Our algorithm should provide us with these 3 paths, 100 sats each.
5607                         let route_params = RouteParameters::from_payment_params_and_value(
5608                                 payment_params, 300_000);
5609                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5610                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5611                         assert_eq!(route.paths.len(), 3);
5612
5613                         let mut total_amount_paid_msat = 0;
5614                         for path in &route.paths {
5615                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5616                                 total_amount_paid_msat += path.final_value_msat();
5617                         }
5618                         assert_eq!(total_amount_paid_msat, 300_000);
5619                 }
5620
5621         }
5622
5623         #[test]
5624         fn mpp_cheaper_route_test() {
5625                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5626                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5627                 let scorer = ln_test_utils::TestScorer::new();
5628                 let random_seed_bytes = [42; 32];
5629                 let config = UserConfig::default();
5630                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5631                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5632                         .unwrap();
5633
5634                 // This test checks that if we have two cheaper paths and one more expensive path,
5635                 // so that liquidity-wise any 2 of 3 combination is sufficient,
5636                 // two cheaper paths will be taken.
5637                 // These paths have equal available liquidity.
5638
5639                 // We need a combination of 3 paths:
5640                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5641                 // Note that these paths overlap (channels 5, 12, 13).
5642                 // Each path will have 100 sats capacity, those channels which
5643                 // are used twice will have 200 sats capacity.
5644
5645                 // Disable other potential paths.
5646                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5647                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5648                         short_channel_id: 2,
5649                         timestamp: 2,
5650                         flags: 2,
5651                         cltv_expiry_delta: 0,
5652                         htlc_minimum_msat: 0,
5653                         htlc_maximum_msat: 100_000,
5654                         fee_base_msat: 0,
5655                         fee_proportional_millionths: 0,
5656                         excess_data: Vec::new()
5657                 });
5658                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5659                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5660                         short_channel_id: 7,
5661                         timestamp: 2,
5662                         flags: 2,
5663                         cltv_expiry_delta: 0,
5664                         htlc_minimum_msat: 0,
5665                         htlc_maximum_msat: 100_000,
5666                         fee_base_msat: 0,
5667                         fee_proportional_millionths: 0,
5668                         excess_data: Vec::new()
5669                 });
5670
5671                 // Path via {node0, node2} is channels {1, 3, 5}.
5672                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5673                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5674                         short_channel_id: 1,
5675                         timestamp: 2,
5676                         flags: 0,
5677                         cltv_expiry_delta: 0,
5678                         htlc_minimum_msat: 0,
5679                         htlc_maximum_msat: 100_000,
5680                         fee_base_msat: 0,
5681                         fee_proportional_millionths: 0,
5682                         excess_data: Vec::new()
5683                 });
5684                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5685                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5686                         short_channel_id: 3,
5687                         timestamp: 2,
5688                         flags: 0,
5689                         cltv_expiry_delta: 0,
5690                         htlc_minimum_msat: 0,
5691                         htlc_maximum_msat: 100_000,
5692                         fee_base_msat: 0,
5693                         fee_proportional_millionths: 0,
5694                         excess_data: Vec::new()
5695                 });
5696
5697                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5698                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5699                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5700                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5701                         short_channel_id: 5,
5702                         timestamp: 2,
5703                         flags: 0,
5704                         cltv_expiry_delta: 0,
5705                         htlc_minimum_msat: 0,
5706                         htlc_maximum_msat: 200_000,
5707                         fee_base_msat: 0,
5708                         fee_proportional_millionths: 0,
5709                         excess_data: Vec::new()
5710                 });
5711                 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5712                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5713                         short_channel_id: 5,
5714                         timestamp: 2,
5715                         flags: 3, // disable direction 1
5716                         cltv_expiry_delta: 0,
5717                         htlc_minimum_msat: 0,
5718                         htlc_maximum_msat: 200_000,
5719                         fee_base_msat: 0,
5720                         fee_proportional_millionths: 0,
5721                         excess_data: Vec::new()
5722                 });
5723
5724                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5725                 // Add 100 sats to the capacities of {12, 13}, because these channels
5726                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5727                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5728                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5729                         short_channel_id: 12,
5730                         timestamp: 2,
5731                         flags: 0,
5732                         cltv_expiry_delta: 0,
5733                         htlc_minimum_msat: 0,
5734                         htlc_maximum_msat: 200_000,
5735                         fee_base_msat: 0,
5736                         fee_proportional_millionths: 0,
5737                         excess_data: Vec::new()
5738                 });
5739                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5740                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5741                         short_channel_id: 13,
5742                         timestamp: 2,
5743                         flags: 0,
5744                         cltv_expiry_delta: 0,
5745                         htlc_minimum_msat: 0,
5746                         htlc_maximum_msat: 200_000,
5747                         fee_base_msat: 0,
5748                         fee_proportional_millionths: 0,
5749                         excess_data: Vec::new()
5750                 });
5751
5752                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5753                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5754                         short_channel_id: 6,
5755                         timestamp: 2,
5756                         flags: 0,
5757                         cltv_expiry_delta: 0,
5758                         htlc_minimum_msat: 0,
5759                         htlc_maximum_msat: 100_000,
5760                         fee_base_msat: 1_000,
5761                         fee_proportional_millionths: 0,
5762                         excess_data: Vec::new()
5763                 });
5764                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5765                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5766                         short_channel_id: 11,
5767                         timestamp: 2,
5768                         flags: 0,
5769                         cltv_expiry_delta: 0,
5770                         htlc_minimum_msat: 0,
5771                         htlc_maximum_msat: 100_000,
5772                         fee_base_msat: 0,
5773                         fee_proportional_millionths: 0,
5774                         excess_data: Vec::new()
5775                 });
5776
5777                 // Path via {node7, node2} is channels {12, 13, 5}.
5778                 // We already limited them to 200 sats (they are used twice for 100 sats).
5779                 // Nothing to do here.
5780
5781                 {
5782                         // Now, attempt to route 180 sats.
5783                         // Our algorithm should provide us with these 2 paths.
5784                         let route_params = RouteParameters::from_payment_params_and_value(
5785                                 payment_params, 180_000);
5786                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5787                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5788                         assert_eq!(route.paths.len(), 2);
5789
5790                         let mut total_value_transferred_msat = 0;
5791                         let mut total_paid_msat = 0;
5792                         for path in &route.paths {
5793                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5794                                 total_value_transferred_msat += path.final_value_msat();
5795                                 for hop in &path.hops {
5796                                         total_paid_msat += hop.fee_msat;
5797                                 }
5798                         }
5799                         // If we paid fee, this would be higher.
5800                         assert_eq!(total_value_transferred_msat, 180_000);
5801                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5802                         assert_eq!(total_fees_paid, 0);
5803                 }
5804         }
5805
5806         #[test]
5807         fn fees_on_mpp_route_test() {
5808                 // This test makes sure that MPP algorithm properly takes into account
5809                 // fees charged on the channels, by making the fees impactful:
5810                 // if the fee is not properly accounted for, the behavior is different.
5811                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5812                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5813                 let scorer = ln_test_utils::TestScorer::new();
5814                 let random_seed_bytes = [42; 32];
5815                 let config = UserConfig::default();
5816                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5817                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5818                         .unwrap();
5819
5820                 // We need a route consisting of 2 paths:
5821                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5822                 // We will route 200 sats, Each path will have 100 sats capacity.
5823
5824                 // This test is not particularly stable: e.g.,
5825                 // there's a way to route via {node0, node2, node4}.
5826                 // It works while pathfinding is deterministic, but can be broken otherwise.
5827                 // It's fine to ignore this concern for now.
5828
5829                 // Disable other potential paths.
5830                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5831                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5832                         short_channel_id: 2,
5833                         timestamp: 2,
5834                         flags: 2,
5835                         cltv_expiry_delta: 0,
5836                         htlc_minimum_msat: 0,
5837                         htlc_maximum_msat: 100_000,
5838                         fee_base_msat: 0,
5839                         fee_proportional_millionths: 0,
5840                         excess_data: Vec::new()
5841                 });
5842
5843                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5844                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5845                         short_channel_id: 7,
5846                         timestamp: 2,
5847                         flags: 2,
5848                         cltv_expiry_delta: 0,
5849                         htlc_minimum_msat: 0,
5850                         htlc_maximum_msat: 100_000,
5851                         fee_base_msat: 0,
5852                         fee_proportional_millionths: 0,
5853                         excess_data: Vec::new()
5854                 });
5855
5856                 // Path via {node0, node2} is channels {1, 3, 5}.
5857                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5858                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5859                         short_channel_id: 1,
5860                         timestamp: 2,
5861                         flags: 0,
5862                         cltv_expiry_delta: 0,
5863                         htlc_minimum_msat: 0,
5864                         htlc_maximum_msat: 100_000,
5865                         fee_base_msat: 0,
5866                         fee_proportional_millionths: 0,
5867                         excess_data: Vec::new()
5868                 });
5869                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5870                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5871                         short_channel_id: 3,
5872                         timestamp: 2,
5873                         flags: 0,
5874                         cltv_expiry_delta: 0,
5875                         htlc_minimum_msat: 0,
5876                         htlc_maximum_msat: 100_000,
5877                         fee_base_msat: 0,
5878                         fee_proportional_millionths: 0,
5879                         excess_data: Vec::new()
5880                 });
5881
5882                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5883                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5884                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5885                         short_channel_id: 5,
5886                         timestamp: 2,
5887                         flags: 0,
5888                         cltv_expiry_delta: 0,
5889                         htlc_minimum_msat: 0,
5890                         htlc_maximum_msat: 100_000,
5891                         fee_base_msat: 0,
5892                         fee_proportional_millionths: 0,
5893                         excess_data: Vec::new()
5894                 });
5895                 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5896                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5897                         short_channel_id: 5,
5898                         timestamp: 2,
5899                         flags: 3, // Disable direction 1
5900                         cltv_expiry_delta: 0,
5901                         htlc_minimum_msat: 0,
5902                         htlc_maximum_msat: 100_000,
5903                         fee_base_msat: 0,
5904                         fee_proportional_millionths: 0,
5905                         excess_data: Vec::new()
5906                 });
5907
5908                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5909                 // All channels should be 100 sats capacity. But for the fee experiment,
5910                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5911                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5912                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5913                 // so no matter how large are other channels,
5914                 // the whole path will be limited by 100 sats with just these 2 conditions:
5915                 // - channel 12 capacity is 250 sats
5916                 // - fee for channel 6 is 150 sats
5917                 // Let's test this by enforcing these 2 conditions and removing other limits.
5918                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5919                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5920                         short_channel_id: 12,
5921                         timestamp: 2,
5922                         flags: 0,
5923                         cltv_expiry_delta: 0,
5924                         htlc_minimum_msat: 0,
5925                         htlc_maximum_msat: 250_000,
5926                         fee_base_msat: 0,
5927                         fee_proportional_millionths: 0,
5928                         excess_data: Vec::new()
5929                 });
5930                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5931                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5932                         short_channel_id: 13,
5933                         timestamp: 2,
5934                         flags: 0,
5935                         cltv_expiry_delta: 0,
5936                         htlc_minimum_msat: 0,
5937                         htlc_maximum_msat: MAX_VALUE_MSAT,
5938                         fee_base_msat: 0,
5939                         fee_proportional_millionths: 0,
5940                         excess_data: Vec::new()
5941                 });
5942
5943                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5944                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5945                         short_channel_id: 6,
5946                         timestamp: 2,
5947                         flags: 0,
5948                         cltv_expiry_delta: 0,
5949                         htlc_minimum_msat: 0,
5950                         htlc_maximum_msat: MAX_VALUE_MSAT,
5951                         fee_base_msat: 150_000,
5952                         fee_proportional_millionths: 0,
5953                         excess_data: Vec::new()
5954                 });
5955                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5956                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5957                         short_channel_id: 11,
5958                         timestamp: 2,
5959                         flags: 0,
5960                         cltv_expiry_delta: 0,
5961                         htlc_minimum_msat: 0,
5962                         htlc_maximum_msat: MAX_VALUE_MSAT,
5963                         fee_base_msat: 0,
5964                         fee_proportional_millionths: 0,
5965                         excess_data: Vec::new()
5966                 });
5967
5968                 {
5969                         // Attempt to route more than available results in a failure.
5970                         let route_params = RouteParameters::from_payment_params_and_value(
5971                                 payment_params.clone(), 210_000);
5972                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5973                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5974                                         &scorer, &Default::default(), &random_seed_bytes) {
5975                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5976                         } else { panic!(); }
5977                 }
5978
5979                 {
5980                         // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5981                         let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5982                                 max_total_routing_fee_msat: Some(149_999) };
5983                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5984                                 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5985                                 &scorer, &Default::default(), &random_seed_bytes) {
5986                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
5987                         } else { panic!(); }
5988                 }
5989
5990                 {
5991                         // Now, attempt to route 200 sats (exact amount we can route).
5992                         let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5993                                 max_total_routing_fee_msat: Some(150_000) };
5994                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5995                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5996                         assert_eq!(route.paths.len(), 2);
5997
5998                         let mut total_amount_paid_msat = 0;
5999                         for path in &route.paths {
6000                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
6001                                 total_amount_paid_msat += path.final_value_msat();
6002                         }
6003                         assert_eq!(total_amount_paid_msat, 200_000);
6004                         assert_eq!(route.get_total_fees(), 150_000);
6005                 }
6006         }
6007
6008         #[test]
6009         fn mpp_with_last_hops() {
6010                 // Previously, if we tried to send an MPP payment to a destination which was only reachable
6011                 // via a single last-hop route hint, we'd fail to route if we first collected routes
6012                 // totaling close but not quite enough to fund the full payment.
6013                 //
6014                 // This was because we considered last-hop hints to have exactly the sought payment amount
6015                 // instead of the amount we were trying to collect, needlessly limiting our path searching
6016                 // at the very first hop.
6017                 //
6018                 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
6019                 // criterion to cause us to refuse all routes at the last hop hint which would be considered
6020                 // to only have the remaining to-collect amount in available liquidity.
6021                 //
6022                 // This bug appeared in production in some specific channel configurations.
6023                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6024                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6025                 let scorer = ln_test_utils::TestScorer::new();
6026                 let random_seed_bytes = [42; 32];
6027                 let config = UserConfig::default();
6028                 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6029                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6030                         .with_route_hints(vec![RouteHint(vec![RouteHintHop {
6031                                 src_node_id: nodes[2],
6032                                 short_channel_id: 42,
6033                                 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6034                                 cltv_expiry_delta: 42,
6035                                 htlc_minimum_msat: None,
6036                                 htlc_maximum_msat: None,
6037                         }])]).unwrap().with_max_channel_saturation_power_of_half(0);
6038
6039                 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6040                 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6041                 // would first use the no-fee route and then fail to find a path along the second route as
6042                 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6043                 // under 5% of our payment amount.
6044                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6045                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6046                         short_channel_id: 1,
6047                         timestamp: 2,
6048                         flags: 0,
6049                         cltv_expiry_delta: (5 << 4) | 5,
6050                         htlc_minimum_msat: 0,
6051                         htlc_maximum_msat: 99_000,
6052                         fee_base_msat: u32::max_value(),
6053                         fee_proportional_millionths: u32::max_value(),
6054                         excess_data: Vec::new()
6055                 });
6056                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6057                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6058                         short_channel_id: 2,
6059                         timestamp: 2,
6060                         flags: 0,
6061                         cltv_expiry_delta: (5 << 4) | 3,
6062                         htlc_minimum_msat: 0,
6063                         htlc_maximum_msat: 99_000,
6064                         fee_base_msat: u32::max_value(),
6065                         fee_proportional_millionths: u32::max_value(),
6066                         excess_data: Vec::new()
6067                 });
6068                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6069                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6070                         short_channel_id: 4,
6071                         timestamp: 2,
6072                         flags: 0,
6073                         cltv_expiry_delta: (4 << 4) | 1,
6074                         htlc_minimum_msat: 0,
6075                         htlc_maximum_msat: MAX_VALUE_MSAT,
6076                         fee_base_msat: 1,
6077                         fee_proportional_millionths: 0,
6078                         excess_data: Vec::new()
6079                 });
6080                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6081                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6082                         short_channel_id: 13,
6083                         timestamp: 2,
6084                         flags: 0|2, // Channel disabled
6085                         cltv_expiry_delta: (13 << 4) | 1,
6086                         htlc_minimum_msat: 0,
6087                         htlc_maximum_msat: MAX_VALUE_MSAT,
6088                         fee_base_msat: 0,
6089                         fee_proportional_millionths: 2000000,
6090                         excess_data: Vec::new()
6091                 });
6092
6093                 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
6094                 // overpay at all.
6095                 let route_params = RouteParameters::from_payment_params_and_value(
6096                         payment_params, 100_000);
6097                 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6098                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6099                 assert_eq!(route.paths.len(), 2);
6100                 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6101                 // Paths are manually ordered ordered by SCID, so:
6102                 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6103                 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6104                 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6105                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6106                 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6107                 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6108                 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6109                 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6110                 assert_eq!(route.get_total_fees(), 1);
6111                 assert_eq!(route.get_total_amount(), 100_000);
6112         }
6113
6114         #[test]
6115         fn drop_lowest_channel_mpp_route_test() {
6116                 // This test checks that low-capacity channel is dropped when after
6117                 // path finding we realize that we found more capacity than we need.
6118                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6119                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6120                 let scorer = ln_test_utils::TestScorer::new();
6121                 let random_seed_bytes = [42; 32];
6122                 let config = UserConfig::default();
6123                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6124                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6125                         .unwrap()
6126                         .with_max_channel_saturation_power_of_half(0);
6127
6128                 // We need a route consisting of 3 paths:
6129                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
6130
6131                 // The first and the second paths should be sufficient, but the third should be
6132                 // cheaper, so that we select it but drop later.
6133
6134                 // First, we set limits on these (previously unlimited) channels.
6135                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6136
6137                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6138                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6139                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6140                         short_channel_id: 1,
6141                         timestamp: 2,
6142                         flags: 0,
6143                         cltv_expiry_delta: 0,
6144                         htlc_minimum_msat: 0,
6145                         htlc_maximum_msat: 100_000,
6146                         fee_base_msat: 0,
6147                         fee_proportional_millionths: 0,
6148                         excess_data: Vec::new()
6149                 });
6150                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6151                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6152                         short_channel_id: 3,
6153                         timestamp: 2,
6154                         flags: 0,
6155                         cltv_expiry_delta: 0,
6156                         htlc_minimum_msat: 0,
6157                         htlc_maximum_msat: 50_000,
6158                         fee_base_msat: 100,
6159                         fee_proportional_millionths: 0,
6160                         excess_data: Vec::new()
6161                 });
6162
6163                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6164                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6165                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6166                         short_channel_id: 12,
6167                         timestamp: 2,
6168                         flags: 0,
6169                         cltv_expiry_delta: 0,
6170                         htlc_minimum_msat: 0,
6171                         htlc_maximum_msat: 60_000,
6172                         fee_base_msat: 100,
6173                         fee_proportional_millionths: 0,
6174                         excess_data: Vec::new()
6175                 });
6176                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6177                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6178                         short_channel_id: 13,
6179                         timestamp: 2,
6180                         flags: 0,
6181                         cltv_expiry_delta: 0,
6182                         htlc_minimum_msat: 0,
6183                         htlc_maximum_msat: 60_000,
6184                         fee_base_msat: 0,
6185                         fee_proportional_millionths: 0,
6186                         excess_data: Vec::new()
6187                 });
6188
6189                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6190                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6191                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6192                         short_channel_id: 2,
6193                         timestamp: 2,
6194                         flags: 0,
6195                         cltv_expiry_delta: 0,
6196                         htlc_minimum_msat: 0,
6197                         htlc_maximum_msat: 20_000,
6198                         fee_base_msat: 0,
6199                         fee_proportional_millionths: 0,
6200                         excess_data: Vec::new()
6201                 });
6202                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6203                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6204                         short_channel_id: 4,
6205                         timestamp: 2,
6206                         flags: 0,
6207                         cltv_expiry_delta: 0,
6208                         htlc_minimum_msat: 0,
6209                         htlc_maximum_msat: 20_000,
6210                         fee_base_msat: 0,
6211                         fee_proportional_millionths: 0,
6212                         excess_data: Vec::new()
6213                 });
6214
6215                 {
6216                         // Attempt to route more than available results in a failure.
6217                         let route_params = RouteParameters::from_payment_params_and_value(
6218                                 payment_params.clone(), 150_000);
6219                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6220                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6221                                         &scorer, &Default::default(), &random_seed_bytes) {
6222                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6223                         } else { panic!(); }
6224                 }
6225
6226                 {
6227                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6228                         // Our algorithm should provide us with these 3 paths.
6229                         let route_params = RouteParameters::from_payment_params_and_value(
6230                                 payment_params.clone(), 125_000);
6231                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6232                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6233                         assert_eq!(route.paths.len(), 3);
6234                         let mut total_amount_paid_msat = 0;
6235                         for path in &route.paths {
6236                                 assert_eq!(path.hops.len(), 2);
6237                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6238                                 total_amount_paid_msat += path.final_value_msat();
6239                         }
6240                         assert_eq!(total_amount_paid_msat, 125_000);
6241                 }
6242
6243                 {
6244                         // Attempt to route without the last small cheap channel
6245                         let route_params = RouteParameters::from_payment_params_and_value(
6246                                 payment_params, 90_000);
6247                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6248                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6249                         assert_eq!(route.paths.len(), 2);
6250                         let mut total_amount_paid_msat = 0;
6251                         for path in &route.paths {
6252                                 assert_eq!(path.hops.len(), 2);
6253                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6254                                 total_amount_paid_msat += path.final_value_msat();
6255                         }
6256                         assert_eq!(total_amount_paid_msat, 90_000);
6257                 }
6258         }
6259
6260         #[test]
6261         fn min_criteria_consistency() {
6262                 // Test that we don't use an inconsistent metric between updating and walking nodes during
6263                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6264                 // was updated with a different criterion from the heap sorting, resulting in loops in
6265                 // calculated paths. We test for that specific case here.
6266
6267                 // We construct a network that looks like this:
6268                 //
6269                 //            node2 -1(3)2- node3
6270                 //              2          2
6271                 //               (2)     (4)
6272                 //                  1   1
6273                 //    node1 -1(5)2- node4 -1(1)2- node6
6274                 //    2
6275                 //   (6)
6276                 //        1
6277                 // our_node
6278                 //
6279                 // We create a loop on the side of our real path - our destination is node 6, with a
6280                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6281                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6282                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6283                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6284                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6285                 // "previous hop" being set to node 3, creating a loop in the path.
6286                 let secp_ctx = Secp256k1::new();
6287                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6288                 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6289                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6290                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6291                 let scorer = ln_test_utils::TestScorer::new();
6292                 let random_seed_bytes = [42; 32];
6293                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6294
6295                 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6296                 for (key, flags) in [(&our_privkey, 0), (&privkeys[1], 3)] {
6297                         update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6298                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6299                                 short_channel_id: 6,
6300                                 timestamp: 1,
6301                                 flags,
6302                                 cltv_expiry_delta: (6 << 4) | 0,
6303                                 htlc_minimum_msat: 0,
6304                                 htlc_maximum_msat: MAX_VALUE_MSAT,
6305                                 fee_base_msat: 0,
6306                                 fee_proportional_millionths: 0,
6307                                 excess_data: Vec::new()
6308                         });
6309                 }
6310                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6311
6312                 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6313                 for (key, flags) in [(&privkeys[1], 0), (&privkeys[4], 3)] {
6314                         update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6315                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6316                                 short_channel_id: 5,
6317                                 timestamp: 1,
6318                                 flags,
6319                                 cltv_expiry_delta: (5 << 4) | 0,
6320                                 htlc_minimum_msat: 0,
6321                                 htlc_maximum_msat: MAX_VALUE_MSAT,
6322                                 fee_base_msat: 100,
6323                                 fee_proportional_millionths: 0,
6324                                 excess_data: Vec::new()
6325                         });
6326                 }
6327                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6328
6329                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6330                 for (key, flags) in [(&privkeys[4], 0), (&privkeys[3], 3)] {
6331                         update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6332                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6333                                 short_channel_id: 4,
6334                                 timestamp: 1,
6335                                 flags,
6336                                 cltv_expiry_delta: (4 << 4) | 0,
6337                                 htlc_minimum_msat: 0,
6338                                 htlc_maximum_msat: MAX_VALUE_MSAT,
6339                                 fee_base_msat: 0,
6340                                 fee_proportional_millionths: 0,
6341                                 excess_data: Vec::new()
6342                         });
6343                 }
6344                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6345
6346                 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6347                 for (key, flags) in [(&privkeys[3], 0), (&privkeys[2], 3)] {
6348                         update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6349                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6350                                 short_channel_id: 3,
6351                                 timestamp: 1,
6352                                 flags,
6353                                 cltv_expiry_delta: (3 << 4) | 0,
6354                                 htlc_minimum_msat: 0,
6355                                 htlc_maximum_msat: MAX_VALUE_MSAT,
6356                                 fee_base_msat: 0,
6357                                 fee_proportional_millionths: 0,
6358                                 excess_data: Vec::new()
6359                         });
6360                 }
6361                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6362
6363                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6364                 for (key, flags) in [(&privkeys[2], 0), (&privkeys[4], 3)] {
6365                         update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6366                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6367                                 short_channel_id: 2,
6368                                 timestamp: 1,
6369                                 flags,
6370                                 cltv_expiry_delta: (2 << 4) | 0,
6371                                 htlc_minimum_msat: 0,
6372                                 htlc_maximum_msat: MAX_VALUE_MSAT,
6373                                 fee_base_msat: 0,
6374                                 fee_proportional_millionths: 0,
6375                                 excess_data: Vec::new()
6376                         });
6377                 }
6378
6379                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6380                 for (key, flags) in [(&privkeys[4], 0), (&privkeys[6], 3)] {
6381                         update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6382                                 chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6383                                 short_channel_id: 1,
6384                                 timestamp: 1,
6385                                 flags,
6386                                 cltv_expiry_delta: (1 << 4) | 0,
6387                                 htlc_minimum_msat: 100,
6388                                 htlc_maximum_msat: MAX_VALUE_MSAT,
6389                                 fee_base_msat: 0,
6390                                 fee_proportional_millionths: 0,
6391                                 excess_data: Vec::new()
6392                         });
6393                 }
6394                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6395
6396                 {
6397                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
6398                         let route_params = RouteParameters::from_payment_params_and_value(
6399                                 payment_params, 10_000);
6400                         let route = get_route(&our_id, &route_params, &network.read_only(), None,
6401                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6402                         assert_eq!(route.paths.len(), 1);
6403                         assert_eq!(route.paths[0].hops.len(), 3);
6404
6405                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6406                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6407                         assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6408                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6409                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6410                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6411
6412                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6413                         assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6414                         assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6415                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6416                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6417                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6418
6419                         assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6420                         assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6421                         assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6422                         assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6423                         assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6424                         assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6425                 }
6426         }
6427
6428
6429         #[test]
6430         fn exact_fee_liquidity_limit() {
6431                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6432                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6433                 // we calculated fees on a higher value, resulting in us ignoring such paths.
6434                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6435                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6436                 let scorer = ln_test_utils::TestScorer::new();
6437                 let random_seed_bytes = [42; 32];
6438                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6439
6440                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6441                 // send.
6442                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6443                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6444                         short_channel_id: 2,
6445                         timestamp: 2,
6446                         flags: 0,
6447                         cltv_expiry_delta: 0,
6448                         htlc_minimum_msat: 0,
6449                         htlc_maximum_msat: 85_000,
6450                         fee_base_msat: 0,
6451                         fee_proportional_millionths: 0,
6452                         excess_data: Vec::new()
6453                 });
6454
6455                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6456                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6457                         short_channel_id: 12,
6458                         timestamp: 2,
6459                         flags: 0,
6460                         cltv_expiry_delta: (4 << 4) | 1,
6461                         htlc_minimum_msat: 0,
6462                         htlc_maximum_msat: 270_000,
6463                         fee_base_msat: 0,
6464                         fee_proportional_millionths: 1000000,
6465                         excess_data: Vec::new()
6466                 });
6467
6468                 {
6469                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6470                         // 200% fee charged channel 13 in the 1-to-2 direction.
6471                         let mut route_params = RouteParameters::from_payment_params_and_value(
6472                                 payment_params, 90_000);
6473                         route_params.max_total_routing_fee_msat = Some(90_000*2);
6474                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6475                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6476                         assert_eq!(route.paths.len(), 1);
6477                         assert_eq!(route.paths[0].hops.len(), 2);
6478
6479                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6480                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6481                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6482                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6483                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6484                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6485
6486                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6487                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6488                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6489                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6490                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6491                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6492                 }
6493         }
6494
6495         #[test]
6496         fn htlc_max_reduction_below_min() {
6497                 // Test that if, while walking the graph, we reduce the value being sent to meet an
6498                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6499                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6500                 // resulting in us thinking there is no possible path, even if other paths exist.
6501                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6502                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6503                 let scorer = ln_test_utils::TestScorer::new();
6504                 let random_seed_bytes = [42; 32];
6505                 let config = UserConfig::default();
6506                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6507                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6508                         .unwrap();
6509
6510                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6511                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6512                 // then try to send 90_000.
6513                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6514                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6515                         short_channel_id: 2,
6516                         timestamp: 2,
6517                         flags: 0,
6518                         cltv_expiry_delta: 0,
6519                         htlc_minimum_msat: 0,
6520                         htlc_maximum_msat: 80_000,
6521                         fee_base_msat: 0,
6522                         fee_proportional_millionths: 0,
6523                         excess_data: Vec::new()
6524                 });
6525                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6526                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6527                         short_channel_id: 4,
6528                         timestamp: 2,
6529                         flags: 0,
6530                         cltv_expiry_delta: (4 << 4) | 1,
6531                         htlc_minimum_msat: 90_000,
6532                         htlc_maximum_msat: MAX_VALUE_MSAT,
6533                         fee_base_msat: 0,
6534                         fee_proportional_millionths: 0,
6535                         excess_data: Vec::new()
6536                 });
6537
6538                 {
6539                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6540                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6541                         // expensive) channels 12-13 path.
6542                         let mut route_params = RouteParameters::from_payment_params_and_value(
6543                                 payment_params, 90_000);
6544                         route_params.max_total_routing_fee_msat = Some(90_000*2);
6545                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6546                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6547                         assert_eq!(route.paths.len(), 1);
6548                         assert_eq!(route.paths[0].hops.len(), 2);
6549
6550                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6551                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6552                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6553                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6554                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6555                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6556
6557                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6558                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6559                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6560                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6561                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6562                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6563                 }
6564         }
6565
6566         #[test]
6567         fn multiple_direct_first_hops() {
6568                 // Previously we'd only ever considered one first hop path per counterparty.
6569                 // However, as we don't restrict users to one channel per peer, we really need to support
6570                 // looking at all first hop paths.
6571                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6572                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6573                 // route over multiple channels with the same first hop.
6574                 let secp_ctx = Secp256k1::new();
6575                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6576                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6577                 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6578                 let scorer = ln_test_utils::TestScorer::new();
6579                 let config = UserConfig::default();
6580                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6581                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6582                         .unwrap();
6583                 let random_seed_bytes = [42; 32];
6584
6585                 {
6586                         let route_params = RouteParameters::from_payment_params_and_value(
6587                                 payment_params.clone(), 100_000);
6588                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6589                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6590                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6591                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6592                         assert_eq!(route.paths.len(), 1);
6593                         assert_eq!(route.paths[0].hops.len(), 1);
6594
6595                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6596                         assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6597                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6598                 }
6599                 {
6600                         let route_params = RouteParameters::from_payment_params_and_value(
6601                                 payment_params.clone(), 100_000);
6602                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6603                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6604                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6605                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6606                         assert_eq!(route.paths.len(), 2);
6607                         assert_eq!(route.paths[0].hops.len(), 1);
6608                         assert_eq!(route.paths[1].hops.len(), 1);
6609
6610                         assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6611                                 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6612
6613                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6614                         assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6615
6616                         assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6617                         assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6618                 }
6619
6620                 {
6621                         // If we have a bunch of outbound channels to the same node, where most are not
6622                         // sufficient to pay the full payment, but one is, we should default to just using the
6623                         // one single channel that has sufficient balance, avoiding MPP.
6624                         //
6625                         // If we have several options above the 3xpayment value threshold, we should pick the
6626                         // smallest of them, avoiding further fragmenting our available outbound balance to
6627                         // this node.
6628                         let route_params = RouteParameters::from_payment_params_and_value(
6629                                 payment_params, 100_000);
6630                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6631                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6632                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6633                                 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6634                                 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6635                                 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6636                                 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6637                                 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6638                                 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6639                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6640                         assert_eq!(route.paths.len(), 1);
6641                         assert_eq!(route.paths[0].hops.len(), 1);
6642
6643                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6644                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6645                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6646                 }
6647         }
6648
6649         #[test]
6650         fn prefers_shorter_route_with_higher_fees() {
6651                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6652                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6653                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6654
6655                 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6656                 let scorer = ln_test_utils::TestScorer::new();
6657                 let random_seed_bytes = [42; 32];
6658                 let route_params = RouteParameters::from_payment_params_and_value(
6659                         payment_params.clone(), 100);
6660                 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6661                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6662                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6663
6664                 assert_eq!(route.get_total_fees(), 100);
6665                 assert_eq!(route.get_total_amount(), 100);
6666                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6667
6668                 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6669                 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6670                 let scorer = FixedPenaltyScorer::with_penalty(100);
6671                 let route_params = RouteParameters::from_payment_params_and_value(
6672                         payment_params, 100);
6673                 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6674                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6675                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6676
6677                 assert_eq!(route.get_total_fees(), 300);
6678                 assert_eq!(route.get_total_amount(), 100);
6679                 assert_eq!(path, vec![2, 4, 7, 10]);
6680         }
6681
6682         struct BadChannelScorer {
6683                 short_channel_id: u64,
6684         }
6685
6686         #[cfg(c_bindings)]
6687         impl Writeable for BadChannelScorer {
6688                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6689         }
6690         impl ScoreLookUp for BadChannelScorer {
6691                 type ScoreParams = ();
6692                 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6693                         if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value()  } else { 0  }
6694                 }
6695         }
6696
6697         struct BadNodeScorer {
6698                 node_id: NodeId,
6699         }
6700
6701         #[cfg(c_bindings)]
6702         impl Writeable for BadNodeScorer {
6703                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6704         }
6705
6706         impl ScoreLookUp for BadNodeScorer {
6707                 type ScoreParams = ();
6708                 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6709                         if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6710                 }
6711         }
6712
6713         #[test]
6714         fn avoids_routing_through_bad_channels_and_nodes() {
6715                 let (secp_ctx, network, _, _, logger) = build_graph();
6716                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6717                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6718                 let network_graph = network.read_only();
6719
6720                 // A path to nodes[6] exists when no penalties are applied to any channel.
6721                 let scorer = ln_test_utils::TestScorer::new();
6722                 let random_seed_bytes = [42; 32];
6723                 let route_params = RouteParameters::from_payment_params_and_value(
6724                         payment_params, 100);
6725                 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6726                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6727                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6728
6729                 assert_eq!(route.get_total_fees(), 100);
6730                 assert_eq!(route.get_total_amount(), 100);
6731                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6732
6733                 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6734                 let scorer = BadChannelScorer { short_channel_id: 6 };
6735                 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6736                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6737                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6738
6739                 assert_eq!(route.get_total_fees(), 300);
6740                 assert_eq!(route.get_total_amount(), 100);
6741                 assert_eq!(path, vec![2, 4, 7, 10]);
6742
6743                 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6744                 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6745                 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6746                         &scorer, &Default::default(), &random_seed_bytes) {
6747                                 Err(LightningError { err, .. } ) => {
6748                                         assert_eq!(err, "Failed to find a path to the given destination");
6749                                 },
6750                                 Ok(_) => panic!("Expected error"),
6751                 }
6752         }
6753
6754         #[test]
6755         fn total_fees_single_path() {
6756                 let route = Route {
6757                         paths: vec![Path { hops: vec![
6758                                 RouteHop {
6759                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6760                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6761                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6762                                 },
6763                                 RouteHop {
6764                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6765                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6766                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6767                                 },
6768                                 RouteHop {
6769                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6770                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6771                                         short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6772                                 },
6773                         ], blinded_tail: None }],
6774                         route_params: None,
6775                 };
6776
6777                 assert_eq!(route.get_total_fees(), 250);
6778                 assert_eq!(route.get_total_amount(), 225);
6779         }
6780
6781         #[test]
6782         fn total_fees_multi_path() {
6783                 let route = Route {
6784                         paths: vec![Path { hops: vec![
6785                                 RouteHop {
6786                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6787                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6788                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6789                                 },
6790                                 RouteHop {
6791                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6792                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6793                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6794                                 },
6795                         ], blinded_tail: None }, Path { hops: vec![
6796                                 RouteHop {
6797                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6798                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6799                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6800                                 },
6801                                 RouteHop {
6802                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6803                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6804                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6805                                 },
6806                         ], blinded_tail: None }],
6807                         route_params: None,
6808                 };
6809
6810                 assert_eq!(route.get_total_fees(), 200);
6811                 assert_eq!(route.get_total_amount(), 300);
6812         }
6813
6814         #[test]
6815         fn total_empty_route_no_panic() {
6816                 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6817                 // would both panic if the route was completely empty. We test to ensure they return 0
6818                 // here, even though its somewhat nonsensical as a route.
6819                 let route = Route { paths: Vec::new(), route_params: None };
6820
6821                 assert_eq!(route.get_total_fees(), 0);
6822                 assert_eq!(route.get_total_amount(), 0);
6823         }
6824
6825         #[test]
6826         fn limits_total_cltv_delta() {
6827                 let (secp_ctx, network, _, _, logger) = build_graph();
6828                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6829                 let network_graph = network.read_only();
6830
6831                 let scorer = ln_test_utils::TestScorer::new();
6832
6833                 // Make sure that generally there is at least one route available
6834                 let feasible_max_total_cltv_delta = 1008;
6835                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6836                         .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6837                 let random_seed_bytes = [42; 32];
6838                 let route_params = RouteParameters::from_payment_params_and_value(
6839                         feasible_payment_params, 100);
6840                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6841                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6842                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6843                 assert_ne!(path.len(), 0);
6844
6845                 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6846                 let fail_max_total_cltv_delta = 23;
6847                 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6848                         .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6849                 let route_params = RouteParameters::from_payment_params_and_value(
6850                         fail_payment_params, 100);
6851                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6852                         &Default::default(), &random_seed_bytes)
6853                 {
6854                         Err(LightningError { err, .. } ) => {
6855                                 assert_eq!(err, "Failed to find a path to the given destination");
6856                         },
6857                         Ok(_) => panic!("Expected error"),
6858                 }
6859         }
6860
6861         #[test]
6862         fn avoids_recently_failed_paths() {
6863                 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6864                 // randomly inserting channels into it until we can't find a route anymore.
6865                 let (secp_ctx, network, _, _, logger) = build_graph();
6866                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6867                 let network_graph = network.read_only();
6868
6869                 let scorer = ln_test_utils::TestScorer::new();
6870                 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6871                         .with_max_path_count(1);
6872                 let random_seed_bytes = [42; 32];
6873
6874                 // We should be able to find a route initially, and then after we fail a few random
6875                 // channels eventually we won't be able to any longer.
6876                 let route_params = RouteParameters::from_payment_params_and_value(
6877                         payment_params.clone(), 100);
6878                 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6879                         &scorer, &Default::default(), &random_seed_bytes).is_ok());
6880                 loop {
6881                         let route_params = RouteParameters::from_payment_params_and_value(
6882                                 payment_params.clone(), 100);
6883                         if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6884                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6885                         {
6886                                 for chan in route.paths[0].hops.iter() {
6887                                         assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6888                                 }
6889                                 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6890                                         % route.paths[0].hops.len();
6891                                 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6892                         } else { break; }
6893                 }
6894         }
6895
6896         #[test]
6897         fn limits_path_length() {
6898                 let (secp_ctx, network, _, _, logger) = build_line_graph();
6899                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6900                 let network_graph = network.read_only();
6901
6902                 let scorer = ln_test_utils::TestScorer::new();
6903                 let random_seed_bytes = [42; 32];
6904
6905                 // First check we can actually create a long route on this graph.
6906                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6907                 let route_params = RouteParameters::from_payment_params_and_value(
6908                         feasible_payment_params, 100);
6909                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6910                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6911                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6912                 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6913
6914                 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6915                 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6916                 let route_params = RouteParameters::from_payment_params_and_value(
6917                         fail_payment_params, 100);
6918                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6919                         &Default::default(), &random_seed_bytes)
6920                 {
6921                         Err(LightningError { err, .. } ) => {
6922                                 assert_eq!(err, "Failed to find a path to the given destination");
6923                         },
6924                         Ok(_) => panic!("Expected error"),
6925                 }
6926         }
6927
6928         #[test]
6929         fn adds_and_limits_cltv_offset() {
6930                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6931                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6932
6933                 let scorer = ln_test_utils::TestScorer::new();
6934
6935                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6936                 let random_seed_bytes = [42; 32];
6937                 let route_params = RouteParameters::from_payment_params_and_value(
6938                         payment_params.clone(), 100);
6939                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6940                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6941                 assert_eq!(route.paths.len(), 1);
6942
6943                 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6944
6945                 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6946                 let mut route_default = route.clone();
6947                 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6948                 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6949                 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6950                 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6951                 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6952
6953                 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6954                 let mut route_limited = route.clone();
6955                 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6956                 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6957                 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6958                 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6959                 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6960         }
6961
6962         #[test]
6963         fn adds_plausible_cltv_offset() {
6964                 let (secp_ctx, network, _, _, logger) = build_graph();
6965                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6966                 let network_graph = network.read_only();
6967                 let network_nodes = network_graph.nodes();
6968                 let network_channels = network_graph.channels();
6969                 let scorer = ln_test_utils::TestScorer::new();
6970                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6971                 let random_seed_bytes = [42; 32];
6972
6973                 let route_params = RouteParameters::from_payment_params_and_value(
6974                         payment_params.clone(), 100);
6975                 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6976                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6977                 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6978
6979                 let mut path_plausibility = vec![];
6980
6981                 for p in route.paths {
6982                         // 1. Select random observation point
6983                         let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6984                         let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6985
6986                         prng.process_in_place(&mut random_bytes);
6987                         let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6988                         let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6989
6990                         // 2. Calculate what CLTV expiry delta we would observe there
6991                         let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6992
6993                         // 3. Starting from the observation point, find candidate paths
6994                         let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6995                         candidates.push_back((observation_point, vec![]));
6996
6997                         let mut found_plausible_candidate = false;
6998
6999                         'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
7000                                 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
7001                                         if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
7002                                                 found_plausible_candidate = true;
7003                                                 break 'candidate_loop;
7004                                         }
7005                                 }
7006
7007                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
7008                                         for channel_id in &cur_node.channels {
7009                                                 if let Some(channel_info) = network_channels.get(&channel_id) {
7010                                                         if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
7011                                                                 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
7012                                                                 if cur_path_cltv_deltas.iter().sum::<u32>()
7013                                                                         .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
7014                                                                         let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
7015                                                                         new_path_cltv_deltas.push(next_cltv_expiry_delta);
7016                                                                         candidates.push_back((*next_id, new_path_cltv_deltas));
7017                                                                 }
7018                                                         }
7019                                                 }
7020                                         }
7021                                 }
7022                         }
7023
7024                         path_plausibility.push(found_plausible_candidate);
7025                 }
7026                 assert!(path_plausibility.iter().all(|x| *x));
7027         }
7028
7029         #[test]
7030         fn builds_correct_path_from_hops() {
7031                 let (secp_ctx, network, _, _, logger) = build_graph();
7032                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7033                 let network_graph = network.read_only();
7034
7035                 let random_seed_bytes = [42; 32];
7036                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7037                 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7038                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7039                 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7040                         Arc::clone(&logger), &random_seed_bytes).unwrap();
7041                 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7042                 assert_eq!(hops.len(), route.paths[0].hops.len());
7043                 for (idx, hop_pubkey) in hops.iter().enumerate() {
7044                         assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7045                 }
7046         }
7047
7048         #[test]
7049         fn avoids_saturating_channels() {
7050                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7051                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7052                 let decay_params = ProbabilisticScoringDecayParameters::default();
7053                 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7054
7055                 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
7056                 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7057                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7058                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7059                         short_channel_id: 4,
7060                         timestamp: 2,
7061                         flags: 0,
7062                         cltv_expiry_delta: (4 << 4) | 1,
7063                         htlc_minimum_msat: 0,
7064                         htlc_maximum_msat: 250_000_000,
7065                         fee_base_msat: 0,
7066                         fee_proportional_millionths: 0,
7067                         excess_data: Vec::new()
7068                 });
7069                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7070                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7071                         short_channel_id: 13,
7072                         timestamp: 2,
7073                         flags: 0,
7074                         cltv_expiry_delta: (13 << 4) | 1,
7075                         htlc_minimum_msat: 0,
7076                         htlc_maximum_msat: 250_000_000,
7077                         fee_base_msat: 0,
7078                         fee_proportional_millionths: 0,
7079                         excess_data: Vec::new()
7080                 });
7081
7082                 let config = UserConfig::default();
7083                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7084                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7085                         .unwrap();
7086                 let random_seed_bytes = [42; 32];
7087
7088                 // 100,000 sats is less than the available liquidity on each channel, set above.
7089                 let route_params = RouteParameters::from_payment_params_and_value(
7090                         payment_params, 100_000_000);
7091                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7092                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7093                 assert_eq!(route.paths.len(), 2);
7094                 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7095                         (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7096         }
7097
7098         #[cfg(feature = "std")]
7099         pub(super) fn random_init_seed() -> u64 {
7100                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7101                 use core::hash::{BuildHasher, Hasher};
7102                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7103                 println!("Using seed of {}", seed);
7104                 seed
7105         }
7106
7107         #[test]
7108         #[cfg(feature = "std")]
7109         fn generate_routes() {
7110                 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7111
7112                 let logger = ln_test_utils::TestLogger::new();
7113                 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7114                         Ok(res) => res,
7115                         Err(e) => {
7116                                 eprintln!("{}", e);
7117                                 return;
7118                         },
7119                 };
7120
7121                 let params = ProbabilisticScoringFeeParameters::default();
7122                 let features = super::Bolt11InvoiceFeatures::empty();
7123
7124                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
7125         }
7126
7127         #[test]
7128         #[cfg(feature = "std")]
7129         fn generate_routes_mpp() {
7130                 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7131
7132                 let logger = ln_test_utils::TestLogger::new();
7133                 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7134                         Ok(res) => res,
7135                         Err(e) => {
7136                                 eprintln!("{}", e);
7137                                 return;
7138                         },
7139                 };
7140
7141                 let params = ProbabilisticScoringFeeParameters::default();
7142                 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7143
7144                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
7145         }
7146
7147         #[test]
7148         #[cfg(feature = "std")]
7149         fn generate_large_mpp_routes() {
7150                 use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7151
7152                 let logger = ln_test_utils::TestLogger::new();
7153                 let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7154                         Ok(res) => res,
7155                         Err(e) => {
7156                                 eprintln!("{}", e);
7157                                 return;
7158                         },
7159                 };
7160
7161                 let params = ProbabilisticScoringFeeParameters::default();
7162                 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7163
7164                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 1_000_000, 2);
7165         }
7166
7167         #[test]
7168         fn honors_manual_penalties() {
7169                 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7170                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7171
7172                 let random_seed_bytes = [42; 32];
7173                 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7174                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7175
7176                 // First check set manual penalties are returned by the scorer.
7177                 let usage = ChannelUsage {
7178                         amount_msat: 0,
7179                         inflight_htlc_msat: 0,
7180                         effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7181                 };
7182                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7183                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7184                 let network_graph = network_graph.read_only();
7185                 let channels = network_graph.channels();
7186                 let channel = channels.get(&5).unwrap();
7187                 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7188                 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7189                         info: info.0,
7190                         short_channel_id: 5,
7191                 });
7192                 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7193
7194                 // Then check we can get a normal route
7195                 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7196                 let route_params = RouteParameters::from_payment_params_and_value(
7197                         payment_params, 100);
7198                 let route = get_route(&our_id, &route_params, &network_graph, None,
7199                         Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7200                 assert!(route.is_ok());
7201
7202                 // Then check that we can't get a route if we ban an intermediate node.
7203                 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7204                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7205                 assert!(route.is_err());
7206
7207                 // Finally make sure we can route again, when we remove the ban.
7208                 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7209                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7210                 assert!(route.is_ok());
7211         }
7212
7213         #[test]
7214         fn abide_by_route_hint_max_htlc() {
7215                 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7216                 // params in the final route.
7217                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7218                 let netgraph = network_graph.read_only();
7219                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7220                 let scorer = ln_test_utils::TestScorer::new();
7221                 let random_seed_bytes = [42; 32];
7222                 let config = UserConfig::default();
7223
7224                 let max_htlc_msat = 50_000;
7225                 let route_hint_1 = RouteHint(vec![RouteHintHop {
7226                         src_node_id: nodes[2],
7227                         short_channel_id: 42,
7228                         fees: RoutingFees {
7229                                 base_msat: 100,
7230                                 proportional_millionths: 0,
7231                         },
7232                         cltv_expiry_delta: 10,
7233                         htlc_minimum_msat: None,
7234                         htlc_maximum_msat: Some(max_htlc_msat),
7235                 }]);
7236                 let dest_node_id = ln_test_utils::pubkey(42);
7237                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7238                         .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7239                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7240                         .unwrap();
7241
7242                 // Make sure we'll error if our route hints don't have enough liquidity according to their
7243                 // htlc_maximum_msat.
7244                 let mut route_params = RouteParameters::from_payment_params_and_value(
7245                         payment_params, max_htlc_msat + 1);
7246                 route_params.max_total_routing_fee_msat = None;
7247                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7248                         &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7249                         &random_seed_bytes)
7250                 {
7251                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
7252                 } else { panic!(); }
7253
7254                 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7255                 let mut route_hint_2 = route_hint_1.clone();
7256                 route_hint_2.0[0].short_channel_id = 43;
7257                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7258                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7259                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7260                         .unwrap();
7261                 let mut route_params = RouteParameters::from_payment_params_and_value(
7262                         payment_params, max_htlc_msat + 1);
7263                 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7264                 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7265                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
7266                 assert_eq!(route.paths.len(), 2);
7267                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7268                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7269         }
7270
7271         #[test]
7272         fn direct_channel_to_hints_with_max_htlc() {
7273                 // Check that if we have a first hop channel peer that's connected to multiple provided route
7274                 // hints, that we properly split the payment between the route hints if needed.
7275                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7276                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7277                 let scorer = ln_test_utils::TestScorer::new();
7278                 let random_seed_bytes = [42; 32];
7279                 let config = UserConfig::default();
7280
7281                 let our_node_id = ln_test_utils::pubkey(42);
7282                 let intermed_node_id = ln_test_utils::pubkey(43);
7283                 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7284
7285                 let amt_msat = 900_000;
7286                 let max_htlc_msat = 500_000;
7287                 let route_hint_1 = RouteHint(vec![RouteHintHop {
7288                         src_node_id: intermed_node_id,
7289                         short_channel_id: 44,
7290                         fees: RoutingFees {
7291                                 base_msat: 100,
7292                                 proportional_millionths: 0,
7293                         },
7294                         cltv_expiry_delta: 10,
7295                         htlc_minimum_msat: None,
7296                         htlc_maximum_msat: Some(max_htlc_msat),
7297                 }, RouteHintHop {
7298                         src_node_id: intermed_node_id,
7299                         short_channel_id: 45,
7300                         fees: RoutingFees {
7301                                 base_msat: 100,
7302                                 proportional_millionths: 0,
7303                         },
7304                         cltv_expiry_delta: 10,
7305                         htlc_minimum_msat: None,
7306                         // Check that later route hint max htlcs don't override earlier ones
7307                         htlc_maximum_msat: Some(max_htlc_msat - 50),
7308                 }]);
7309                 let mut route_hint_2 = route_hint_1.clone();
7310                 route_hint_2.0[0].short_channel_id = 46;
7311                 route_hint_2.0[1].short_channel_id = 47;
7312                 let dest_node_id = ln_test_utils::pubkey(44);
7313                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7314                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7315                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7316                         .unwrap();
7317
7318                 let route_params = RouteParameters::from_payment_params_and_value(
7319                         payment_params, amt_msat);
7320                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7321                         Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7322                         &Default::default(), &random_seed_bytes).unwrap();
7323                 assert_eq!(route.paths.len(), 2);
7324                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7325                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7326                 assert_eq!(route.get_total_amount(), amt_msat);
7327
7328                 // Re-run but with two first hop channels connected to the same route hint peers that must be
7329                 // split between.
7330                 let first_hops = vec![
7331                         get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7332                         get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7333                 ];
7334                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7335                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7336                         &Default::default(), &random_seed_bytes).unwrap();
7337                 assert_eq!(route.paths.len(), 2);
7338                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7339                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7340                 assert_eq!(route.get_total_amount(), amt_msat);
7341
7342                 // Make sure this works for blinded route hints.
7343                 let blinded_path = BlindedPath {
7344                         introduction_node: IntroductionNode::NodeId(intermed_node_id),
7345                         blinding_point: ln_test_utils::pubkey(42),
7346                         blinded_hops: vec![
7347                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7348                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7349                         ],
7350                 };
7351                 let blinded_payinfo = BlindedPayInfo {
7352                         fee_base_msat: 100,
7353                         fee_proportional_millionths: 0,
7354                         htlc_minimum_msat: 1,
7355                         htlc_maximum_msat: max_htlc_msat,
7356                         cltv_expiry_delta: 10,
7357                         features: BlindedHopFeatures::empty(),
7358                 };
7359                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7360                 let payment_params = PaymentParameters::blinded(vec![
7361                         (blinded_payinfo.clone(), blinded_path.clone()),
7362                         (blinded_payinfo.clone(), blinded_path.clone())])
7363                         .with_bolt12_features(bolt12_features).unwrap();
7364                 let route_params = RouteParameters::from_payment_params_and_value(
7365                         payment_params, amt_msat);
7366                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7367                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7368                         &Default::default(), &random_seed_bytes).unwrap();
7369                 assert_eq!(route.paths.len(), 2);
7370                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7371                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7372                 assert_eq!(route.get_total_amount(), amt_msat);
7373         }
7374
7375         #[test]
7376         fn blinded_route_ser() {
7377                 let blinded_path_1 = BlindedPath {
7378                         introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(42)),
7379                         blinding_point: ln_test_utils::pubkey(43),
7380                         blinded_hops: vec![
7381                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7382                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7383                         ],
7384                 };
7385                 let blinded_path_2 = BlindedPath {
7386                         introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(46)),
7387                         blinding_point: ln_test_utils::pubkey(47),
7388                         blinded_hops: vec![
7389                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7390                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7391                         ],
7392                 };
7393                 // (De)serialize a Route with 1 blinded path out of two total paths.
7394                 let mut route = Route { paths: vec![Path {
7395                         hops: vec![RouteHop {
7396                                 pubkey: ln_test_utils::pubkey(50),
7397                                 node_features: NodeFeatures::empty(),
7398                                 short_channel_id: 42,
7399                                 channel_features: ChannelFeatures::empty(),
7400                                 fee_msat: 100,
7401                                 cltv_expiry_delta: 0,
7402                                 maybe_announced_channel: true,
7403                         }],
7404                         blinded_tail: Some(BlindedTail {
7405                                 hops: blinded_path_1.blinded_hops,
7406                                 blinding_point: blinded_path_1.blinding_point,
7407                                 excess_final_cltv_expiry_delta: 40,
7408                                 final_value_msat: 100,
7409                         })}, Path {
7410                         hops: vec![RouteHop {
7411                                 pubkey: ln_test_utils::pubkey(51),
7412                                 node_features: NodeFeatures::empty(),
7413                                 short_channel_id: 43,
7414                                 channel_features: ChannelFeatures::empty(),
7415                                 fee_msat: 100,
7416                                 cltv_expiry_delta: 0,
7417                                 maybe_announced_channel: true,
7418                         }], blinded_tail: None }],
7419                         route_params: None,
7420                 };
7421                 let encoded_route = route.encode();
7422                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7423                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7424                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7425
7426                 // (De)serialize a Route with two paths, each containing a blinded tail.
7427                 route.paths[1].blinded_tail = Some(BlindedTail {
7428                         hops: blinded_path_2.blinded_hops,
7429                         blinding_point: blinded_path_2.blinding_point,
7430                         excess_final_cltv_expiry_delta: 41,
7431                         final_value_msat: 101,
7432                 });
7433                 let encoded_route = route.encode();
7434                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7435                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7436                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7437         }
7438
7439         #[test]
7440         fn blinded_path_inflight_processing() {
7441                 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7442                 // account for the blinded tail's final amount_msat.
7443                 let mut inflight_htlcs = InFlightHtlcs::new();
7444                 let blinded_path = BlindedPath {
7445                         introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7446                         blinding_point: ln_test_utils::pubkey(48),
7447                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7448                 };
7449                 let path = Path {
7450                         hops: vec![RouteHop {
7451                                 pubkey: ln_test_utils::pubkey(42),
7452                                 node_features: NodeFeatures::empty(),
7453                                 short_channel_id: 42,
7454                                 channel_features: ChannelFeatures::empty(),
7455                                 fee_msat: 100,
7456                                 cltv_expiry_delta: 0,
7457                                 maybe_announced_channel: false,
7458                         },
7459                         RouteHop {
7460                                 pubkey: ln_test_utils::pubkey(43),
7461                                 node_features: NodeFeatures::empty(),
7462                                 short_channel_id: 43,
7463                                 channel_features: ChannelFeatures::empty(),
7464                                 fee_msat: 1,
7465                                 cltv_expiry_delta: 0,
7466                                 maybe_announced_channel: false,
7467                         }],
7468                         blinded_tail: Some(BlindedTail {
7469                                 hops: blinded_path.blinded_hops,
7470                                 blinding_point: blinded_path.blinding_point,
7471                                 excess_final_cltv_expiry_delta: 0,
7472                                 final_value_msat: 200,
7473                         }),
7474                 };
7475                 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7476                 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7477                 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7478         }
7479
7480         #[test]
7481         fn blinded_path_cltv_shadow_offset() {
7482                 // Make sure we add a shadow offset when sending to blinded paths.
7483                 let blinded_path = BlindedPath {
7484                         introduction_node: IntroductionNode::NodeId(ln_test_utils::pubkey(43)),
7485                         blinding_point: ln_test_utils::pubkey(44),
7486                         blinded_hops: vec![
7487                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7488                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7489                         ],
7490                 };
7491                 let mut route = Route { paths: vec![Path {
7492                         hops: vec![RouteHop {
7493                                 pubkey: ln_test_utils::pubkey(42),
7494                                 node_features: NodeFeatures::empty(),
7495                                 short_channel_id: 42,
7496                                 channel_features: ChannelFeatures::empty(),
7497                                 fee_msat: 100,
7498                                 cltv_expiry_delta: 0,
7499                                 maybe_announced_channel: false,
7500                         },
7501                         RouteHop {
7502                                 pubkey: ln_test_utils::pubkey(43),
7503                                 node_features: NodeFeatures::empty(),
7504                                 short_channel_id: 43,
7505                                 channel_features: ChannelFeatures::empty(),
7506                                 fee_msat: 1,
7507                                 cltv_expiry_delta: 0,
7508                                 maybe_announced_channel: false,
7509                         }
7510                         ],
7511                         blinded_tail: Some(BlindedTail {
7512                                 hops: blinded_path.blinded_hops,
7513                                 blinding_point: blinded_path.blinding_point,
7514                                 excess_final_cltv_expiry_delta: 0,
7515                                 final_value_msat: 200,
7516                         }),
7517                 }], route_params: None};
7518
7519                 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7520                 let (_, network_graph, _, _, _) = build_line_graph();
7521                 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7522                 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7523                 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7524         }
7525
7526         #[test]
7527         fn simple_blinded_route_hints() {
7528                 do_simple_blinded_route_hints(1);
7529                 do_simple_blinded_route_hints(2);
7530                 do_simple_blinded_route_hints(3);
7531         }
7532
7533         fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7534                 // Check that we can generate a route to a blinded path with the expected hops.
7535                 let (secp_ctx, network, _, _, logger) = build_graph();
7536                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7537                 let network_graph = network.read_only();
7538
7539                 let scorer = ln_test_utils::TestScorer::new();
7540                 let random_seed_bytes = [42; 32];
7541
7542                 let mut blinded_path = BlindedPath {
7543                         introduction_node: IntroductionNode::NodeId(nodes[2]),
7544                         blinding_point: ln_test_utils::pubkey(42),
7545                         blinded_hops: Vec::with_capacity(num_blinded_hops),
7546                 };
7547                 for i in 0..num_blinded_hops {
7548                         blinded_path.blinded_hops.push(
7549                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7550                         );
7551                 }
7552                 let blinded_payinfo = BlindedPayInfo {
7553                         fee_base_msat: 100,
7554                         fee_proportional_millionths: 500,
7555                         htlc_minimum_msat: 1000,
7556                         htlc_maximum_msat: 100_000_000,
7557                         cltv_expiry_delta: 15,
7558                         features: BlindedHopFeatures::empty(),
7559                 };
7560
7561                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7562                 let route_params = RouteParameters::from_payment_params_and_value(
7563                         payment_params, 1001);
7564                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7565                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
7566                 assert_eq!(route.paths.len(), 1);
7567                 assert_eq!(route.paths[0].hops.len(), 2);
7568
7569                 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7570                 assert_eq!(tail.hops, blinded_path.blinded_hops);
7571                 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7572                 assert_eq!(tail.final_value_msat, 1001);
7573
7574                 let final_hop = route.paths[0].hops.last().unwrap();
7575                 assert_eq!(
7576                         NodeId::from_pubkey(&final_hop.pubkey),
7577                         *blinded_path.public_introduction_node_id(&network_graph).unwrap()
7578                 );
7579                 if tail.hops.len() > 1 {
7580                         assert_eq!(final_hop.fee_msat,
7581                                 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7582                         assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7583                 } else {
7584                         assert_eq!(final_hop.fee_msat, 0);
7585                         assert_eq!(final_hop.cltv_expiry_delta, 0);
7586                 }
7587         }
7588
7589         #[test]
7590         fn blinded_path_routing_errors() {
7591                 // Check that we can generate a route to a blinded path with the expected hops.
7592                 let (secp_ctx, network, _, _, logger) = build_graph();
7593                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7594                 let network_graph = network.read_only();
7595
7596                 let scorer = ln_test_utils::TestScorer::new();
7597                 let random_seed_bytes = [42; 32];
7598
7599                 let mut invalid_blinded_path = BlindedPath {
7600                         introduction_node: IntroductionNode::NodeId(nodes[2]),
7601                         blinding_point: ln_test_utils::pubkey(42),
7602                         blinded_hops: vec![
7603                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7604                         ],
7605                 };
7606                 let blinded_payinfo = BlindedPayInfo {
7607                         fee_base_msat: 100,
7608                         fee_proportional_millionths: 500,
7609                         htlc_minimum_msat: 1000,
7610                         htlc_maximum_msat: 100_000_000,
7611                         cltv_expiry_delta: 15,
7612                         features: BlindedHopFeatures::empty(),
7613                 };
7614
7615                 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7616                 invalid_blinded_path_2.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(45));
7617                 let payment_params = PaymentParameters::blinded(vec![
7618                         (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7619                         (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7620                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7621                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7622                         &scorer, &Default::default(), &random_seed_bytes)
7623                 {
7624                         Err(LightningError { err, .. }) => {
7625                                 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7626                         },
7627                         _ => panic!("Expected error")
7628                 }
7629
7630                 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(our_id);
7631                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7632                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7633                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7634                         &Default::default(), &random_seed_bytes)
7635                 {
7636                         Err(LightningError { err, .. }) => {
7637                                 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7638                         },
7639                         _ => panic!("Expected error")
7640                 }
7641
7642                 invalid_blinded_path.introduction_node = IntroductionNode::NodeId(ln_test_utils::pubkey(46));
7643                 invalid_blinded_path.blinded_hops.clear();
7644                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7645                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7646                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7647                         &Default::default(), &random_seed_bytes)
7648                 {
7649                         Err(LightningError { err, .. }) => {
7650                                 assert_eq!(err, "0-hop blinded path provided");
7651                         },
7652                         _ => panic!("Expected error")
7653                 }
7654         }
7655
7656         #[test]
7657         fn matching_intro_node_paths_provided() {
7658                 // Check that if multiple blinded paths with the same intro node are provided in payment
7659                 // parameters, we'll return the correct paths in the resulting MPP route.
7660                 let (secp_ctx, network, _, _, logger) = build_graph();
7661                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7662                 let network_graph = network.read_only();
7663
7664                 let scorer = ln_test_utils::TestScorer::new();
7665                 let random_seed_bytes = [42; 32];
7666                 let config = UserConfig::default();
7667
7668                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7669                 let blinded_path_1 = BlindedPath {
7670                         introduction_node: IntroductionNode::NodeId(nodes[2]),
7671                         blinding_point: ln_test_utils::pubkey(42),
7672                         blinded_hops: vec![
7673                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7674                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7675                         ],
7676                 };
7677                 let blinded_payinfo_1 = BlindedPayInfo {
7678                         fee_base_msat: 0,
7679                         fee_proportional_millionths: 0,
7680                         htlc_minimum_msat: 0,
7681                         htlc_maximum_msat: 30_000,
7682                         cltv_expiry_delta: 0,
7683                         features: BlindedHopFeatures::empty(),
7684                 };
7685
7686                 let mut blinded_path_2 = blinded_path_1.clone();
7687                 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7688                 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7689                 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7690
7691                 let blinded_hints = vec![
7692                         (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7693                         (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7694                 ];
7695                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7696                         .with_bolt12_features(bolt12_features).unwrap();
7697
7698                 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7699                 route_params.max_total_routing_fee_msat = Some(100_000);
7700                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7701                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
7702                 assert_eq!(route.paths.len(), 2);
7703                 let mut total_amount_paid_msat = 0;
7704                 for path in route.paths.into_iter() {
7705                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7706                         if let Some(bt) = &path.blinded_tail {
7707                                 assert_eq!(bt.blinding_point,
7708                                         blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7709                                                 .map(|(_, bp)| bp.blinding_point).unwrap());
7710                         } else { panic!(); }
7711                         total_amount_paid_msat += path.final_value_msat();
7712                 }
7713                 assert_eq!(total_amount_paid_msat, 100_000);
7714         }
7715
7716         #[test]
7717         fn direct_to_intro_node() {
7718                 // This previously caused a debug panic in the router when asserting
7719                 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7720                 // direct channels we failed to account for the fee charged for use of the blinded path.
7721
7722                 // Build a graph:
7723                 // node0 -1(1)2 - node1
7724                 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7725                 // doesn't account for the blinded path fee.
7726
7727                 let secp_ctx = Secp256k1::new();
7728                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7729                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7730                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7731                 let scorer = ln_test_utils::TestScorer::new();
7732                 let random_seed_bytes = [42; 32];
7733
7734                 let amt_msat = 10_000_000;
7735                 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7736                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7737                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7738                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7739                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7740                         short_channel_id: 1,
7741                         timestamp: 1,
7742                         flags: 0,
7743                         cltv_expiry_delta: 42,
7744                         htlc_minimum_msat: 1_000,
7745                         htlc_maximum_msat: 10_000_000,
7746                         fee_base_msat: 800,
7747                         fee_proportional_millionths: 0,
7748                         excess_data: Vec::new()
7749                 });
7750                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7751                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7752                         short_channel_id: 1,
7753                         timestamp: 1,
7754                         flags: 1,
7755                         cltv_expiry_delta: 42,
7756                         htlc_minimum_msat: 1_000,
7757                         htlc_maximum_msat: 10_000_000,
7758                         fee_base_msat: 800,
7759                         fee_proportional_millionths: 0,
7760                         excess_data: Vec::new()
7761                 });
7762                 let first_hops = vec![
7763                         get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7764
7765                 let blinded_path = BlindedPath {
7766                         introduction_node: IntroductionNode::NodeId(nodes[1]),
7767                         blinding_point: ln_test_utils::pubkey(42),
7768                         blinded_hops: vec![
7769                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7770                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7771                         ],
7772                 };
7773                 let blinded_payinfo = BlindedPayInfo {
7774                         fee_base_msat: 1000,
7775                         fee_proportional_millionths: 0,
7776                         htlc_minimum_msat: 1000,
7777                         htlc_maximum_msat: MAX_VALUE_MSAT,
7778                         cltv_expiry_delta: 0,
7779                         features: BlindedHopFeatures::empty(),
7780                 };
7781                 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7782
7783                 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7784
7785                 let netgraph = network_graph.read_only();
7786                 let route_params = RouteParameters::from_payment_params_and_value(
7787                         payment_params.clone(), amt_msat);
7788                 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7789                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7790                         &Default::default(), &random_seed_bytes) {
7791                                 assert_eq!(err, "Failed to find a path to the given destination");
7792                 } else { panic!("Expected error") }
7793
7794                 // Sending an exact amount accounting for the blinded path fee works.
7795                 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7796                 let route_params = RouteParameters::from_payment_params_and_value(
7797                         payment_params, amt_minus_blinded_path_fee);
7798                 let route = get_route(&nodes[0], &route_params, &netgraph,
7799                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7800                         &Default::default(), &random_seed_bytes).unwrap();
7801                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7802                 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7803         }
7804
7805         #[test]
7806         fn direct_to_matching_intro_nodes() {
7807                 // This previously caused us to enter `unreachable` code in the following situation:
7808                 // 1. We add a route candidate for intro_node contributing a high amount
7809                 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7810                 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7811                 //    amount, and update our route candidate for intro_node for the lower amount
7812                 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7813                 //    lower contribution amount, but fail (this was previously caused by failure to account for
7814                 //    blinded path fees when adding first_hop<>intro_node candidates)
7815                 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7816                 //    candidate still thinks its path is contributing the original higher amount. This caused us
7817                 //    to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7818                 //    larger amount
7819                 let secp_ctx = Secp256k1::new();
7820                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7821                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7822                 let scorer = ln_test_utils::TestScorer::new();
7823                 let random_seed_bytes = [42; 32];
7824                 let config = UserConfig::default();
7825
7826                 // Values are taken from the fuzz input that uncovered this panic.
7827                 let amt_msat = 21_7020_5185_1403_2640;
7828                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7829                 let first_hops = vec![
7830                         get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7831                                 18446744073709551615)];
7832
7833                 let blinded_path = BlindedPath {
7834                         introduction_node: IntroductionNode::NodeId(nodes[1]),
7835                         blinding_point: ln_test_utils::pubkey(42),
7836                         blinded_hops: vec![
7837                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7838                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7839                         ],
7840                 };
7841                 let blinded_payinfo = BlindedPayInfo {
7842                         fee_base_msat: 5046_2720,
7843                         fee_proportional_millionths: 0,
7844                         htlc_minimum_msat: 4503_5996_2737_0496,
7845                         htlc_maximum_msat: 45_0359_9627_3704_9600,
7846                         cltv_expiry_delta: 0,
7847                         features: BlindedHopFeatures::empty(),
7848                 };
7849                 let mut blinded_hints = vec![
7850                         (blinded_payinfo.clone(), blinded_path.clone()),
7851                         (blinded_payinfo.clone(), blinded_path.clone()),
7852                 ];
7853                 blinded_hints[1].0.fee_base_msat = 419_4304;
7854                 blinded_hints[1].0.fee_proportional_millionths = 257;
7855                 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7856                 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7857                 blinded_hints[1].0.cltv_expiry_delta = 0;
7858
7859                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7860                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7861                         .with_bolt12_features(bolt12_features).unwrap();
7862
7863                 let netgraph = network_graph.read_only();
7864                 let route_params = RouteParameters::from_payment_params_and_value(
7865                         payment_params, amt_msat);
7866                 let route = get_route(&nodes[0], &route_params, &netgraph,
7867                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7868                         &Default::default(), &random_seed_bytes).unwrap();
7869                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7870                 assert_eq!(route.get_total_amount(), amt_msat);
7871         }
7872
7873         #[test]
7874         fn we_are_intro_node_candidate_hops() {
7875                 // This previously led to a panic in the router because we'd generate a Path with only a
7876                 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7877                 // where the origin node is the intro node. We now fully disallow considering candidate hops
7878                 // where the origin node is the intro node.
7879                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7880                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7881                 let scorer = ln_test_utils::TestScorer::new();
7882                 let random_seed_bytes = [42; 32];
7883                 let config = UserConfig::default();
7884
7885                 // Values are taken from the fuzz input that uncovered this panic.
7886                 let amt_msat = 21_7020_5185_1423_0019;
7887
7888                 let blinded_path = BlindedPath {
7889                         introduction_node: IntroductionNode::NodeId(our_id),
7890                         blinding_point: ln_test_utils::pubkey(42),
7891                         blinded_hops: vec![
7892                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7893                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7894                         ],
7895                 };
7896                 let blinded_payinfo = BlindedPayInfo {
7897                         fee_base_msat: 5052_9027,
7898                         fee_proportional_millionths: 0,
7899                         htlc_minimum_msat: 21_7020_5185_1423_0019,
7900                         htlc_maximum_msat: 1844_6744_0737_0955_1615,
7901                         cltv_expiry_delta: 0,
7902                         features: BlindedHopFeatures::empty(),
7903                 };
7904                 let mut blinded_hints = vec![
7905                         (blinded_payinfo.clone(), blinded_path.clone()),
7906                         (blinded_payinfo.clone(), blinded_path.clone()),
7907                 ];
7908                 blinded_hints[1].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7909
7910                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7911                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7912                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7913
7914                 let netgraph = network_graph.read_only();
7915                 let route_params = RouteParameters::from_payment_params_and_value(
7916                         payment_params, amt_msat);
7917                 if let Err(LightningError { err, .. }) = get_route(
7918                         &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7919                 ) {
7920                         assert_eq!(err, "Failed to find a path to the given destination");
7921                 } else { panic!() }
7922         }
7923
7924         #[test]
7925         fn we_are_intro_node_bp_in_final_path_fee_calc() {
7926                 // This previously led to a debug panic in the router because we'd find an invalid Path with
7927                 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7928                 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7929                 // the payment, when it was intended to only include the final value of the payment.
7930                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7931                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7932                 let scorer = ln_test_utils::TestScorer::new();
7933                 let random_seed_bytes = [42; 32];
7934                 let config = UserConfig::default();
7935
7936                 // Values are taken from the fuzz input that uncovered this panic.
7937                 let amt_msat = 21_7020_5185_1423_0019;
7938
7939                 let blinded_path = BlindedPath {
7940                         introduction_node: IntroductionNode::NodeId(our_id),
7941                         blinding_point: ln_test_utils::pubkey(42),
7942                         blinded_hops: vec![
7943                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7944                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7945                         ],
7946                 };
7947                 let blinded_payinfo = BlindedPayInfo {
7948                         fee_base_msat: 10_4425_1395,
7949                         fee_proportional_millionths: 0,
7950                         htlc_minimum_msat: 21_7301_9934_9094_0931,
7951                         htlc_maximum_msat: 1844_6744_0737_0955_1615,
7952                         cltv_expiry_delta: 0,
7953                         features: BlindedHopFeatures::empty(),
7954                 };
7955                 let mut blinded_hints = vec![
7956                         (blinded_payinfo.clone(), blinded_path.clone()),
7957                         (blinded_payinfo.clone(), blinded_path.clone()),
7958                         (blinded_payinfo.clone(), blinded_path.clone()),
7959                 ];
7960                 blinded_hints[1].0.fee_base_msat = 5052_9027;
7961                 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7962                 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7963
7964                 blinded_hints[2].1.introduction_node = IntroductionNode::NodeId(nodes[6]);
7965
7966                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7967                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7968                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7969
7970                 let netgraph = network_graph.read_only();
7971                 let route_params = RouteParameters::from_payment_params_and_value(
7972                         payment_params, amt_msat);
7973                 if let Err(LightningError { err, .. }) = get_route(
7974                         &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7975                 ) {
7976                         assert_eq!(err, "Failed to find a path to the given destination");
7977                 } else { panic!() }
7978         }
7979
7980         #[test]
7981         fn min_htlc_overpay_violates_max_htlc() {
7982                 do_min_htlc_overpay_violates_max_htlc(true);
7983                 do_min_htlc_overpay_violates_max_htlc(false);
7984         }
7985         fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7986                 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7987                 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7988                 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7989                 // that the used liquidity for a hop was less than its available liquidity limit.
7990                 let secp_ctx = Secp256k1::new();
7991                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7992                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7993                 let scorer = ln_test_utils::TestScorer::new();
7994                 let random_seed_bytes = [42; 32];
7995                 let config = UserConfig::default();
7996
7997                 // Values are taken from the fuzz input that uncovered this panic.
7998                 let amt_msat = 7_4009_8048;
7999                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8000                 let first_hop_outbound_capacity = 2_7345_2000;
8001                 let first_hops = vec![get_channel_details(
8002                         Some(200), nodes[0], channelmanager::provided_init_features(&config),
8003                         first_hop_outbound_capacity
8004                 )];
8005
8006                 let base_fee = 1_6778_3453;
8007                 let htlc_min = 2_5165_8240;
8008                 let payment_params = if blinded_payee {
8009                         let blinded_path = BlindedPath {
8010                                 introduction_node: IntroductionNode::NodeId(nodes[0]),
8011                                 blinding_point: ln_test_utils::pubkey(42),
8012                                 blinded_hops: vec![
8013                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8014                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8015                                 ],
8016                         };
8017                         let blinded_payinfo = BlindedPayInfo {
8018                                 fee_base_msat: base_fee,
8019                                 fee_proportional_millionths: 0,
8020                                 htlc_minimum_msat: htlc_min,
8021                                 htlc_maximum_msat: htlc_min * 1000,
8022                                 cltv_expiry_delta: 0,
8023                                 features: BlindedHopFeatures::empty(),
8024                         };
8025                         let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8026                         PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
8027                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
8028                 } else {
8029                         let route_hint = RouteHint(vec![RouteHintHop {
8030                                 src_node_id: nodes[0],
8031                                 short_channel_id: 42,
8032                                 fees: RoutingFees {
8033                                         base_msat: base_fee,
8034                                         proportional_millionths: 0,
8035                                 },
8036                                 cltv_expiry_delta: 10,
8037                                 htlc_minimum_msat: Some(htlc_min),
8038                                 htlc_maximum_msat: None,
8039                         }]);
8040
8041                         PaymentParameters::from_node_id(nodes[1], 42)
8042                                 .with_route_hints(vec![route_hint]).unwrap()
8043                                 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8044                 };
8045
8046                 let netgraph = network_graph.read_only();
8047                 let route_params = RouteParameters::from_payment_params_and_value(
8048                         payment_params, amt_msat);
8049                 if let Err(LightningError { err, .. }) = get_route(
8050                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8051                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8052                 ) {
8053                         assert_eq!(err, "Failed to find a path to the given destination");
8054                 } else { panic!() }
8055         }
8056
8057         #[test]
8058         fn previously_used_liquidity_violates_max_htlc() {
8059                 do_previously_used_liquidity_violates_max_htlc(true);
8060                 do_previously_used_liquidity_violates_max_htlc(false);
8061
8062         }
8063         fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8064                 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8065                 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8066                 // candidate. In this case, the candidate does not have enough due to a previous path taking up
8067                 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8068                 // asserting that the used liquidity for a hop was less than its available liquidity limit.
8069                 let secp_ctx = Secp256k1::new();
8070                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8071                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8072                 let scorer = ln_test_utils::TestScorer::new();
8073                 let random_seed_bytes = [42; 32];
8074                 let config = UserConfig::default();
8075
8076                 // Values are taken from the fuzz input that uncovered this panic.
8077                 let amt_msat = 52_4288;
8078                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8079                 let first_hops = vec![get_channel_details(
8080                         Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8081                 ), get_channel_details(
8082                         Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8083                 )];
8084
8085                 let base_fees = [0, 425_9840, 0, 0];
8086                 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8087                 let payment_params = if blinded_payee {
8088                         let blinded_path = BlindedPath {
8089                                 introduction_node: IntroductionNode::NodeId(nodes[0]),
8090                                 blinding_point: ln_test_utils::pubkey(42),
8091                                 blinded_hops: vec![
8092                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8093                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8094                                 ],
8095                         };
8096                         let mut blinded_hints = Vec::new();
8097                         for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8098                                 blinded_hints.push((BlindedPayInfo {
8099                                         fee_base_msat: *base_fee,
8100                                         fee_proportional_millionths: 0,
8101                                         htlc_minimum_msat: *htlc_min,
8102                                         htlc_maximum_msat: htlc_min * 100,
8103                                         cltv_expiry_delta: 10,
8104                                         features: BlindedHopFeatures::empty(),
8105                                 }, blinded_path.clone()));
8106                         }
8107                         let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8108                         PaymentParameters::blinded(blinded_hints.clone())
8109                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
8110                 } else {
8111                         let mut route_hints = Vec::new();
8112                         for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8113                                 route_hints.push(RouteHint(vec![RouteHintHop {
8114                                         src_node_id: nodes[0],
8115                                         short_channel_id: 42 + idx as u64,
8116                                         fees: RoutingFees {
8117                                                 base_msat: *base_fee,
8118                                                 proportional_millionths: 0,
8119                                         },
8120                                         cltv_expiry_delta: 10,
8121                                         htlc_minimum_msat: Some(*htlc_min),
8122                                         htlc_maximum_msat: Some(htlc_min * 100),
8123                                 }]));
8124                         }
8125                         PaymentParameters::from_node_id(nodes[1], 42)
8126                                 .with_route_hints(route_hints).unwrap()
8127                                 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8128                 };
8129
8130                 let netgraph = network_graph.read_only();
8131                 let route_params = RouteParameters::from_payment_params_and_value(
8132                         payment_params, amt_msat);
8133
8134                 let route = get_route(
8135                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8136                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8137                 ).unwrap();
8138                 assert_eq!(route.paths.len(), 1);
8139                 assert_eq!(route.get_total_amount(), amt_msat);
8140         }
8141
8142         #[test]
8143         fn candidate_path_min() {
8144                 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8145                 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8146                 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8147                 // would add a connecting first_hop node that did not have enough contribution amount, leading
8148                 // to a debug panic upon invalid path construction.
8149                 let secp_ctx = Secp256k1::new();
8150                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8151                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8152                 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8153                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8154                 let random_seed_bytes = [42; 32];
8155                 let config = UserConfig::default();
8156
8157                 // Values are taken from the fuzz input that uncovered this panic.
8158                 let amt_msat = 7_4009_8048;
8159                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8160                 let first_hops = vec![get_channel_details(
8161                         Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8162                 )];
8163
8164                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8165                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8166                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8167                         short_channel_id: 6,
8168                         timestamp: 1,
8169                         flags: 0,
8170                         cltv_expiry_delta: (6 << 4) | 0,
8171                         htlc_minimum_msat: 0,
8172                         htlc_maximum_msat: MAX_VALUE_MSAT,
8173                         fee_base_msat: 0,
8174                         fee_proportional_millionths: 0,
8175                         excess_data: Vec::new()
8176                 });
8177                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8178
8179                 let htlc_min = 2_5165_8240;
8180                 let blinded_hints = vec![
8181                         (BlindedPayInfo {
8182                                 fee_base_msat: 1_6778_3453,
8183                                 fee_proportional_millionths: 0,
8184                                 htlc_minimum_msat: htlc_min,
8185                                 htlc_maximum_msat: htlc_min * 100,
8186                                 cltv_expiry_delta: 10,
8187                                 features: BlindedHopFeatures::empty(),
8188                         }, BlindedPath {
8189                                 introduction_node: IntroductionNode::NodeId(nodes[0]),
8190                                 blinding_point: ln_test_utils::pubkey(42),
8191                                 blinded_hops: vec![
8192                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8193                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8194                                 ],
8195                         })
8196                 ];
8197                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8198                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8199                         .with_bolt12_features(bolt12_features.clone()).unwrap();
8200                 let route_params = RouteParameters::from_payment_params_and_value(
8201                         payment_params, amt_msat);
8202                 let netgraph = network_graph.read_only();
8203
8204                 if let Err(LightningError { err, .. }) = get_route(
8205                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8206                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8207                         &random_seed_bytes
8208                 ) {
8209                         assert_eq!(err, "Failed to find a path to the given destination");
8210                 } else { panic!() }
8211         }
8212
8213         #[test]
8214         fn path_contribution_includes_min_htlc_overpay() {
8215                 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8216                 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8217                 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8218                 // selection, both tested here.
8219                 let secp_ctx = Secp256k1::new();
8220                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8221                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8222                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8223                 let random_seed_bytes = [42; 32];
8224                 let config = UserConfig::default();
8225
8226                 // Values are taken from the fuzz input that uncovered this panic.
8227                 let amt_msat = 562_0000;
8228                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8229                 let first_hops = vec![
8230                         get_channel_details(
8231                                 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8232                         ),
8233                 ];
8234
8235                 let htlc_mins = [49_0000, 1125_0000];
8236                 let payment_params = {
8237                         let blinded_path = BlindedPath {
8238                                 introduction_node: IntroductionNode::NodeId(nodes[0]),
8239                                 blinding_point: ln_test_utils::pubkey(42),
8240                                 blinded_hops: vec![
8241                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8242                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8243                                 ],
8244                         };
8245                         let mut blinded_hints = Vec::new();
8246                         for htlc_min in htlc_mins.iter() {
8247                                 blinded_hints.push((BlindedPayInfo {
8248                                         fee_base_msat: 0,
8249                                         fee_proportional_millionths: 0,
8250                                         htlc_minimum_msat: *htlc_min,
8251                                         htlc_maximum_msat: *htlc_min * 100,
8252                                         cltv_expiry_delta: 10,
8253                                         features: BlindedHopFeatures::empty(),
8254                                 }, blinded_path.clone()));
8255                         }
8256                         let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8257                         PaymentParameters::blinded(blinded_hints.clone())
8258                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
8259                 };
8260
8261                 let netgraph = network_graph.read_only();
8262                 let route_params = RouteParameters::from_payment_params_and_value(
8263                         payment_params, amt_msat);
8264                 let route = get_route(
8265                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8266                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8267                         &random_seed_bytes
8268                 ).unwrap();
8269                 assert_eq!(route.paths.len(), 1);
8270                 assert_eq!(route.get_total_amount(), amt_msat);
8271         }
8272
8273         #[test]
8274         fn first_hop_preferred_over_hint() {
8275                 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8276                 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8277                 let secp_ctx = Secp256k1::new();
8278                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8279                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8280                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8281                 let scorer = ln_test_utils::TestScorer::new();
8282                 let random_seed_bytes = [42; 32];
8283                 let config = UserConfig::default();
8284
8285                 let amt_msat = 1_000_000;
8286                 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8287
8288                 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8289                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8290                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8291                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8292                         short_channel_id: 1,
8293                         timestamp: 1,
8294                         flags: 0,
8295                         cltv_expiry_delta: 42,
8296                         htlc_minimum_msat: 1_000,
8297                         htlc_maximum_msat: 10_000_000,
8298                         fee_base_msat: 800,
8299                         fee_proportional_millionths: 0,
8300                         excess_data: Vec::new()
8301                 });
8302                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8303                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8304                         short_channel_id: 1,
8305                         timestamp: 1,
8306                         flags: 1,
8307                         cltv_expiry_delta: 42,
8308                         htlc_minimum_msat: 1_000,
8309                         htlc_maximum_msat: 10_000_000,
8310                         fee_base_msat: 800,
8311                         fee_proportional_millionths: 0,
8312                         excess_data: Vec::new()
8313                 });
8314
8315                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8316                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8317                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8318                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8319                         short_channel_id: 2,
8320                         timestamp: 2,
8321                         flags: 0,
8322                         cltv_expiry_delta: 42,
8323                         htlc_minimum_msat: 1_000,
8324                         htlc_maximum_msat: 10_000_000,
8325                         fee_base_msat: 800,
8326                         fee_proportional_millionths: 0,
8327                         excess_data: Vec::new()
8328                 });
8329                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8330                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8331                         short_channel_id: 2,
8332                         timestamp: 2,
8333                         flags: 1,
8334                         cltv_expiry_delta: 42,
8335                         htlc_minimum_msat: 1_000,
8336                         htlc_maximum_msat: 10_000_000,
8337                         fee_base_msat: 800,
8338                         fee_proportional_millionths: 0,
8339                         excess_data: Vec::new()
8340                 });
8341
8342                 let dest_node_id = nodes[2];
8343
8344                 let route_hint = RouteHint(vec![RouteHintHop {
8345                         src_node_id: our_node_id,
8346                         short_channel_id: 44,
8347                         fees: RoutingFees {
8348                                 base_msat: 234,
8349                                 proportional_millionths: 0,
8350                         },
8351                         cltv_expiry_delta: 10,
8352                         htlc_minimum_msat: None,
8353                         htlc_maximum_msat: Some(5_000_000),
8354                 },
8355                 RouteHintHop {
8356                         src_node_id: nodes[0],
8357                         short_channel_id: 45,
8358                         fees: RoutingFees {
8359                                 base_msat: 123,
8360                                 proportional_millionths: 0,
8361                         },
8362                         cltv_expiry_delta: 10,
8363                         htlc_minimum_msat: None,
8364                         htlc_maximum_msat: None,
8365                 }]);
8366
8367                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8368                         .with_route_hints(vec![route_hint]).unwrap()
8369                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8370                 let route_params = RouteParameters::from_payment_params_and_value(
8371                         payment_params, amt_msat);
8372
8373                 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8374                 // route hint.
8375                 let first_hop = get_channel_details(Some(1), nodes[0],
8376                         channelmanager::provided_init_features(&config), 999_999);
8377                 let first_hops = vec![first_hop];
8378
8379                 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8380                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8381                         &Default::default(), &random_seed_bytes).unwrap();
8382                 assert_eq!(route.paths.len(), 1);
8383                 assert_eq!(route.get_total_amount(), amt_msat);
8384                 assert_eq!(route.paths[0].hops.len(), 2);
8385                 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8386                 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8387                 assert_eq!(route.get_total_fees(), 123);
8388
8389                 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8390                 // for a first hop channel.
8391                 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8392                 first_hop.outbound_scid_alias = Some(44);
8393                 let first_hops = vec![first_hop];
8394
8395                 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8396                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8397                         &Default::default(), &random_seed_bytes);
8398                 assert!(route_res.is_err());
8399
8400                 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8401                 // use the cheaper second hop of the route hint.
8402                 let mut first_hop = get_channel_details(Some(1), nodes[0],
8403                         channelmanager::provided_init_features(&config), 10_000_000);
8404                 first_hop.outbound_scid_alias = Some(44);
8405                 let first_hops = vec![first_hop];
8406
8407                 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8408                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8409                         &Default::default(), &random_seed_bytes).unwrap();
8410                 assert_eq!(route.paths.len(), 1);
8411                 assert_eq!(route.get_total_amount(), amt_msat);
8412                 assert_eq!(route.paths[0].hops.len(), 2);
8413                 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8414                 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8415                 assert_eq!(route.get_total_fees(), 123);
8416         }
8417
8418         #[test]
8419         fn allow_us_being_first_hint() {
8420                 // Check that we consider a route hint even if we are the src of the first hop.
8421                 let secp_ctx = Secp256k1::new();
8422                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8423                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8424                 let scorer = ln_test_utils::TestScorer::new();
8425                 let random_seed_bytes = [42; 32];
8426                 let config = UserConfig::default();
8427
8428                 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8429
8430                 let amt_msat = 1_000_000;
8431                 let dest_node_id = nodes[1];
8432
8433                 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8434                 let first_hops = vec![first_hop];
8435
8436                 let route_hint = RouteHint(vec![RouteHintHop {
8437                         src_node_id: our_node_id,
8438                         short_channel_id: 44,
8439                         fees: RoutingFees {
8440                                 base_msat: 123,
8441                                 proportional_millionths: 0,
8442                         },
8443                         cltv_expiry_delta: 10,
8444                         htlc_minimum_msat: None,
8445                         htlc_maximum_msat: None,
8446                 }]);
8447
8448                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8449                         .with_route_hints(vec![route_hint]).unwrap()
8450                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8451
8452                 let route_params = RouteParameters::from_payment_params_and_value(
8453                         payment_params, amt_msat);
8454
8455
8456                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8457                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8458                         &Default::default(), &random_seed_bytes).unwrap();
8459
8460                 assert_eq!(route.paths.len(), 1);
8461                 assert_eq!(route.get_total_amount(), amt_msat);
8462                 assert_eq!(route.get_total_fees(), 0);
8463                 assert_eq!(route.paths[0].hops.len(), 1);
8464
8465                 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8466         }
8467 }
8468
8469 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8470 pub(crate) mod bench_utils {
8471         use super::*;
8472         use std::fs::File;
8473
8474         use bitcoin::hashes::Hash;
8475         use bitcoin::secp256k1::SecretKey;
8476
8477         use crate::chain::transaction::OutPoint;
8478         use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate};
8479         use crate::ln::channel_state::{ChannelCounterparty, ChannelShutdownState};
8480         use crate::ln::channelmanager;
8481         use crate::ln::types::ChannelId;
8482         use crate::util::config::UserConfig;
8483         use crate::util::test_utils::TestLogger;
8484         use crate::sync::Arc;
8485
8486         /// Tries to open a network graph file, or panics with a URL to fetch it.
8487         pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8488                 let load_file = |fname, err_str| {
8489                         File::open(fname) // By default we're run in RL/lightning
8490                                 .or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8491                                 .or_else(|_| { // Fall back to guessing based on the binary location
8492                                         // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8493                                         let mut path = std::env::current_exe().unwrap();
8494                                         path.pop(); // lightning-...
8495                                         path.pop(); // deps
8496                                         path.pop(); // debug
8497                                         path.pop(); // target
8498                                         path.push("lightning");
8499                                         path.push(fname);
8500                                         File::open(path)
8501                                 })
8502                                 .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8503                                         // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8504                                         let mut path = std::env::current_exe().unwrap();
8505                                         path.pop(); // bench...
8506                                         path.pop(); // deps
8507                                         path.pop(); // debug
8508                                         path.pop(); // target
8509                                         path.pop(); // bench
8510                                         path.push("lightning");
8511                                         path.push(fname);
8512                                         File::open(path)
8513                                 })
8514                         .map_err(|_| err_str)
8515                 };
8516                 let graph_res = load_file(
8517                         "net_graph-2023-12-10.bin",
8518                         "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.118-2023-12-10.bin and place it at lightning/net_graph-2023-12-10.bin"
8519                 );
8520                 let scorer_res = load_file(
8521                         "scorer-2023-12-10.bin",
8522                         "Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at lightning/scorer-2023-12-10.bin"
8523                 );
8524                 #[cfg(require_route_graph_test)]
8525                 return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8526                 #[cfg(not(require_route_graph_test))]
8527                 return Ok((graph_res?, scorer_res?));
8528         }
8529
8530         pub(crate) fn read_graph_scorer(logger: &TestLogger)
8531         -> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8532                 let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8533                 let graph = Arc::new(NetworkGraph::read(&mut graph_file, logger).unwrap());
8534                 let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8535                 let scorer = ProbabilisticScorer::read(&mut scorer_file, scorer_args).unwrap();
8536                 Ok((graph, scorer))
8537         }
8538
8539         pub(crate) fn payer_pubkey() -> PublicKey {
8540                 let secp_ctx = Secp256k1::new();
8541                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8542         }
8543
8544         #[inline]
8545         pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8546                 ChannelDetails {
8547                         channel_id: ChannelId::new_zero(),
8548                         counterparty: ChannelCounterparty {
8549                                 features: channelmanager::provided_init_features(&UserConfig::default()),
8550                                 node_id,
8551                                 unspendable_punishment_reserve: 0,
8552                                 forwarding_info: None,
8553                                 outbound_htlc_minimum_msat: None,
8554                                 outbound_htlc_maximum_msat: None,
8555                         },
8556                         funding_txo: Some(OutPoint {
8557                                 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8558                         }),
8559                         channel_type: None,
8560                         short_channel_id: Some(1),
8561                         inbound_scid_alias: None,
8562                         outbound_scid_alias: None,
8563                         channel_value_satoshis: 10_000_000_000,
8564                         user_channel_id: 0,
8565                         balance_msat: 10_000_000_000,
8566                         outbound_capacity_msat: 10_000_000_000,
8567                         next_outbound_htlc_minimum_msat: 0,
8568                         next_outbound_htlc_limit_msat: 10_000_000_000,
8569                         inbound_capacity_msat: 0,
8570                         unspendable_punishment_reserve: None,
8571                         confirmations_required: None,
8572                         confirmations: None,
8573                         force_close_spend_delay: None,
8574                         is_outbound: true,
8575                         is_channel_ready: true,
8576                         is_usable: true,
8577                         is_public: true,
8578                         inbound_htlc_minimum_msat: None,
8579                         inbound_htlc_maximum_msat: None,
8580                         config: None,
8581                         feerate_sat_per_1000_weight: None,
8582                         channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
8583                         pending_inbound_htlcs: Vec::new(),
8584                         pending_outbound_htlcs: Vec::new(),
8585                 }
8586         }
8587
8588         pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8589                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8590                 starting_amount: u64, route_count: usize,
8591         ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8592                 let payer = payer_pubkey();
8593                 let random_seed_bytes = [42; 32];
8594
8595                 let nodes = graph.read_only().nodes().clone();
8596                 let mut route_endpoints = Vec::new();
8597                 for _ in 0..route_count {
8598                         loop {
8599                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8600                                 let src = PublicKey::from_slice(nodes.unordered_keys()
8601                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8602                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8603                                 let dst = PublicKey::from_slice(nodes.unordered_keys()
8604                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8605                                 let params = PaymentParameters::from_node_id(dst, 42)
8606                                         .with_bolt11_features(features.clone()).unwrap();
8607                                 let first_hop = first_hop(src);
8608                                 let amt_msat = starting_amount + seed % 1_000_000;
8609                                 let route_params = RouteParameters::from_payment_params_and_value(
8610                                         params.clone(), amt_msat);
8611                                 let path_exists =
8612                                         get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8613                                                 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8614                                 if path_exists {
8615                                         route_endpoints.push((first_hop, params, amt_msat));
8616                                         break;
8617                                 }
8618                         }
8619                 }
8620
8621                 route_endpoints
8622         }
8623 }
8624
8625 #[cfg(ldk_bench)]
8626 pub mod benches {
8627         use super::*;
8628         use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8629         use crate::ln::channelmanager;
8630         use crate::ln::features::Bolt11InvoiceFeatures;
8631         use crate::routing::gossip::NetworkGraph;
8632         use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
8633         use crate::util::config::UserConfig;
8634         use crate::util::logger::{Logger, Record};
8635         use crate::util::test_utils::TestLogger;
8636
8637         use criterion::Criterion;
8638
8639         struct DummyLogger {}
8640         impl Logger for DummyLogger {
8641                 fn log(&self, _record: Record) {}
8642         }
8643
8644         pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8645                 let logger = TestLogger::new();
8646                 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8647                 let scorer = FixedPenaltyScorer::with_penalty(0);
8648                 generate_routes(bench, &network_graph, scorer, &Default::default(),
8649                         Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8650         }
8651
8652         pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8653                 let logger = TestLogger::new();
8654                 let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
8655                 let scorer = FixedPenaltyScorer::with_penalty(0);
8656                 generate_routes(bench, &network_graph, scorer, &Default::default(),
8657                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8658                         "generate_mpp_routes_with_zero_penalty_scorer");
8659         }
8660
8661         pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8662                 let logger = TestLogger::new();
8663                 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8664                 let params = ProbabilisticScoringFeeParameters::default();
8665                 generate_routes(bench, &network_graph, scorer, &params, Bolt11InvoiceFeatures::empty(), 0,
8666                         "generate_routes_with_probabilistic_scorer");
8667         }
8668
8669         pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8670                 let logger = TestLogger::new();
8671                 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8672                 let params = ProbabilisticScoringFeeParameters::default();
8673                 generate_routes(bench, &network_graph, scorer, &params,
8674                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8675                         "generate_mpp_routes_with_probabilistic_scorer");
8676         }
8677
8678         pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8679                 let logger = TestLogger::new();
8680                 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8681                 let params = ProbabilisticScoringFeeParameters::default();
8682                 generate_routes(bench, &network_graph, scorer, &params,
8683                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8684                         "generate_large_mpp_routes_with_probabilistic_scorer");
8685         }
8686
8687         pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8688                 let logger = TestLogger::new();
8689                 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8690                 let mut params = ProbabilisticScoringFeeParameters::default();
8691                 params.linear_success_probability = false;
8692                 generate_routes(bench, &network_graph, scorer, &params,
8693                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8694                         "generate_routes_with_nonlinear_probabilistic_scorer");
8695         }
8696
8697         pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8698                 let logger = TestLogger::new();
8699                 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8700                 let mut params = ProbabilisticScoringFeeParameters::default();
8701                 params.linear_success_probability = false;
8702                 generate_routes(bench, &network_graph, scorer, &params,
8703                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8704                         "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8705         }
8706
8707         pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8708                 let logger = TestLogger::new();
8709                 let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
8710                 let mut params = ProbabilisticScoringFeeParameters::default();
8711                 params.linear_success_probability = false;
8712                 generate_routes(bench, &network_graph, scorer, &params,
8713                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8714                         "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8715         }
8716
8717         fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8718                 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8719                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8720                 bench_name: &'static str,
8721         ) {
8722                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8723                 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8724
8725                 // ...then benchmark finding paths between the nodes we learned.
8726                 do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
8727         }
8728
8729         #[inline(never)]
8730         fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
8731                 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
8732                 score_params: &S::ScoreParams, bench_name: &'static str,
8733                 route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
8734         ) {
8735                 let payer = bench_utils::payer_pubkey();
8736                 let random_seed_bytes = [42; 32];
8737
8738                 let mut idx = 0;
8739                 bench.bench_function(bench_name, |b| b.iter(|| {
8740                         let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8741                         let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8742                         assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8743                                 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());
8744                         idx += 1;
8745                 }));
8746         }
8747 }