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