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