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