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