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