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