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