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