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