33182f7cb0d87f94723356345e0a2f3199b5eeb1
[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         let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
1626
1627         log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph with a fee limit of {} msat",
1628                 our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
1629                 if allow_mpp { "with" } else { "without" },
1630                 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " },
1631                 max_total_routing_fee_msat);
1632
1633         // Step (1).
1634         // Prepare the data we'll use for payee-to-payer search by
1635         // inserting first hops suggested by the caller as targets.
1636         // Our search will then attempt to reach them while traversing from the payee node.
1637         let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1638                 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1639         if let Some(hops) = first_hops {
1640                 for chan in hops {
1641                         if chan.get_outbound_payment_scid().is_none() {
1642                                 panic!("first_hops should be filled in with usable channels, not pending ones");
1643                         }
1644                         if chan.counterparty.node_id == *our_node_pubkey {
1645                                 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1646                         }
1647                         first_hop_targets
1648                                 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1649                                 .or_insert(Vec::new())
1650                                 .push(chan);
1651                 }
1652                 if first_hop_targets.is_empty() {
1653                         return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1654                 }
1655         }
1656
1657         // The main heap containing all candidate next-hops sorted by their score (max(fee,
1658         // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1659         // adding duplicate entries when we find a better path to a given node.
1660         let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1661
1662         // Map from node_id to information about the best current path to that node, including feerate
1663         // information.
1664         let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1665
1666         // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1667         // indicating that we may wish to try again with a higher value, potentially paying to meet an
1668         // htlc_minimum with extra fees while still finding a cheaper path.
1669         let mut hit_minimum_limit;
1670
1671         // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1672         // We start with a path_value of the exact amount we want, and if that generates a route we may
1673         // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1674         // amount we want in total across paths, selecting the best subset at the end.
1675         const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1676         let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1677         let mut path_value_msat = final_value_msat;
1678
1679         // Routing Fragmentation Mitigation heuristic:
1680         //
1681         // Routing fragmentation across many payment paths increases the overall routing
1682         // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1683         // Taking too many smaller paths also increases the chance of payment failure.
1684         // Thus to avoid this effect, we require from our collected links to provide
1685         // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1686         // This requirement is currently set to be 1/max_path_count of the payment
1687         // value to ensure we only ever return routes that do not violate this limit.
1688         let minimal_value_contribution_msat: u64 = if allow_mpp {
1689                 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1690         } else {
1691                 final_value_msat
1692         };
1693
1694         // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1695         // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1696         // drop the requirement by setting this to 0.
1697         let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1698
1699         // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1700         // determine if the channel can be used by additional MPP paths or to inform path finding
1701         // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1702         // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1703         // direction.
1704         let mut used_liquidities: HashMap<CandidateHopId, u64> =
1705                 HashMap::with_capacity(network_nodes.len());
1706
1707         // Keeping track of how much value we already collected across other paths. Helps to decide
1708         // when we want to stop looking for new paths.
1709         let mut already_collected_value_msat = 0;
1710
1711         for (_, channels) in first_hop_targets.iter_mut() {
1712                 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1713                         our_node_pubkey);
1714         }
1715
1716         log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1717                 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1718
1719         // Remember how many candidates we ignored to allow for some logging afterwards.
1720         let mut num_ignored_value_contribution: u32 = 0;
1721         let mut num_ignored_path_length_limit: u32 = 0;
1722         let mut num_ignored_cltv_delta_limit: u32 = 0;
1723         let mut num_ignored_previously_failed: u32 = 0;
1724         let mut num_ignored_total_fee_limit: u32 = 0;
1725         let mut num_ignored_avoid_overpayment: u32 = 0;
1726         let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
1727
1728         macro_rules! add_entry {
1729                 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1730                 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1731                 // since that value has to be transferred over this channel.
1732                 // Returns the contribution amount of $candidate if the channel caused an update to `targets`.
1733                 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1734                         $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1735                         $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1736                         // We "return" whether we updated the path at the end, and how much we can route via
1737                         // this channel, via this:
1738                         let mut hop_contribution_amt_msat = None;
1739                         // Channels to self should not be used. This is more of belt-and-suspenders, because in
1740                         // practice these cases should be caught earlier:
1741                         // - for regular channels at channel announcement (TODO)
1742                         // - for first and last hops early in get_route
1743                         if $src_node_id != $dest_node_id {
1744                                 let scid_opt = $candidate.short_channel_id();
1745                                 let effective_capacity = $candidate.effective_capacity();
1746                                 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1747
1748                                 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1749                                 // It may be misleading because we might later choose to reduce the value transferred
1750                                 // over these channels, and the channel which was insufficient might become sufficient.
1751                                 // Worst case: we drop a good channel here because it can't cover the high following
1752                                 // fees caused by one expensive channel, but then this channel could have been used
1753                                 // if the amount being transferred over this path is lower.
1754                                 // We do this for now, but this is a subject for removal.
1755                                 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1756                                         let used_liquidity_msat = used_liquidities
1757                                                 .get(&$candidate.id($src_node_id < $dest_node_id))
1758                                                 .map_or(0, |used_liquidity_msat| {
1759                                                         available_value_contribution_msat = available_value_contribution_msat
1760                                                                 .saturating_sub(*used_liquidity_msat);
1761                                                         *used_liquidity_msat
1762                                                 });
1763
1764                                         // Verify the liquidity offered by this channel complies to the minimal contribution.
1765                                         let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1766                                         // Do not consider candidate hops that would exceed the maximum path length.
1767                                         let path_length_to_node = $next_hops_path_length + 1;
1768                                         let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1769
1770                                         // Do not consider candidates that exceed the maximum total cltv expiry limit.
1771                                         // In order to already account for some of the privacy enhancing random CLTV
1772                                         // expiry delta offset we add on top later, we subtract a rough estimate
1773                                         // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1774                                         let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1775                                                 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1776                                                 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1777                                         let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1778                                                 .saturating_add($candidate.cltv_expiry_delta());
1779                                         let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1780
1781                                         let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1782                                         // Includes paying fees for the use of the following channels.
1783                                         let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1784                                                 Some(result) => result,
1785                                                 // Can't overflow due to how the values were computed right above.
1786                                                 None => unreachable!(),
1787                                         };
1788                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1789                                         let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1790                                                 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1791
1792                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1793                                         let may_overpay_to_meet_path_minimum_msat =
1794                                                 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1795                                                   recommended_value_msat >= $candidate.htlc_minimum_msat()) ||
1796                                                  (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1797                                                   recommended_value_msat >= $next_hops_path_htlc_minimum_msat));
1798
1799                                         let payment_failed_on_this_channel = scid_opt.map_or(false,
1800                                                 |scid| payment_params.previously_failed_channels.contains(&scid));
1801
1802                                         let should_log_candidate = match $candidate {
1803                                                 CandidateRouteHop::FirstHop { .. } => true,
1804                                                 CandidateRouteHop::PrivateHop { .. } => true,
1805                                                 CandidateRouteHop::Blinded { .. } => true,
1806                                                 CandidateRouteHop::OneHopBlinded { .. } => true,
1807                                                 _ => false,
1808                                         };
1809
1810                                         // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1811                                         // bother considering this channel. If retrying with recommended_value_msat may
1812                                         // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1813                                         // around again with a higher amount.
1814                                         if !contributes_sufficient_value {
1815                                                 if should_log_candidate {
1816                                                         log_trace!(logger, "Ignoring {} due to insufficient value contribution.", LoggedCandidateHop(&$candidate));
1817                                                 }
1818                                                 num_ignored_value_contribution += 1;
1819                                         } else if exceeds_max_path_length {
1820                                                 if should_log_candidate {
1821                                                         log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
1822                                                 }
1823                                                 num_ignored_path_length_limit += 1;
1824                                         } else if exceeds_cltv_delta_limit {
1825                                                 if should_log_candidate {
1826                                                         log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
1827                                                 }
1828                                                 num_ignored_cltv_delta_limit += 1;
1829                                         } else if payment_failed_on_this_channel {
1830                                                 if should_log_candidate {
1831                                                         log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
1832                                                 }
1833                                                 num_ignored_previously_failed += 1;
1834                                         } else if may_overpay_to_meet_path_minimum_msat {
1835                                                 if should_log_candidate {
1836                                                         log_trace!(logger,
1837                                                                 "Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit.",
1838                                                                 LoggedCandidateHop(&$candidate));
1839                                                 }
1840                                                 num_ignored_avoid_overpayment += 1;
1841                                                 hit_minimum_limit = true;
1842                                         } else if over_path_minimum_msat {
1843                                                 // Note that low contribution here (limited by available_liquidity_msat)
1844                                                 // might violate htlc_minimum_msat on the hops which are next along the
1845                                                 // payment path (upstream to the payee). To avoid that, we recompute
1846                                                 // path fees knowing the final path contribution after constructing it.
1847                                                 let curr_min = cmp::max(
1848                                                         $next_hops_path_htlc_minimum_msat, $candidate.htlc_minimum_msat()
1849                                                 );
1850                                                 let path_htlc_minimum_msat = compute_fees_saturating(curr_min, $candidate.fees())
1851                                                         .saturating_add(curr_min);
1852                                                 let hm_entry = dist.entry($src_node_id);
1853                                                 let old_entry = hm_entry.or_insert_with(|| {
1854                                                         // If there was previously no known way to access the source node
1855                                                         // (recall it goes payee-to-payer) of short_channel_id, first add a
1856                                                         // semi-dummy record just to compute the fees to reach the source node.
1857                                                         // This will affect our decision on selecting short_channel_id
1858                                                         // as a way to reach the $dest_node_id.
1859                                                         PathBuildingHop {
1860                                                                 node_id: $dest_node_id.clone(),
1861                                                                 candidate: $candidate.clone(),
1862                                                                 fee_msat: 0,
1863                                                                 next_hops_fee_msat: u64::max_value(),
1864                                                                 hop_use_fee_msat: u64::max_value(),
1865                                                                 total_fee_msat: u64::max_value(),
1866                                                                 path_htlc_minimum_msat,
1867                                                                 path_penalty_msat: u64::max_value(),
1868                                                                 was_processed: false,
1869                                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1870                                                                 value_contribution_msat,
1871                                                         }
1872                                                 });
1873
1874                                                 #[allow(unused_mut)] // We only use the mut in cfg(test)
1875                                                 let mut should_process = !old_entry.was_processed;
1876                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1877                                                 {
1878                                                         // In test/fuzzing builds, we do extra checks to make sure the skipping
1879                                                         // of already-seen nodes only happens in cases we expect (see below).
1880                                                         if !should_process { should_process = true; }
1881                                                 }
1882
1883                                                 if should_process {
1884                                                         let mut hop_use_fee_msat = 0;
1885                                                         let mut total_fee_msat: u64 = $next_hops_fee_msat;
1886
1887                                                         // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1888                                                         // will have the same effective-fee
1889                                                         if $src_node_id != our_node_id {
1890                                                                 // Note that `u64::max_value` means we'll always fail the
1891                                                                 // `old_entry.total_fee_msat > total_fee_msat` check below
1892                                                                 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1893                                                                 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1894                                                         }
1895
1896                                                         // Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
1897                                                         if total_fee_msat > max_total_routing_fee_msat {
1898                                                                 if should_log_candidate {
1899                                                                         log_trace!(logger, "Ignoring {} due to exceeding max total routing fee limit.", LoggedCandidateHop(&$candidate));
1900                                                                 }
1901                                                                 num_ignored_total_fee_limit += 1;
1902                                                         } else {
1903                                                                 let channel_usage = ChannelUsage {
1904                                                                         amount_msat: amount_to_transfer_over_msat,
1905                                                                         inflight_htlc_msat: used_liquidity_msat,
1906                                                                         effective_capacity,
1907                                                                 };
1908                                                                 let channel_penalty_msat = scid_opt.map_or(0,
1909                                                                         |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1910                                                                                 channel_usage, score_params));
1911                                                                 let path_penalty_msat = $next_hops_path_penalty_msat
1912                                                                         .saturating_add(channel_penalty_msat);
1913                                                                 let new_graph_node = RouteGraphNode {
1914                                                                         node_id: $src_node_id,
1915                                                                         lowest_fee_to_node: total_fee_msat,
1916                                                                         total_cltv_delta: hop_total_cltv_delta,
1917                                                                         value_contribution_msat,
1918                                                                         path_htlc_minimum_msat,
1919                                                                         path_penalty_msat,
1920                                                                         path_length_to_node,
1921                                                                 };
1922
1923                                                                 // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1924                                                                 // if this way is cheaper than the already known
1925                                                                 // (considering the cost to "reach" this channel from the route destination,
1926                                                                 // the cost of using this channel,
1927                                                                 // and the cost of routing to the source node of this channel).
1928                                                                 // Also, consider that htlc_minimum_msat_difference, because we might end up
1929                                                                 // paying it. Consider the following exploit:
1930                                                                 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1931                                                                 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1932                                                                 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1933                                                                 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1934                                                                 // to this channel.
1935                                                                 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1936                                                                 // but it may require additional tracking - we don't want to double-count
1937                                                                 // the fees included in $next_hops_path_htlc_minimum_msat, but also
1938                                                                 // can't use something that may decrease on future hops.
1939                                                                 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1940                                                                         .saturating_add(old_entry.path_penalty_msat);
1941                                                                 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1942                                                                         .saturating_add(path_penalty_msat);
1943
1944                                                                 if !old_entry.was_processed && new_cost < old_cost {
1945                                                                         targets.push(new_graph_node);
1946                                                                         old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1947                                                                         old_entry.hop_use_fee_msat = hop_use_fee_msat;
1948                                                                         old_entry.total_fee_msat = total_fee_msat;
1949                                                                         old_entry.node_id = $dest_node_id.clone();
1950                                                                         old_entry.candidate = $candidate.clone();
1951                                                                         old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1952                                                                         old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1953                                                                         old_entry.path_penalty_msat = path_penalty_msat;
1954                                                                         #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1955                                                                         {
1956                                                                                 old_entry.value_contribution_msat = value_contribution_msat;
1957                                                                         }
1958                                                                         hop_contribution_amt_msat = Some(value_contribution_msat);
1959                                                                 } else if old_entry.was_processed && new_cost < old_cost {
1960                                                                         #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1961                                                                         {
1962                                                                                 // If we're skipping processing a node which was previously
1963                                                                                 // processed even though we found another path to it with a
1964                                                                                 // cheaper fee, check that it was because the second path we
1965                                                                                 // found (which we are processing now) has a lower value
1966                                                                                 // contribution due to an HTLC minimum limit.
1967                                                                                 //
1968                                                                                 // e.g. take a graph with two paths from node 1 to node 2, one
1969                                                                                 // through channel A, and one through channel B. Channel A and
1970                                                                                 // B are both in the to-process heap, with their scores set by
1971                                                                                 // a higher htlc_minimum than fee.
1972                                                                                 // Channel A is processed first, and the channels onwards from
1973                                                                                 // node 1 are added to the to-process heap. Thereafter, we pop
1974                                                                                 // Channel B off of the heap, note that it has a much more
1975                                                                                 // restrictive htlc_maximum_msat, and recalculate the fees for
1976                                                                                 // all of node 1's channels using the new, reduced, amount.
1977                                                                                 //
1978                                                                                 // This would be bogus - we'd be selecting a higher-fee path
1979                                                                                 // with a lower htlc_maximum_msat instead of the one we'd
1980                                                                                 // already decided to use.
1981                                                                                 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1982                                                                                 debug_assert!(
1983                                                                                         value_contribution_msat + path_penalty_msat <
1984                                                                                         old_entry.value_contribution_msat + old_entry.path_penalty_msat
1985                                                                                 );
1986                                                                         }
1987                                                                 }
1988                                                         }
1989                                                 }
1990                                         } else {
1991                                                 if should_log_candidate {
1992                                                         log_trace!(logger,
1993                                                                 "Ignoring {} due to its htlc_minimum_msat limit.",
1994                                                                 LoggedCandidateHop(&$candidate));
1995                                                 }
1996                                                 num_ignored_htlc_minimum_msat_limit += 1;
1997                                         }
1998                                 }
1999                         }
2000                         hop_contribution_amt_msat
2001                 } }
2002         }
2003
2004         let default_node_features = default_node_features();
2005
2006         // Find ways (channels with destination) to reach a given node and store them
2007         // in the corresponding data structures (routing graph etc).
2008         // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2009         // meaning how much will be paid in fees after this node (to the best of our knowledge).
2010         // This data can later be helpful to optimize routing (pay lower fees).
2011         macro_rules! add_entries_to_cheapest_to_target_node {
2012                 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
2013                   $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
2014                   $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2015                         let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
2016                                 let was_processed = elem.was_processed;
2017                                 elem.was_processed = true;
2018                                 was_processed
2019                         } else {
2020                                 // Entries are added to dist in add_entry!() when there is a channel from a node.
2021                                 // Because there are no channels from payee, it will not have a dist entry at this point.
2022                                 // If we're processing any other node, it is always be the result of a channel from it.
2023                                 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2024                                 false
2025                         };
2026
2027                         if !skip_node {
2028                                 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
2029                                         for details in first_channels {
2030                                                 let candidate = CandidateRouteHop::FirstHop { details };
2031                                                 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
2032                                                         $next_hops_value_contribution,
2033                                                         $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
2034                                                         $next_hops_cltv_delta, $next_hops_path_length);
2035                                         }
2036                                 }
2037
2038                                 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
2039                                         &node_info.features
2040                                 } else {
2041                                         &default_node_features
2042                                 };
2043
2044                                 if !features.requires_unknown_bits() {
2045                                         for chan_id in $node.channels.iter() {
2046                                                 let chan = network_channels.get(chan_id).unwrap();
2047                                                 if !chan.features.requires_unknown_bits() {
2048                                                         if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2049                                                                 if first_hops.is_none() || *source != our_node_id {
2050                                                                         if directed_channel.direction().enabled {
2051                                                                                 let candidate = CandidateRouteHop::PublicHop {
2052                                                                                         info: directed_channel,
2053                                                                                         short_channel_id: *chan_id,
2054                                                                                 };
2055                                                                                 add_entry!(candidate, *source, $node_id,
2056                                                                                         $fee_to_target_msat,
2057                                                                                         $next_hops_value_contribution,
2058                                                                                         $next_hops_path_htlc_minimum_msat,
2059                                                                                         $next_hops_path_penalty_msat,
2060                                                                                         $next_hops_cltv_delta, $next_hops_path_length);
2061                                                                         }
2062                                                                 }
2063                                                         }
2064                                                 }
2065                                         }
2066                                 }
2067                         }
2068                 };
2069         }
2070
2071         let mut payment_paths = Vec::<PaymentPath>::new();
2072
2073         // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2074         'paths_collection: loop {
2075                 // For every new path, start from scratch, except for used_liquidities, which
2076                 // helps to avoid reusing previously selected paths in future iterations.
2077                 targets.clear();
2078                 dist.clear();
2079                 hit_minimum_limit = false;
2080
2081                 // If first hop is a private channel and the only way to reach the payee, this is the only
2082                 // place where it could be added.
2083                 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
2084                         for details in first_channels {
2085                                 let candidate = CandidateRouteHop::FirstHop { details };
2086                                 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
2087                                                                         0, 0u64, 0, 0).is_some();
2088                                 log_trace!(logger, "{} direct route to payee via {}",
2089                                                 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
2090                         }
2091                 }));
2092
2093                 // Add the payee as a target, so that the payee-to-payer
2094                 // search algorithm knows what to start with.
2095                 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
2096                         // The payee is not in our network graph, so nothing to add here.
2097                         // There is still a chance of reaching them via last_hops though,
2098                         // so don't yet fail the payment here.
2099                         // If not, targets.pop() will not even let us enter the loop in step 2.
2100                         None => {},
2101                         Some(node) => {
2102                                 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
2103                         },
2104                 });
2105
2106                 // Step (2).
2107                 // If a caller provided us with last hops, add them to routing targets. Since this happens
2108                 // earlier than general path finding, they will be somewhat prioritized, although currently
2109                 // it matters only if the fees are exactly the same.
2110                 for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
2111                         let intro_node_id = NodeId::from_pubkey(&hint.1.introduction_node_id);
2112                         let have_intro_node_in_graph =
2113                                 // Only add the hops in this route to our candidate set if either
2114                                 // we have a direct channel to the first hop or the first hop is
2115                                 // in the regular network graph.
2116                                 first_hop_targets.get(&intro_node_id).is_some() ||
2117                                 network_nodes.get(&intro_node_id).is_some();
2118                         if !have_intro_node_in_graph || our_node_id == intro_node_id { continue }
2119                         let candidate = if hint.1.blinded_hops.len() == 1 {
2120                                 CandidateRouteHop::OneHopBlinded { hint, hint_idx }
2121                         } else { CandidateRouteHop::Blinded { hint, hint_idx } };
2122                         let mut path_contribution_msat = path_value_msat;
2123                         if let Some(hop_used_msat) = add_entry!(candidate, intro_node_id, maybe_dummy_payee_node_id,
2124                                 0, path_contribution_msat, 0, 0_u64, 0, 0)
2125                         {
2126                                 path_contribution_msat = hop_used_msat;
2127                         } else { continue }
2128                         if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hint.1.introduction_node_id)) {
2129                                 sort_first_hop_channels(first_channels, &used_liquidities, recommended_value_msat,
2130                                         our_node_pubkey);
2131                                 for details in first_channels {
2132                                         let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2133                                         let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
2134                                                 Some(fee) => fee,
2135                                                 None => continue
2136                                         };
2137                                         let path_min = candidate.htlc_minimum_msat().saturating_add(
2138                                                 compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
2139                                         add_entry!(first_hop_candidate, our_node_id, intro_node_id, blinded_path_fee,
2140                                                 path_contribution_msat, path_min, 0_u64, candidate.cltv_expiry_delta(),
2141                                                 candidate.blinded_path().map_or(1, |bp| bp.blinded_hops.len() as u8));
2142                                 }
2143                         }
2144                 }
2145                 for route in payment_params.payee.unblinded_route_hints().iter()
2146                         .filter(|route| !route.0.is_empty())
2147                 {
2148                         let first_hop_src_id = NodeId::from_pubkey(&route.0.first().unwrap().src_node_id);
2149                         let first_hop_src_is_reachable =
2150                                 // Only add the hops in this route to our candidate set if either we are part of
2151                                 // the first hop, we have a direct channel to the first hop, or the first hop is in
2152                                 // the regular network graph.
2153                                 our_node_id == first_hop_src_id ||
2154                                 first_hop_targets.get(&first_hop_src_id).is_some() ||
2155                                 network_nodes.get(&first_hop_src_id).is_some();
2156                         if first_hop_src_is_reachable {
2157                                 // We start building the path from reverse, i.e., from payee
2158                                 // to the first RouteHintHop in the path.
2159                                 let hop_iter = route.0.iter().rev();
2160                                 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2161                                         route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2162                                 let mut hop_used = true;
2163                                 let mut aggregate_next_hops_fee_msat: u64 = 0;
2164                                 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
2165                                 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
2166                                 let mut aggregate_next_hops_cltv_delta: u32 = 0;
2167                                 let mut aggregate_next_hops_path_length: u8 = 0;
2168                                 let mut aggregate_path_contribution_msat = path_value_msat;
2169
2170                                 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
2171                                         let source = NodeId::from_pubkey(&hop.src_node_id);
2172                                         let target = NodeId::from_pubkey(&prev_hop_id);
2173
2174                                         if let Some(first_channels) = first_hop_targets.get(&target) {
2175                                                 if first_channels.iter().any(|d| d.outbound_scid_alias == Some(hop.short_channel_id)) {
2176                                                         log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2177                                                                 hop.short_channel_id);
2178                                                         break;
2179                                                 }
2180                                         }
2181
2182                                         let candidate = network_channels
2183                                                 .get(&hop.short_channel_id)
2184                                                 .and_then(|channel| channel.as_directed_to(&target))
2185                                                 .map(|(info, _)| CandidateRouteHop::PublicHop {
2186                                                         info,
2187                                                         short_channel_id: hop.short_channel_id,
2188                                                 })
2189                                                 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
2190
2191                                         if let Some(hop_used_msat) = add_entry!(candidate, source, target,
2192                                                 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2193                                                 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2194                                                 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
2195                                         {
2196                                                 aggregate_path_contribution_msat = hop_used_msat;
2197                                         } else {
2198                                                 // If this hop was not used then there is no use checking the preceding
2199                                                 // hops in the RouteHint. We can break by just searching for a direct
2200                                                 // channel between last checked hop and first_hop_targets.
2201                                                 hop_used = false;
2202                                         }
2203
2204                                         let used_liquidity_msat = used_liquidities
2205                                                 .get(&candidate.id(source < target)).copied()
2206                                                 .unwrap_or(0);
2207                                         let channel_usage = ChannelUsage {
2208                                                 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
2209                                                 inflight_htlc_msat: used_liquidity_msat,
2210                                                 effective_capacity: candidate.effective_capacity(),
2211                                         };
2212                                         let channel_penalty_msat = scorer.channel_penalty_msat(
2213                                                 hop.short_channel_id, &source, &target, channel_usage, score_params
2214                                         );
2215                                         aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
2216                                                 .saturating_add(channel_penalty_msat);
2217
2218                                         aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2219                                                 .saturating_add(hop.cltv_expiry_delta as u32);
2220
2221                                         aggregate_next_hops_path_length = aggregate_next_hops_path_length
2222                                                 .saturating_add(1);
2223
2224                                         // Searching for a direct channel between last checked hop and first_hop_targets
2225                                         if let Some(first_channels) = first_hop_targets.get_mut(&target) {
2226                                                 sort_first_hop_channels(first_channels, &used_liquidities,
2227                                                         recommended_value_msat, our_node_pubkey);
2228                                                 for details in first_channels {
2229                                                         let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2230                                                         add_entry!(first_hop_candidate, our_node_id, target,
2231                                                                 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2232                                                                 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2233                                                                 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2234                                                 }
2235                                         }
2236
2237                                         if !hop_used {
2238                                                 break;
2239                                         }
2240
2241                                         // In the next values of the iterator, the aggregate fees already reflects
2242                                         // the sum of value sent from payer (final_value_msat) and routing fees
2243                                         // for the last node in the RouteHint. We need to just add the fees to
2244                                         // route through the current node so that the preceding node (next iteration)
2245                                         // can use it.
2246                                         let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2247                                                 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2248                                         aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2249
2250                                         // The next channel will need to relay this channel's min_htlc *plus* the fees taken by
2251                                         // this route hint's source node to forward said min over this channel.
2252                                         aggregate_next_hops_path_htlc_minimum_msat = {
2253                                                 let curr_htlc_min = cmp::max(
2254                                                         candidate.htlc_minimum_msat(), aggregate_next_hops_path_htlc_minimum_msat
2255                                                 );
2256                                                 let curr_htlc_min_fee = if let Some(val) = compute_fees(curr_htlc_min, hop.fees) { val } else { break };
2257                                                 if let Some(min) = curr_htlc_min.checked_add(curr_htlc_min_fee) { min } else { break }
2258                                         };
2259
2260                                         if idx == route.0.len() - 1 {
2261                                                 // The last hop in this iterator is the first hop in
2262                                                 // overall RouteHint.
2263                                                 // If this hop connects to a node with which we have a direct channel,
2264                                                 // ignore the network graph and, if the last hop was added, add our
2265                                                 // direct channel to the candidate set.
2266                                                 //
2267                                                 // Note that we *must* check if the last hop was added as `add_entry`
2268                                                 // always assumes that the third argument is a node to which we have a
2269                                                 // path.
2270                                                 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2271                                                         sort_first_hop_channels(first_channels, &used_liquidities,
2272                                                                 recommended_value_msat, our_node_pubkey);
2273                                                         for details in first_channels {
2274                                                                 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2275                                                                 add_entry!(first_hop_candidate, our_node_id,
2276                                                                         NodeId::from_pubkey(&hop.src_node_id),
2277                                                                         aggregate_next_hops_fee_msat,
2278                                                                         aggregate_path_contribution_msat,
2279                                                                         aggregate_next_hops_path_htlc_minimum_msat,
2280                                                                         aggregate_next_hops_path_penalty_msat,
2281                                                                         aggregate_next_hops_cltv_delta,
2282                                                                         aggregate_next_hops_path_length);
2283                                                         }
2284                                                 }
2285                                         }
2286                                 }
2287                         }
2288                 }
2289
2290                 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2291
2292                 // At this point, targets are filled with the data from first and
2293                 // last hops communicated by the caller, and the payment receiver.
2294                 let mut found_new_path = false;
2295
2296                 // Step (3).
2297                 // If this loop terminates due the exhaustion of targets, two situations are possible:
2298                 // - not enough outgoing liquidity:
2299                 //   0 < already_collected_value_msat < final_value_msat
2300                 // - enough outgoing liquidity:
2301                 //   final_value_msat <= already_collected_value_msat < recommended_value_msat
2302                 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2303                 // paths_collection will be stopped because found_new_path==false.
2304                 // This is not necessarily a routing failure.
2305                 '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() {
2306
2307                         // Since we're going payee-to-payer, hitting our node as a target means we should stop
2308                         // traversing the graph and arrange the path out of what we found.
2309                         if node_id == our_node_id {
2310                                 let mut new_entry = dist.remove(&our_node_id).unwrap();
2311                                 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2312
2313                                 'path_walk: loop {
2314                                         let mut features_set = false;
2315                                         if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2316                                                 for details in first_channels {
2317                                                         if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2318                                                                 if details.get_outbound_payment_scid().unwrap() == scid {
2319                                                                         ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2320                                                                         features_set = true;
2321                                                                         break;
2322                                                                 }
2323                                                         }
2324                                                 }
2325                                         }
2326                                         if !features_set {
2327                                                 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2328                                                         if let Some(node_info) = node.announcement_info.as_ref() {
2329                                                                 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2330                                                         } else {
2331                                                                 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2332                                                         }
2333                                                 } else {
2334                                                         // We can fill in features for everything except hops which were
2335                                                         // provided via the invoice we're paying. We could guess based on the
2336                                                         // recipient's features but for now we simply avoid guessing at all.
2337                                                 }
2338                                         }
2339
2340                                         // Means we succesfully traversed from the payer to the payee, now
2341                                         // save this path for the payment route. Also, update the liquidity
2342                                         // remaining on the used hops, so that we take them into account
2343                                         // while looking for more paths.
2344                                         if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2345                                                 break 'path_walk;
2346                                         }
2347
2348                                         new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2349                                                 Some(payment_hop) => payment_hop,
2350                                                 // We can't arrive at None because, if we ever add an entry to targets,
2351                                                 // we also fill in the entry in dist (see add_entry!).
2352                                                 None => unreachable!(),
2353                                         };
2354                                         // We "propagate" the fees one hop backward (topologically) here,
2355                                         // so that fees paid for a HTLC forwarding on the current channel are
2356                                         // associated with the previous channel (where they will be subtracted).
2357                                         ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2358                                         ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2359                                 }
2360                                 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2361                                 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2362
2363                                 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2364                                         ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2365
2366                                 let mut payment_path = PaymentPath {hops: ordered_hops};
2367
2368                                 // We could have possibly constructed a slightly inconsistent path: since we reduce
2369                                 // value being transferred along the way, we could have violated htlc_minimum_msat
2370                                 // on some channels we already passed (assuming dest->source direction). Here, we
2371                                 // recompute the fees again, so that if that's the case, we match the currently
2372                                 // underpaid htlc_minimum_msat with fees.
2373                                 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2374                                 let desired_value_contribution = cmp::min(value_contribution_msat, final_value_msat);
2375                                 value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
2376
2377                                 // Since a path allows to transfer as much value as
2378                                 // the smallest channel it has ("bottleneck"), we should recompute
2379                                 // the fees so sender HTLC don't overpay fees when traversing
2380                                 // larger channels than the bottleneck. This may happen because
2381                                 // when we were selecting those channels we were not aware how much value
2382                                 // this path will transfer, and the relative fee for them
2383                                 // might have been computed considering a larger value.
2384                                 // Remember that we used these channels so that we don't rely
2385                                 // on the same liquidity in future paths.
2386                                 let mut prevented_redundant_path_selection = false;
2387                                 let prev_hop_iter = core::iter::once(&our_node_id)
2388                                         .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2389                                 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2390                                         let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2391                                         let used_liquidity_msat = used_liquidities
2392                                                 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2393                                                 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2394                                                 .or_insert(spent_on_hop_msat);
2395                                         let hop_capacity = hop.candidate.effective_capacity();
2396                                         let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2397                                         if *used_liquidity_msat == hop_max_msat {
2398                                                 // If this path used all of this channel's available liquidity, we know
2399                                                 // this path will not be selected again in the next loop iteration.
2400                                                 prevented_redundant_path_selection = true;
2401                                         }
2402                                         debug_assert!(*used_liquidity_msat <= hop_max_msat);
2403                                 }
2404                                 if !prevented_redundant_path_selection {
2405                                         // If we weren't capped by hitting a liquidity limit on a channel in the path,
2406                                         // we'll probably end up picking the same path again on the next iteration.
2407                                         // Decrease the available liquidity of a hop in the middle of the path.
2408                                         let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2409                                         let exhausted = u64::max_value();
2410                                         log_trace!(logger,
2411                                                 "Disabling route candidate {} for future path building iterations to avoid duplicates.",
2412                                                 LoggedCandidateHop(victim_candidate));
2413                                         *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2414                                         *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2415                                 }
2416
2417                                 // Track the total amount all our collected paths allow to send so that we know
2418                                 // when to stop looking for more paths
2419                                 already_collected_value_msat += value_contribution_msat;
2420
2421                                 payment_paths.push(payment_path);
2422                                 found_new_path = true;
2423                                 break 'path_construction;
2424                         }
2425
2426                         // If we found a path back to the payee, we shouldn't try to process it again. This is
2427                         // the equivalent of the `elem.was_processed` check in
2428                         // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2429                         if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2430
2431                         // Otherwise, since the current target node is not us,
2432                         // keep "unrolling" the payment graph from payee to payer by
2433                         // finding a way to reach the current target from the payer side.
2434                         match network_nodes.get(&node_id) {
2435                                 None => {},
2436                                 Some(node) => {
2437                                         add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2438                                                 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2439                                                 total_cltv_delta, path_length_to_node);
2440                                 },
2441                         }
2442                 }
2443
2444                 if !allow_mpp {
2445                         if !found_new_path && channel_saturation_pow_half != 0 {
2446                                 channel_saturation_pow_half = 0;
2447                                 continue 'paths_collection;
2448                         }
2449                         // If we don't support MPP, no use trying to gather more value ever.
2450                         break 'paths_collection;
2451                 }
2452
2453                 // Step (4).
2454                 // Stop either when the recommended value is reached or if no new path was found in this
2455                 // iteration.
2456                 // In the latter case, making another path finding attempt won't help,
2457                 // because we deterministically terminated the search due to low liquidity.
2458                 if !found_new_path && channel_saturation_pow_half != 0 {
2459                         channel_saturation_pow_half = 0;
2460                 } else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
2461                         log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
2462                         path_value_msat = recommended_value_msat;
2463                 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2464                         log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2465                                 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2466                         break 'paths_collection;
2467                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2468                         // Further, if this was our first walk of the graph, and we weren't limited by an
2469                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
2470                         // limited by an htlc_minimum_msat value, find another path with a higher value,
2471                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2472                         // still keeping a lower total fee than this path.
2473                         if !hit_minimum_limit {
2474                                 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2475                                 break 'paths_collection;
2476                         }
2477                         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.");
2478                         path_value_msat = recommended_value_msat;
2479                 }
2480         }
2481
2482         let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
2483                 num_ignored_cltv_delta_limit + num_ignored_previously_failed +
2484                 num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
2485                 num_ignored_total_fee_limit;
2486         if num_ignored_total > 0 {
2487                 log_trace!(logger,
2488                         "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.",
2489                         num_ignored_value_contribution, num_ignored_path_length_limit,
2490                         num_ignored_cltv_delta_limit, num_ignored_previously_failed,
2491                         num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
2492                         num_ignored_total_fee_limit, num_ignored_total);
2493         }
2494
2495         // Step (5).
2496         if payment_paths.len() == 0 {
2497                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2498         }
2499
2500         if already_collected_value_msat < final_value_msat {
2501                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2502         }
2503
2504         // Step (6).
2505         let mut selected_route = payment_paths;
2506
2507         debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2508         let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2509
2510         // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2511         // the value they contribute towards the payment amount.
2512         // We sort in descending order as we will remove from the front in `retain`, next.
2513         selected_route.sort_unstable_by(|a, b|
2514                 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2515                         .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2516         );
2517
2518         // We should make sure that at least 1 path left.
2519         let mut paths_left = selected_route.len();
2520         selected_route.retain(|path| {
2521                 if paths_left == 1 {
2522                         return true
2523                 }
2524                 let path_value_msat = path.get_value_msat();
2525                 if path_value_msat <= overpaid_value_msat {
2526                         overpaid_value_msat -= path_value_msat;
2527                         paths_left -= 1;
2528                         return false;
2529                 }
2530                 true
2531         });
2532         debug_assert!(selected_route.len() > 0);
2533
2534         if overpaid_value_msat != 0 {
2535                 // Step (7).
2536                 // Now, subtract the remaining overpaid value from the most-expensive path.
2537                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2538                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2539                 selected_route.sort_unstable_by(|a, b| {
2540                         let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2541                         let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2542                         a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2543                 });
2544                 let expensive_payment_path = selected_route.first_mut().unwrap();
2545
2546                 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2547                 // can't go negative.
2548                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2549                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2550         }
2551
2552         // Step (8).
2553         // Sort by the path itself and combine redundant paths.
2554         // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2555         // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2556         // across nodes.
2557         selected_route.sort_unstable_by_key(|path| {
2558                 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2559                 debug_assert!(path.hops.len() <= key.len());
2560                 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2561                         *key = scid;
2562                 }
2563                 key
2564         });
2565         for idx in 0..(selected_route.len() - 1) {
2566                 if idx + 1 >= selected_route.len() { break; }
2567                 if iter_equal(selected_route[idx    ].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id)),
2568                               selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(true), h.0.node_id))) {
2569                         let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2570                         selected_route[idx].update_value_and_recompute_fees(new_value);
2571                         selected_route.remove(idx + 1);
2572                 }
2573         }
2574
2575         let mut paths = Vec::new();
2576         for payment_path in selected_route {
2577                 let mut hops = Vec::with_capacity(payment_path.hops.len());
2578                 let mut prev_hop_node_id = our_node_id;
2579                 for (hop, node_features) in payment_path.hops.iter()
2580                         .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2581                 {
2582                         let maybe_announced_channel = if let CandidateRouteHop::PublicHop { .. } = hop.candidate {
2583                                 // If we sourced the hop from the graph we're sure the target node is announced.
2584                                 true
2585                         } else if let CandidateRouteHop::FirstHop { details } = hop.candidate {
2586                                 // If this is a first hop we also know if it's announced.
2587                                 details.is_public
2588                         } else {
2589                                 // If we sourced it any other way, we double-check the network graph to see if
2590                                 // there are announced channels between the endpoints. If so, the hop might be
2591                                 // referring to any of the announced channels, as its `short_channel_id` might be
2592                                 // an alias, in which case we don't take any chances here.
2593                                 network_graph.node(&hop.node_id).map_or(false, |hop_node|
2594                                         hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
2595                                                         .map_or(false, |c| c.as_directed_from(&prev_hop_node_id).is_some()))
2596                                 )
2597                         };
2598
2599                         hops.push(RouteHop {
2600                                 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)})?,
2601                                 node_features: node_features.clone(),
2602                                 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2603                                 channel_features: hop.candidate.features(),
2604                                 fee_msat: hop.fee_msat,
2605                                 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2606                                 maybe_announced_channel,
2607                         });
2608
2609                         prev_hop_node_id = hop.node_id;
2610                 }
2611                 let mut final_cltv_delta = final_cltv_expiry_delta;
2612                 let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
2613                         if let Some(blinded_path) = h.candidate.blinded_path() {
2614                                 final_cltv_delta = h.candidate.cltv_expiry_delta();
2615                                 Some(BlindedTail {
2616                                         hops: blinded_path.blinded_hops.clone(),
2617                                         blinding_point: blinded_path.blinding_point,
2618                                         excess_final_cltv_expiry_delta: 0,
2619                                         final_value_msat: h.fee_msat,
2620                                 })
2621                         } else { None }
2622                 });
2623                 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2624                 // applicable for the previous hop.
2625                 hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
2626                         core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2627                 });
2628
2629                 paths.push(Path { hops, blinded_tail });
2630         }
2631         // Make sure we would never create a route with more paths than we allow.
2632         debug_assert!(paths.len() <= payment_params.max_path_count.into());
2633
2634         if let Some(node_features) = payment_params.payee.node_features() {
2635                 for path in paths.iter_mut() {
2636                         path.hops.last_mut().unwrap().node_features = node_features.clone();
2637                 }
2638         }
2639
2640         let route = Route { paths, route_params: Some(route_params.clone()) };
2641
2642         // Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
2643         if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
2644                 if route.get_total_fees() > max_total_routing_fee_msat {
2645                         return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
2646                                 max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
2647                 }
2648         }
2649
2650         log_info!(logger, "Got route: {}", log_route!(route));
2651         Ok(route)
2652 }
2653
2654 // When an adversarial intermediary node observes a payment, it may be able to infer its
2655 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2656 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2657 // payment path by adding a randomized 'shadow route' offset to the final hop.
2658 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2659         network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2660 ) {
2661         let network_channels = network_graph.channels();
2662         let network_nodes = network_graph.nodes();
2663
2664         for path in route.paths.iter_mut() {
2665                 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2666
2667                 // Remember the last three nodes of the random walk and avoid looping back on them.
2668                 // Init with the last three nodes from the actual path, if possible.
2669                 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2670                         NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2671                         NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2672
2673                 // Choose the last publicly known node as the starting point for the random walk.
2674                 let mut cur_hop: Option<NodeId> = None;
2675                 let mut path_nonce = [0u8; 12];
2676                 if let Some(starting_hop) = path.hops.iter().rev()
2677                         .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2678                                 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2679                                 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2680                 }
2681
2682                 // Init PRNG with the path-dependant nonce, which is static for private paths.
2683                 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2684                 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2685
2686                 // Pick a random path length in [1 .. 3]
2687                 prng.process_in_place(&mut random_path_bytes);
2688                 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2689
2690                 for random_hop in 0..random_walk_length {
2691                         // If we don't find a suitable offset in the public network graph, we default to
2692                         // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2693                         let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2694
2695                         if let Some(cur_node_id) = cur_hop {
2696                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2697                                         // Randomly choose the next unvisited hop.
2698                                         prng.process_in_place(&mut random_path_bytes);
2699                                         if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2700                                                 .checked_rem(cur_node.channels.len())
2701                                                 .and_then(|index| cur_node.channels.get(index))
2702                                                 .and_then(|id| network_channels.get(id)) {
2703                                                         random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2704                                                                 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2705                                                                         nodes_to_avoid[random_hop] = *next_id;
2706                                                                         random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2707                                                                         cur_hop = Some(*next_id);
2708                                                                 }
2709                                                         });
2710                                                 }
2711                                 }
2712                         }
2713
2714                         shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2715                                 .checked_add(random_hop_offset)
2716                                 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2717                 }
2718
2719                 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2720                 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2721                 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2722
2723                 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2724                 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2725                 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2726                 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2727                 max_path_offset = cmp::max(
2728                         max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2729                         max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2730                 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2731
2732                 // Add 'shadow' CLTV offset to the final hop
2733                 if let Some(tail) = path.blinded_tail.as_mut() {
2734                         tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2735                                 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2736                 }
2737                 if let Some(last_hop) = path.hops.last_mut() {
2738                         last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2739                                 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2740                 }
2741         }
2742 }
2743
2744 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2745 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2746 ///
2747 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2748 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2749         our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2750         network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2751 ) -> Result<Route, LightningError>
2752 where L::Target: Logger, GL::Target: Logger {
2753         let graph_lock = network_graph.read_only();
2754         let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
2755                 &graph_lock, logger, random_seed_bytes)?;
2756         add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2757         Ok(route)
2758 }
2759
2760 fn build_route_from_hops_internal<L: Deref>(
2761         our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2762         network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
2763 ) -> Result<Route, LightningError> where L::Target: Logger {
2764
2765         struct HopScorer {
2766                 our_node_id: NodeId,
2767                 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2768         }
2769
2770         impl ScoreLookUp for HopScorer {
2771                 type ScoreParams = ();
2772                 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2773                         _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2774                 {
2775                         let mut cur_id = self.our_node_id;
2776                         for i in 0..self.hop_ids.len() {
2777                                 if let Some(next_id) = self.hop_ids[i] {
2778                                         if cur_id == *source && next_id == *target {
2779                                                 return 0;
2780                                         }
2781                                         cur_id = next_id;
2782                                 } else {
2783                                         break;
2784                                 }
2785                         }
2786                         u64::max_value()
2787                 }
2788         }
2789
2790         impl<'a> Writeable for HopScorer {
2791                 #[inline]
2792                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2793                         unreachable!();
2794                 }
2795         }
2796
2797         if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2798                 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2799         }
2800
2801         let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2802         let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2803         for i in 0..hops.len() {
2804                 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2805         }
2806
2807         let scorer = HopScorer { our_node_id, hop_ids };
2808
2809         get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
2810 }
2811
2812 #[cfg(test)]
2813 mod tests {
2814         use crate::blinded_path::{BlindedHop, BlindedPath};
2815         use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2816         use crate::routing::utxo::UtxoResult;
2817         use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2818                 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2819                 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters};
2820         use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2821         use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2822         use crate::chain::transaction::OutPoint;
2823         use crate::sign::EntropySource;
2824         use crate::ln::ChannelId;
2825         use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
2826         use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2827         use crate::ln::channelmanager;
2828         use crate::offers::invoice::BlindedPayInfo;
2829         use crate::util::config::UserConfig;
2830         use crate::util::test_utils as ln_test_utils;
2831         use crate::util::chacha20::ChaCha20;
2832         use crate::util::ser::{Readable, Writeable};
2833         #[cfg(c_bindings)]
2834         use crate::util::ser::Writer;
2835
2836         use bitcoin::hashes::Hash;
2837         use bitcoin::network::constants::Network;
2838         use bitcoin::blockdata::constants::genesis_block;
2839         use bitcoin::blockdata::script::Builder;
2840         use bitcoin::blockdata::opcodes;
2841         use bitcoin::blockdata::transaction::TxOut;
2842
2843         use hex;
2844
2845         use bitcoin::secp256k1::{PublicKey,SecretKey};
2846         use bitcoin::secp256k1::Secp256k1;
2847
2848         use crate::io::Cursor;
2849         use crate::prelude::*;
2850         use crate::sync::Arc;
2851
2852         use core::convert::TryInto;
2853
2854         fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2855                         features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2856                 channelmanager::ChannelDetails {
2857                         channel_id: ChannelId::new_zero(),
2858                         counterparty: channelmanager::ChannelCounterparty {
2859                                 features,
2860                                 node_id,
2861                                 unspendable_punishment_reserve: 0,
2862                                 forwarding_info: None,
2863                                 outbound_htlc_minimum_msat: None,
2864                                 outbound_htlc_maximum_msat: None,
2865                         },
2866                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2867                         channel_type: None,
2868                         short_channel_id,
2869                         outbound_scid_alias: None,
2870                         inbound_scid_alias: None,
2871                         channel_value_satoshis: 0,
2872                         user_channel_id: 0,
2873                         outbound_capacity_msat,
2874                         next_outbound_htlc_limit_msat: outbound_capacity_msat,
2875                         next_outbound_htlc_minimum_msat: 0,
2876                         inbound_capacity_msat: 42,
2877                         unspendable_punishment_reserve: None,
2878                         confirmations_required: None,
2879                         confirmations: None,
2880                         force_close_spend_delay: None,
2881                         is_outbound: true, is_channel_ready: true,
2882                         is_usable: true, is_public: true,
2883                         inbound_htlc_minimum_msat: None,
2884                         inbound_htlc_maximum_msat: None,
2885                         config: None,
2886                         feerate_sat_per_1000_weight: None,
2887                         channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
2888                 }
2889         }
2890
2891         #[test]
2892         fn simple_route_test() {
2893                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2894                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2895                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2896                 let scorer = ln_test_utils::TestScorer::new();
2897                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2898                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2899
2900                 // Simple route to 2 via 1
2901
2902                 let route_params = RouteParameters::from_payment_params_and_value(
2903                         payment_params.clone(), 0);
2904                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2905                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
2906                         &Default::default(), &random_seed_bytes) {
2907                                 assert_eq!(err, "Cannot send a payment of 0 msat");
2908                 } else { panic!(); }
2909
2910                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2911                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2912                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2913                 assert_eq!(route.paths[0].hops.len(), 2);
2914
2915                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2916                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2917                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2918                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2919                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2920                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2921
2922                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2923                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2924                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2925                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2926                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2927                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2928         }
2929
2930         #[test]
2931         fn invalid_first_hop_test() {
2932                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2933                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2934                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2935                 let scorer = ln_test_utils::TestScorer::new();
2936                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2937                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2938
2939                 // Simple route to 2 via 1
2940
2941                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2942
2943                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
2944                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
2945                         &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
2946                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
2947                                 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2948                 } else { panic!(); }
2949
2950                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
2951                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
2952                 assert_eq!(route.paths[0].hops.len(), 2);
2953         }
2954
2955         #[test]
2956         fn htlc_minimum_test() {
2957                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2958                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2959                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2960                 let scorer = ln_test_utils::TestScorer::new();
2961                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2962                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2963
2964                 // Simple route to 2 via 1
2965
2966                 // Disable other paths
2967                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2968                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2969                         short_channel_id: 12,
2970                         timestamp: 2,
2971                         flags: 2, // to disable
2972                         cltv_expiry_delta: 0,
2973                         htlc_minimum_msat: 0,
2974                         htlc_maximum_msat: MAX_VALUE_MSAT,
2975                         fee_base_msat: 0,
2976                         fee_proportional_millionths: 0,
2977                         excess_data: Vec::new()
2978                 });
2979                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2980                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2981                         short_channel_id: 3,
2982                         timestamp: 2,
2983                         flags: 2, // to disable
2984                         cltv_expiry_delta: 0,
2985                         htlc_minimum_msat: 0,
2986                         htlc_maximum_msat: MAX_VALUE_MSAT,
2987                         fee_base_msat: 0,
2988                         fee_proportional_millionths: 0,
2989                         excess_data: Vec::new()
2990                 });
2991                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2992                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2993                         short_channel_id: 13,
2994                         timestamp: 2,
2995                         flags: 2, // to disable
2996                         cltv_expiry_delta: 0,
2997                         htlc_minimum_msat: 0,
2998                         htlc_maximum_msat: MAX_VALUE_MSAT,
2999                         fee_base_msat: 0,
3000                         fee_proportional_millionths: 0,
3001                         excess_data: Vec::new()
3002                 });
3003                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3004                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3005                         short_channel_id: 6,
3006                         timestamp: 2,
3007                         flags: 2, // to disable
3008                         cltv_expiry_delta: 0,
3009                         htlc_minimum_msat: 0,
3010                         htlc_maximum_msat: MAX_VALUE_MSAT,
3011                         fee_base_msat: 0,
3012                         fee_proportional_millionths: 0,
3013                         excess_data: Vec::new()
3014                 });
3015                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3016                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3017                         short_channel_id: 7,
3018                         timestamp: 2,
3019                         flags: 2, // to disable
3020                         cltv_expiry_delta: 0,
3021                         htlc_minimum_msat: 0,
3022                         htlc_maximum_msat: MAX_VALUE_MSAT,
3023                         fee_base_msat: 0,
3024                         fee_proportional_millionths: 0,
3025                         excess_data: Vec::new()
3026                 });
3027
3028                 // Check against amount_to_transfer_over_msat.
3029                 // Set minimal HTLC of 200_000_000 msat.
3030                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3031                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3032                         short_channel_id: 2,
3033                         timestamp: 3,
3034                         flags: 0,
3035                         cltv_expiry_delta: 0,
3036                         htlc_minimum_msat: 200_000_000,
3037                         htlc_maximum_msat: MAX_VALUE_MSAT,
3038                         fee_base_msat: 0,
3039                         fee_proportional_millionths: 0,
3040                         excess_data: Vec::new()
3041                 });
3042
3043                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3044                 // be used.
3045                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3046                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3047                         short_channel_id: 4,
3048                         timestamp: 3,
3049                         flags: 0,
3050                         cltv_expiry_delta: 0,
3051                         htlc_minimum_msat: 0,
3052                         htlc_maximum_msat: 199_999_999,
3053                         fee_base_msat: 0,
3054                         fee_proportional_millionths: 0,
3055                         excess_data: Vec::new()
3056                 });
3057
3058                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3059                 let route_params = RouteParameters::from_payment_params_and_value(
3060                         payment_params, 199_999_999);
3061                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3062                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3063                         &Default::default(), &random_seed_bytes) {
3064                                 assert_eq!(err, "Failed to find a path to the given destination");
3065                 } else { panic!(); }
3066
3067                 // Lift the restriction on the first hop.
3068                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3069                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3070                         short_channel_id: 2,
3071                         timestamp: 4,
3072                         flags: 0,
3073                         cltv_expiry_delta: 0,
3074                         htlc_minimum_msat: 0,
3075                         htlc_maximum_msat: MAX_VALUE_MSAT,
3076                         fee_base_msat: 0,
3077                         fee_proportional_millionths: 0,
3078                         excess_data: Vec::new()
3079                 });
3080
3081                 // A payment above the minimum should pass
3082                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3083                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3084                 assert_eq!(route.paths[0].hops.len(), 2);
3085         }
3086
3087         #[test]
3088         fn htlc_minimum_overpay_test() {
3089                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3090                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3091                 let config = UserConfig::default();
3092                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3093                 let scorer = ln_test_utils::TestScorer::new();
3094                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3095                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3096
3097                 // A route to node#2 via two paths.
3098                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3099                 // Thus, they can't send 60 without overpaying.
3100                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3101                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3102                         short_channel_id: 2,
3103                         timestamp: 2,
3104                         flags: 0,
3105                         cltv_expiry_delta: 0,
3106                         htlc_minimum_msat: 35_000,
3107                         htlc_maximum_msat: 40_000,
3108                         fee_base_msat: 0,
3109                         fee_proportional_millionths: 0,
3110                         excess_data: Vec::new()
3111                 });
3112                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3113                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3114                         short_channel_id: 12,
3115                         timestamp: 3,
3116                         flags: 0,
3117                         cltv_expiry_delta: 0,
3118                         htlc_minimum_msat: 35_000,
3119                         htlc_maximum_msat: 40_000,
3120                         fee_base_msat: 0,
3121                         fee_proportional_millionths: 0,
3122                         excess_data: Vec::new()
3123                 });
3124
3125                 // Make 0 fee.
3126                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3127                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3128                         short_channel_id: 13,
3129                         timestamp: 2,
3130                         flags: 0,
3131                         cltv_expiry_delta: 0,
3132                         htlc_minimum_msat: 0,
3133                         htlc_maximum_msat: MAX_VALUE_MSAT,
3134                         fee_base_msat: 0,
3135                         fee_proportional_millionths: 0,
3136                         excess_data: Vec::new()
3137                 });
3138                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3139                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3140                         short_channel_id: 4,
3141                         timestamp: 2,
3142                         flags: 0,
3143                         cltv_expiry_delta: 0,
3144                         htlc_minimum_msat: 0,
3145                         htlc_maximum_msat: MAX_VALUE_MSAT,
3146                         fee_base_msat: 0,
3147                         fee_proportional_millionths: 0,
3148                         excess_data: Vec::new()
3149                 });
3150
3151                 // Disable other paths
3152                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3153                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3154                         short_channel_id: 1,
3155                         timestamp: 3,
3156                         flags: 2, // to disable
3157                         cltv_expiry_delta: 0,
3158                         htlc_minimum_msat: 0,
3159                         htlc_maximum_msat: MAX_VALUE_MSAT,
3160                         fee_base_msat: 0,
3161                         fee_proportional_millionths: 0,
3162                         excess_data: Vec::new()
3163                 });
3164
3165                 let mut route_params = RouteParameters::from_payment_params_and_value(
3166                         payment_params.clone(), 60_000);
3167                 route_params.max_total_routing_fee_msat = Some(15_000);
3168                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3169                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3170                 // Overpay fees to hit htlc_minimum_msat.
3171                 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3172                 // TODO: this could be better balanced to overpay 10k and not 15k.
3173                 assert_eq!(overpaid_fees, 15_000);
3174
3175                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3176                 // while taking even more fee to match htlc_minimum_msat.
3177                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3178                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3179                         short_channel_id: 12,
3180                         timestamp: 4,
3181                         flags: 0,
3182                         cltv_expiry_delta: 0,
3183                         htlc_minimum_msat: 65_000,
3184                         htlc_maximum_msat: 80_000,
3185                         fee_base_msat: 0,
3186                         fee_proportional_millionths: 0,
3187                         excess_data: Vec::new()
3188                 });
3189                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3190                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3191                         short_channel_id: 2,
3192                         timestamp: 3,
3193                         flags: 0,
3194                         cltv_expiry_delta: 0,
3195                         htlc_minimum_msat: 0,
3196                         htlc_maximum_msat: MAX_VALUE_MSAT,
3197                         fee_base_msat: 0,
3198                         fee_proportional_millionths: 0,
3199                         excess_data: Vec::new()
3200                 });
3201                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3202                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3203                         short_channel_id: 4,
3204                         timestamp: 4,
3205                         flags: 0,
3206                         cltv_expiry_delta: 0,
3207                         htlc_minimum_msat: 0,
3208                         htlc_maximum_msat: MAX_VALUE_MSAT,
3209                         fee_base_msat: 0,
3210                         fee_proportional_millionths: 100_000,
3211                         excess_data: Vec::new()
3212                 });
3213
3214                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3215                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3216                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3217                 assert_eq!(route.paths.len(), 1);
3218                 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3219                 let fees = route.paths[0].hops[0].fee_msat;
3220                 assert_eq!(fees, 5_000);
3221
3222                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3223                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3224                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3225                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3226                 // the other channel.
3227                 assert_eq!(route.paths.len(), 1);
3228                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3229                 let fees = route.paths[0].hops[0].fee_msat;
3230                 assert_eq!(fees, 5_000);
3231         }
3232
3233         #[test]
3234         fn htlc_minimum_recipient_overpay_test() {
3235                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3236                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3237                 let config = UserConfig::default();
3238                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3239                 let scorer = ln_test_utils::TestScorer::new();
3240                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3241                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3242
3243                 // Route to node2 over a single path which requires overpaying the recipient themselves.
3244
3245                 // First disable all paths except the us -> node1 -> node2 path
3246                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3247                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3248                         short_channel_id: 13,
3249                         timestamp: 2,
3250                         flags: 3,
3251                         cltv_expiry_delta: 0,
3252                         htlc_minimum_msat: 0,
3253                         htlc_maximum_msat: 0,
3254                         fee_base_msat: 0,
3255                         fee_proportional_millionths: 0,
3256                         excess_data: Vec::new()
3257                 });
3258
3259                 // Set channel 4 to free but with a high htlc_minimum_msat
3260                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3261                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3262                         short_channel_id: 4,
3263                         timestamp: 2,
3264                         flags: 0,
3265                         cltv_expiry_delta: 0,
3266                         htlc_minimum_msat: 15_000,
3267                         htlc_maximum_msat: MAX_VALUE_MSAT,
3268                         fee_base_msat: 0,
3269                         fee_proportional_millionths: 0,
3270                         excess_data: Vec::new()
3271                 });
3272
3273                 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3274                 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3275                 // what we try to find a route for, so this test only just happens to work out to exactly
3276                 // the fee limit.
3277                 let mut route_params = RouteParameters::from_payment_params_and_value(
3278                         payment_params.clone(), 5_000);
3279                 route_params.max_total_routing_fee_msat = Some(9_999);
3280                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3281                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3282                         &Default::default(), &random_seed_bytes) {
3283                                 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3284                 } else { panic!(); }
3285
3286                 let mut route_params = RouteParameters::from_payment_params_and_value(
3287                         payment_params.clone(), 5_000);
3288                 route_params.max_total_routing_fee_msat = Some(10_000);
3289                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3290                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3291                 assert_eq!(route.get_total_fees(), 10_000);
3292         }
3293
3294         #[test]
3295         fn disable_channels_test() {
3296                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3297                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3298                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3299                 let scorer = ln_test_utils::TestScorer::new();
3300                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3301                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3302
3303                 // // Disable channels 4 and 12 by flags=2
3304                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3305                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3306                         short_channel_id: 4,
3307                         timestamp: 2,
3308                         flags: 2, // to disable
3309                         cltv_expiry_delta: 0,
3310                         htlc_minimum_msat: 0,
3311                         htlc_maximum_msat: MAX_VALUE_MSAT,
3312                         fee_base_msat: 0,
3313                         fee_proportional_millionths: 0,
3314                         excess_data: Vec::new()
3315                 });
3316                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3317                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3318                         short_channel_id: 12,
3319                         timestamp: 2,
3320                         flags: 2, // to disable
3321                         cltv_expiry_delta: 0,
3322                         htlc_minimum_msat: 0,
3323                         htlc_maximum_msat: MAX_VALUE_MSAT,
3324                         fee_base_msat: 0,
3325                         fee_proportional_millionths: 0,
3326                         excess_data: Vec::new()
3327                 });
3328
3329                 // If all the channels require some features we don't understand, route should fail
3330                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3331                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3332                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3333                         &Default::default(), &random_seed_bytes) {
3334                                 assert_eq!(err, "Failed to find a path to the given destination");
3335                 } else { panic!(); }
3336
3337                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3338                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3339                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3340                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3341                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3342                         &Default::default(), &random_seed_bytes).unwrap();
3343                 assert_eq!(route.paths[0].hops.len(), 2);
3344
3345                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3346                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3347                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3348                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3349                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3350                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3351
3352                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3353                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3354                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3355                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3356                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3357                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3358         }
3359
3360         #[test]
3361         fn disable_node_test() {
3362                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3363                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3364                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3365                 let scorer = ln_test_utils::TestScorer::new();
3366                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3367                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3368
3369                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3370                 let mut unknown_features = NodeFeatures::empty();
3371                 unknown_features.set_unknown_feature_required();
3372                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3373                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3374                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3375
3376                 // If all nodes require some features we don't understand, route should fail
3377                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3378                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3379                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3380                         &Default::default(), &random_seed_bytes) {
3381                                 assert_eq!(err, "Failed to find a path to the given destination");
3382                 } else { panic!(); }
3383
3384                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3385                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3386                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3387                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3388                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3389                         &Default::default(), &random_seed_bytes).unwrap();
3390                 assert_eq!(route.paths[0].hops.len(), 2);
3391
3392                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3393                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3394                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3395                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3396                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3397                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3398
3399                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3400                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3401                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3402                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3403                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3404                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3405
3406                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3407                 // naively) assume that the user checked the feature bits on the invoice, which override
3408                 // the node_announcement.
3409         }
3410
3411         #[test]
3412         fn our_chans_test() {
3413                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3414                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3415                 let scorer = ln_test_utils::TestScorer::new();
3416                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3417                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3418
3419                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3420                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3421                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3422                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3423                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3424                 assert_eq!(route.paths[0].hops.len(), 3);
3425
3426                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3427                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3428                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3429                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3430                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3431                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3432
3433                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3434                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3435                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3436                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3437                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3438                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3439
3440                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3441                 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3442                 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3443                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3444                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3445                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3446
3447                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3448                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3449                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3450                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3451                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3452                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3453                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3454                         &Default::default(), &random_seed_bytes).unwrap();
3455                 assert_eq!(route.paths[0].hops.len(), 2);
3456
3457                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3458                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3459                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3460                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3461                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3462                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3463
3464                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3465                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3466                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3467                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3468                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3469                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3470         }
3471
3472         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3473                 let zero_fees = RoutingFees {
3474                         base_msat: 0,
3475                         proportional_millionths: 0,
3476                 };
3477                 vec![RouteHint(vec![RouteHintHop {
3478                         src_node_id: nodes[3],
3479                         short_channel_id: 8,
3480                         fees: zero_fees,
3481                         cltv_expiry_delta: (8 << 4) | 1,
3482                         htlc_minimum_msat: None,
3483                         htlc_maximum_msat: None,
3484                 }
3485                 ]), RouteHint(vec![RouteHintHop {
3486                         src_node_id: nodes[4],
3487                         short_channel_id: 9,
3488                         fees: RoutingFees {
3489                                 base_msat: 1001,
3490                                 proportional_millionths: 0,
3491                         },
3492                         cltv_expiry_delta: (9 << 4) | 1,
3493                         htlc_minimum_msat: None,
3494                         htlc_maximum_msat: None,
3495                 }]), RouteHint(vec![RouteHintHop {
3496                         src_node_id: nodes[5],
3497                         short_channel_id: 10,
3498                         fees: zero_fees,
3499                         cltv_expiry_delta: (10 << 4) | 1,
3500                         htlc_minimum_msat: None,
3501                         htlc_maximum_msat: None,
3502                 }])]
3503         }
3504
3505         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3506                 let zero_fees = RoutingFees {
3507                         base_msat: 0,
3508                         proportional_millionths: 0,
3509                 };
3510                 vec![RouteHint(vec![RouteHintHop {
3511                         src_node_id: nodes[2],
3512                         short_channel_id: 5,
3513                         fees: RoutingFees {
3514                                 base_msat: 100,
3515                                 proportional_millionths: 0,
3516                         },
3517                         cltv_expiry_delta: (5 << 4) | 1,
3518                         htlc_minimum_msat: None,
3519                         htlc_maximum_msat: None,
3520                 }, RouteHintHop {
3521                         src_node_id: nodes[3],
3522                         short_channel_id: 8,
3523                         fees: zero_fees,
3524                         cltv_expiry_delta: (8 << 4) | 1,
3525                         htlc_minimum_msat: None,
3526                         htlc_maximum_msat: None,
3527                 }
3528                 ]), RouteHint(vec![RouteHintHop {
3529                         src_node_id: nodes[4],
3530                         short_channel_id: 9,
3531                         fees: RoutingFees {
3532                                 base_msat: 1001,
3533                                 proportional_millionths: 0,
3534                         },
3535                         cltv_expiry_delta: (9 << 4) | 1,
3536                         htlc_minimum_msat: None,
3537                         htlc_maximum_msat: None,
3538                 }]), RouteHint(vec![RouteHintHop {
3539                         src_node_id: nodes[5],
3540                         short_channel_id: 10,
3541                         fees: zero_fees,
3542                         cltv_expiry_delta: (10 << 4) | 1,
3543                         htlc_minimum_msat: None,
3544                         htlc_maximum_msat: None,
3545                 }])]
3546         }
3547
3548         #[test]
3549         fn partial_route_hint_test() {
3550                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3551                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3552                 let scorer = ln_test_utils::TestScorer::new();
3553                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3554                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3555
3556                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3557                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3558                 // RouteHint may be partially used by the algo to build the best path.
3559
3560                 // First check that last hop can't have its source as the payee.
3561                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3562                         src_node_id: nodes[6],
3563                         short_channel_id: 8,
3564                         fees: RoutingFees {
3565                                 base_msat: 1000,
3566                                 proportional_millionths: 0,
3567                         },
3568                         cltv_expiry_delta: (8 << 4) | 1,
3569                         htlc_minimum_msat: None,
3570                         htlc_maximum_msat: None,
3571                 }]);
3572
3573                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3574                 invalid_last_hops.push(invalid_last_hop);
3575                 {
3576                         let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3577                                 .with_route_hints(invalid_last_hops).unwrap();
3578                         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3579                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3580                                 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3581                                 &Default::default(), &random_seed_bytes) {
3582                                         assert_eq!(err, "Route hint cannot have the payee as the source.");
3583                         } else { panic!(); }
3584                 }
3585
3586                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3587                         .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3588                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3589                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3590                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3591                 assert_eq!(route.paths[0].hops.len(), 5);
3592
3593                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3594                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3595                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3596                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3597                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3598                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3599
3600                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3601                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3602                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3603                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3604                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3605                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3606
3607                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3608                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3609                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3610                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3611                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3612                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3613
3614                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3615                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3616                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3617                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3618                 // If we have a peer in the node map, we'll use their features here since we don't have
3619                 // a way of figuring out their features from the invoice:
3620                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3621                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3622
3623                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3624                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3625                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3626                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3627                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3628                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3629         }
3630
3631         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3632                 let zero_fees = RoutingFees {
3633                         base_msat: 0,
3634                         proportional_millionths: 0,
3635                 };
3636                 vec![RouteHint(vec![RouteHintHop {
3637                         src_node_id: nodes[3],
3638                         short_channel_id: 8,
3639                         fees: zero_fees,
3640                         cltv_expiry_delta: (8 << 4) | 1,
3641                         htlc_minimum_msat: None,
3642                         htlc_maximum_msat: None,
3643                 }]), RouteHint(vec![
3644
3645                 ]), RouteHint(vec![RouteHintHop {
3646                         src_node_id: nodes[5],
3647                         short_channel_id: 10,
3648                         fees: zero_fees,
3649                         cltv_expiry_delta: (10 << 4) | 1,
3650                         htlc_minimum_msat: None,
3651                         htlc_maximum_msat: None,
3652                 }])]
3653         }
3654
3655         #[test]
3656         fn ignores_empty_last_hops_test() {
3657                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3658                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3659                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3660                 let scorer = ln_test_utils::TestScorer::new();
3661                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3662                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3663
3664                 // Test handling of an empty RouteHint passed in Invoice.
3665                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3666                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3667                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3668                 assert_eq!(route.paths[0].hops.len(), 5);
3669
3670                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3671                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3672                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3673                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3674                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3675                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3676
3677                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3678                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3679                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3680                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3681                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3682                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3683
3684                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3685                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3686                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3687                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3688                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3689                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3690
3691                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3692                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3693                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3694                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3695                 // If we have a peer in the node map, we'll use their features here since we don't have
3696                 // a way of figuring out their features from the invoice:
3697                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3698                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3699
3700                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3701                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3702                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3703                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3704                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3705                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3706         }
3707
3708         /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3709         /// and 0xff01.
3710         fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3711                 let zero_fees = RoutingFees {
3712                         base_msat: 0,
3713                         proportional_millionths: 0,
3714                 };
3715                 vec![RouteHint(vec![RouteHintHop {
3716                         src_node_id: hint_hops[0],
3717                         short_channel_id: 0xff00,
3718                         fees: RoutingFees {
3719                                 base_msat: 100,
3720                                 proportional_millionths: 0,
3721                         },
3722                         cltv_expiry_delta: (5 << 4) | 1,
3723                         htlc_minimum_msat: None,
3724                         htlc_maximum_msat: None,
3725                 }, RouteHintHop {
3726                         src_node_id: hint_hops[1],
3727                         short_channel_id: 0xff01,
3728                         fees: zero_fees,
3729                         cltv_expiry_delta: (8 << 4) | 1,
3730                         htlc_minimum_msat: None,
3731                         htlc_maximum_msat: None,
3732                 }])]
3733         }
3734
3735         #[test]
3736         fn multi_hint_last_hops_test() {
3737                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3738                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3739                 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3740                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3741                 let scorer = ln_test_utils::TestScorer::new();
3742                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3743                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3744                 // Test through channels 2, 3, 0xff00, 0xff01.
3745                 // Test shows that multiple hop hints are considered.
3746
3747                 // Disabling channels 6 & 7 by flags=2
3748                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3749                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3750                         short_channel_id: 6,
3751                         timestamp: 2,
3752                         flags: 2, // to disable
3753                         cltv_expiry_delta: 0,
3754                         htlc_minimum_msat: 0,
3755                         htlc_maximum_msat: MAX_VALUE_MSAT,
3756                         fee_base_msat: 0,
3757                         fee_proportional_millionths: 0,
3758                         excess_data: Vec::new()
3759                 });
3760                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3761                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3762                         short_channel_id: 7,
3763                         timestamp: 2,
3764                         flags: 2, // to disable
3765                         cltv_expiry_delta: 0,
3766                         htlc_minimum_msat: 0,
3767                         htlc_maximum_msat: MAX_VALUE_MSAT,
3768                         fee_base_msat: 0,
3769                         fee_proportional_millionths: 0,
3770                         excess_data: Vec::new()
3771                 });
3772
3773                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3774                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3775                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3776                 assert_eq!(route.paths[0].hops.len(), 4);
3777
3778                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3779                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3780                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3781                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3782                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3783                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3784
3785                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3786                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3787                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3788                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3789                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3790                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3791
3792                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3793                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3794                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3795                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3796                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3797                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3798
3799                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3800                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3801                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3802                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3803                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3804                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3805         }
3806
3807         #[test]
3808         fn private_multi_hint_last_hops_test() {
3809                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3810                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3811
3812                 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3813                 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3814
3815                 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3816                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3817                 let scorer = ln_test_utils::TestScorer::new();
3818                 // Test through channels 2, 3, 0xff00, 0xff01.
3819                 // Test shows that multiple hop hints are considered.
3820
3821                 // Disabling channels 6 & 7 by flags=2
3822                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3823                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3824                         short_channel_id: 6,
3825                         timestamp: 2,
3826                         flags: 2, // to disable
3827                         cltv_expiry_delta: 0,
3828                         htlc_minimum_msat: 0,
3829                         htlc_maximum_msat: MAX_VALUE_MSAT,
3830                         fee_base_msat: 0,
3831                         fee_proportional_millionths: 0,
3832                         excess_data: Vec::new()
3833                 });
3834                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3835                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3836                         short_channel_id: 7,
3837                         timestamp: 2,
3838                         flags: 2, // to disable
3839                         cltv_expiry_delta: 0,
3840                         htlc_minimum_msat: 0,
3841                         htlc_maximum_msat: MAX_VALUE_MSAT,
3842                         fee_base_msat: 0,
3843                         fee_proportional_millionths: 0,
3844                         excess_data: Vec::new()
3845                 });
3846
3847                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3848                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3849                         Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
3850                 assert_eq!(route.paths[0].hops.len(), 4);
3851
3852                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3853                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3854                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3855                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3856                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3857                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3858
3859                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3860                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3861                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3862                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3863                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3864                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3865
3866                 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3867                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3868                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3869                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3870                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3871                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3872
3873                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3874                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3875                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3876                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3877                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3878                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3879         }
3880
3881         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3882                 let zero_fees = RoutingFees {
3883                         base_msat: 0,
3884                         proportional_millionths: 0,
3885                 };
3886                 vec![RouteHint(vec![RouteHintHop {
3887                         src_node_id: nodes[4],
3888                         short_channel_id: 11,
3889                         fees: zero_fees,
3890                         cltv_expiry_delta: (11 << 4) | 1,
3891                         htlc_minimum_msat: None,
3892                         htlc_maximum_msat: None,
3893                 }, RouteHintHop {
3894                         src_node_id: nodes[3],
3895                         short_channel_id: 8,
3896                         fees: zero_fees,
3897                         cltv_expiry_delta: (8 << 4) | 1,
3898                         htlc_minimum_msat: None,
3899                         htlc_maximum_msat: None,
3900                 }]), RouteHint(vec![RouteHintHop {
3901                         src_node_id: nodes[4],
3902                         short_channel_id: 9,
3903                         fees: RoutingFees {
3904                                 base_msat: 1001,
3905                                 proportional_millionths: 0,
3906                         },
3907                         cltv_expiry_delta: (9 << 4) | 1,
3908                         htlc_minimum_msat: None,
3909                         htlc_maximum_msat: None,
3910                 }]), RouteHint(vec![RouteHintHop {
3911                         src_node_id: nodes[5],
3912                         short_channel_id: 10,
3913                         fees: zero_fees,
3914                         cltv_expiry_delta: (10 << 4) | 1,
3915                         htlc_minimum_msat: None,
3916                         htlc_maximum_msat: None,
3917                 }])]
3918         }
3919
3920         #[test]
3921         fn last_hops_with_public_channel_test() {
3922                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3923                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3924                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3925                 let scorer = ln_test_utils::TestScorer::new();
3926                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3927                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3928                 // This test shows that public routes can be present in the invoice
3929                 // which would be handled in the same manner.
3930
3931                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3932                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3933                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3934                 assert_eq!(route.paths[0].hops.len(), 5);
3935
3936                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3937                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3938                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3939                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3940                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3941                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3942
3943                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3944                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3945                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3946                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3947                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3948                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3949
3950                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3951                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3952                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3953                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3954                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3955                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3956
3957                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3958                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3959                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3960                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3961                 // If we have a peer in the node map, we'll use their features here since we don't have
3962                 // a way of figuring out their features from the invoice:
3963                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3964                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3965
3966                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3967                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3968                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3969                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3970                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3971                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3972         }
3973
3974         #[test]
3975         fn our_chans_last_hop_connect_test() {
3976                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3977                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3978                 let scorer = ln_test_utils::TestScorer::new();
3979                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3980                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3981
3982                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3983                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3984                 let mut last_hops = last_hops(&nodes);
3985                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3986                         .with_route_hints(last_hops.clone()).unwrap();
3987                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3988                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3989                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3990                         &Default::default(), &random_seed_bytes).unwrap();
3991                 assert_eq!(route.paths[0].hops.len(), 2);
3992
3993                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3994                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3995                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3996                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3997                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3998                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3999
4000                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4001                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4002                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4003                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4004                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4005                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4006
4007                 last_hops[0].0[0].fees.base_msat = 1000;
4008
4009                 // Revert to via 6 as the fee on 8 goes up
4010                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4011                         .with_route_hints(last_hops).unwrap();
4012                 let route_params = RouteParameters::from_payment_params_and_value(
4013                         payment_params.clone(), 100);
4014                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4015                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4016                 assert_eq!(route.paths[0].hops.len(), 4);
4017
4018                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4019                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4020                 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4021                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4022                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4023                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4024
4025                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4026                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4027                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4028                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4029                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4030                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4031
4032                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4033                 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4034                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4035                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4036                 // If we have a peer in the node map, we'll use their features here since we don't have
4037                 // a way of figuring out their features from the invoice:
4038                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4039                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4040
4041                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4042                 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4043                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4044                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4045                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4046                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4047
4048                 // ...but still use 8 for larger payments as 6 has a variable feerate
4049                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4050                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4051                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4052                 assert_eq!(route.paths[0].hops.len(), 5);
4053
4054                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4055                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4056                 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4057                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4058                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4059                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4060
4061                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4062                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4063                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4064                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4065                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4066                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4067
4068                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4069                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4070                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4071                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4072                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4073                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4074
4075                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4076                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4077                 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4078                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4079                 // If we have a peer in the node map, we'll use their features here since we don't have
4080                 // a way of figuring out their features from the invoice:
4081                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4082                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4083
4084                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4085                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4086                 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4087                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4088                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4089                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4090         }
4091
4092         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> {
4093                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4094                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4095                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4096
4097                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4098                 let last_hops = RouteHint(vec![RouteHintHop {
4099                         src_node_id: middle_node_id,
4100                         short_channel_id: 8,
4101                         fees: RoutingFees {
4102                                 base_msat: 1000,
4103                                 proportional_millionths: last_hop_fee_prop,
4104                         },
4105                         cltv_expiry_delta: (8 << 4) | 1,
4106                         htlc_minimum_msat: None,
4107                         htlc_maximum_msat: last_hop_htlc_max,
4108                 }]);
4109                 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4110                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4111                 let scorer = ln_test_utils::TestScorer::new();
4112                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4113                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4114                 let logger = ln_test_utils::TestLogger::new();
4115                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4116                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4117                 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4118                                 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4119                                 &random_seed_bytes);
4120                 route
4121         }
4122
4123         #[test]
4124         fn unannounced_path_test() {
4125                 // We should be able to send a payment to a destination without any help of a routing graph
4126                 // if we have a channel with a common counterparty that appears in the first and last hop
4127                 // hints.
4128                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4129
4130                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4131                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4132                 assert_eq!(route.paths[0].hops.len(), 2);
4133
4134                 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4135                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4136                 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4137                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4138                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4139                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4140
4141                 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4142                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4143                 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4144                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4145                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4146                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4147         }
4148
4149         #[test]
4150         fn overflow_unannounced_path_test_liquidity_underflow() {
4151                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4152                 // the last-hop had a fee which overflowed a u64, we'd panic.
4153                 // This was due to us adding the first-hop from us unconditionally, causing us to think
4154                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4155                 // In this test, we previously hit a subtraction underflow due to having less available
4156                 // liquidity at the last hop than 0.
4157                 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());
4158         }
4159
4160         #[test]
4161         fn overflow_unannounced_path_test_feerate_overflow() {
4162                 // This tests for the same case as above, except instead of hitting a subtraction
4163                 // underflow, we hit a case where the fee charged at a hop overflowed.
4164                 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());
4165         }
4166
4167         #[test]
4168         fn available_amount_while_routing_test() {
4169                 // Tests whether we choose the correct available channel amount while routing.
4170
4171                 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4172                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4173                 let scorer = ln_test_utils::TestScorer::new();
4174                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4175                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4176                 let config = UserConfig::default();
4177                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4178
4179                 // We will use a simple single-path route from
4180                 // our node to node2 via node0: channels {1, 3}.
4181
4182                 // First disable all other paths.
4183                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4184                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4185                         short_channel_id: 2,
4186                         timestamp: 2,
4187                         flags: 2,
4188                         cltv_expiry_delta: 0,
4189                         htlc_minimum_msat: 0,
4190                         htlc_maximum_msat: 100_000,
4191                         fee_base_msat: 0,
4192                         fee_proportional_millionths: 0,
4193                         excess_data: Vec::new()
4194                 });
4195                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4196                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4197                         short_channel_id: 12,
4198                         timestamp: 2,
4199                         flags: 2,
4200                         cltv_expiry_delta: 0,
4201                         htlc_minimum_msat: 0,
4202                         htlc_maximum_msat: 100_000,
4203                         fee_base_msat: 0,
4204                         fee_proportional_millionths: 0,
4205                         excess_data: Vec::new()
4206                 });
4207
4208                 // Make the first channel (#1) very permissive,
4209                 // and we will be testing all limits on the second channel.
4210                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4211                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4212                         short_channel_id: 1,
4213                         timestamp: 2,
4214                         flags: 0,
4215                         cltv_expiry_delta: 0,
4216                         htlc_minimum_msat: 0,
4217                         htlc_maximum_msat: 1_000_000_000,
4218                         fee_base_msat: 0,
4219                         fee_proportional_millionths: 0,
4220                         excess_data: Vec::new()
4221                 });
4222
4223                 // First, let's see if routing works if we have absolutely no idea about the available amount.
4224                 // In this case, it should be set to 250_000 sats.
4225                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4226                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4227                         short_channel_id: 3,
4228                         timestamp: 2,
4229                         flags: 0,
4230                         cltv_expiry_delta: 0,
4231                         htlc_minimum_msat: 0,
4232                         htlc_maximum_msat: 250_000_000,
4233                         fee_base_msat: 0,
4234                         fee_proportional_millionths: 0,
4235                         excess_data: Vec::new()
4236                 });
4237
4238                 {
4239                         // Attempt to route more than available results in a failure.
4240                         let route_params = RouteParameters::from_payment_params_and_value(
4241                                 payment_params.clone(), 250_000_001);
4242                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4243                                         &our_id, &route_params, &network_graph.read_only(), None,
4244                                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4245                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4246                         } else { panic!(); }
4247                 }
4248
4249                 {
4250                         // Now, attempt to route an exact amount we have should be fine.
4251                         let route_params = RouteParameters::from_payment_params_and_value(
4252                                 payment_params.clone(), 250_000_000);
4253                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4254                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4255                         assert_eq!(route.paths.len(), 1);
4256                         let path = route.paths.last().unwrap();
4257                         assert_eq!(path.hops.len(), 2);
4258                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4259                         assert_eq!(path.final_value_msat(), 250_000_000);
4260                 }
4261
4262                 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4263                 // Disable channel #1 and use another first hop.
4264                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4265                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4266                         short_channel_id: 1,
4267                         timestamp: 3,
4268                         flags: 2,
4269                         cltv_expiry_delta: 0,
4270                         htlc_minimum_msat: 0,
4271                         htlc_maximum_msat: 1_000_000_000,
4272                         fee_base_msat: 0,
4273                         fee_proportional_millionths: 0,
4274                         excess_data: Vec::new()
4275                 });
4276
4277                 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4278                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4279
4280                 {
4281                         // Attempt to route more than available results in a failure.
4282                         let route_params = RouteParameters::from_payment_params_and_value(
4283                                 payment_params.clone(), 200_000_001);
4284                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4285                                         &our_id, &route_params, &network_graph.read_only(),
4286                                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4287                                         &Default::default(), &random_seed_bytes) {
4288                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4289                         } else { panic!(); }
4290                 }
4291
4292                 {
4293                         // Now, attempt to route an exact amount we have should be fine.
4294                         let route_params = RouteParameters::from_payment_params_and_value(
4295                                 payment_params.clone(), 200_000_000);
4296                         let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4297                                 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4298                                 &Default::default(), &random_seed_bytes).unwrap();
4299                         assert_eq!(route.paths.len(), 1);
4300                         let path = route.paths.last().unwrap();
4301                         assert_eq!(path.hops.len(), 2);
4302                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4303                         assert_eq!(path.final_value_msat(), 200_000_000);
4304                 }
4305
4306                 // Enable channel #1 back.
4307                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4308                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4309                         short_channel_id: 1,
4310                         timestamp: 4,
4311                         flags: 0,
4312                         cltv_expiry_delta: 0,
4313                         htlc_minimum_msat: 0,
4314                         htlc_maximum_msat: 1_000_000_000,
4315                         fee_base_msat: 0,
4316                         fee_proportional_millionths: 0,
4317                         excess_data: Vec::new()
4318                 });
4319
4320
4321                 // Now let's see if routing works if we know only htlc_maximum_msat.
4322                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4323                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4324                         short_channel_id: 3,
4325                         timestamp: 3,
4326                         flags: 0,
4327                         cltv_expiry_delta: 0,
4328                         htlc_minimum_msat: 0,
4329                         htlc_maximum_msat: 15_000,
4330                         fee_base_msat: 0,
4331                         fee_proportional_millionths: 0,
4332                         excess_data: Vec::new()
4333                 });
4334
4335                 {
4336                         // Attempt to route more than available results in a failure.
4337                         let route_params = RouteParameters::from_payment_params_and_value(
4338                                 payment_params.clone(), 15_001);
4339                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4340                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4341                                         &scorer, &Default::default(), &random_seed_bytes) {
4342                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4343                         } else { panic!(); }
4344                 }
4345
4346                 {
4347                         // Now, attempt to route an exact amount we have should be fine.
4348                         let route_params = RouteParameters::from_payment_params_and_value(
4349                                 payment_params.clone(), 15_000);
4350                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4351                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4352                         assert_eq!(route.paths.len(), 1);
4353                         let path = route.paths.last().unwrap();
4354                         assert_eq!(path.hops.len(), 2);
4355                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4356                         assert_eq!(path.final_value_msat(), 15_000);
4357                 }
4358
4359                 // Now let's see if routing works if we know only capacity from the UTXO.
4360
4361                 // We can't change UTXO capacity on the fly, so we'll disable
4362                 // the existing channel and add another one with the capacity we need.
4363                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4364                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4365                         short_channel_id: 3,
4366                         timestamp: 4,
4367                         flags: 2,
4368                         cltv_expiry_delta: 0,
4369                         htlc_minimum_msat: 0,
4370                         htlc_maximum_msat: MAX_VALUE_MSAT,
4371                         fee_base_msat: 0,
4372                         fee_proportional_millionths: 0,
4373                         excess_data: Vec::new()
4374                 });
4375
4376                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4377                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4378                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4379                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4380                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4381
4382                 *chain_monitor.utxo_ret.lock().unwrap() =
4383                         UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4384                 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4385
4386                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4387                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4388                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4389                         short_channel_id: 333,
4390                         timestamp: 1,
4391                         flags: 0,
4392                         cltv_expiry_delta: (3 << 4) | 1,
4393                         htlc_minimum_msat: 0,
4394                         htlc_maximum_msat: 15_000,
4395                         fee_base_msat: 0,
4396                         fee_proportional_millionths: 0,
4397                         excess_data: Vec::new()
4398                 });
4399                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4400                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4401                         short_channel_id: 333,
4402                         timestamp: 1,
4403                         flags: 1,
4404                         cltv_expiry_delta: (3 << 4) | 2,
4405                         htlc_minimum_msat: 0,
4406                         htlc_maximum_msat: 15_000,
4407                         fee_base_msat: 100,
4408                         fee_proportional_millionths: 0,
4409                         excess_data: Vec::new()
4410                 });
4411
4412                 {
4413                         // Attempt to route more than available results in a failure.
4414                         let route_params = RouteParameters::from_payment_params_and_value(
4415                                 payment_params.clone(), 15_001);
4416                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4417                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4418                                         &scorer, &Default::default(), &random_seed_bytes) {
4419                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4420                         } else { panic!(); }
4421                 }
4422
4423                 {
4424                         // Now, attempt to route an exact amount we have should be fine.
4425                         let route_params = RouteParameters::from_payment_params_and_value(
4426                                 payment_params.clone(), 15_000);
4427                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4428                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4429                         assert_eq!(route.paths.len(), 1);
4430                         let path = route.paths.last().unwrap();
4431                         assert_eq!(path.hops.len(), 2);
4432                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4433                         assert_eq!(path.final_value_msat(), 15_000);
4434                 }
4435
4436                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4437                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4438                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4439                         short_channel_id: 333,
4440                         timestamp: 6,
4441                         flags: 0,
4442                         cltv_expiry_delta: 0,
4443                         htlc_minimum_msat: 0,
4444                         htlc_maximum_msat: 10_000,
4445                         fee_base_msat: 0,
4446                         fee_proportional_millionths: 0,
4447                         excess_data: Vec::new()
4448                 });
4449
4450                 {
4451                         // Attempt to route more than available results in a failure.
4452                         let route_params = RouteParameters::from_payment_params_and_value(
4453                                 payment_params.clone(), 10_001);
4454                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4455                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4456                                         &scorer, &Default::default(), &random_seed_bytes) {
4457                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4458                         } else { panic!(); }
4459                 }
4460
4461                 {
4462                         // Now, attempt to route an exact amount we have should be fine.
4463                         let route_params = RouteParameters::from_payment_params_and_value(
4464                                 payment_params.clone(), 10_000);
4465                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4466                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4467                         assert_eq!(route.paths.len(), 1);
4468                         let path = route.paths.last().unwrap();
4469                         assert_eq!(path.hops.len(), 2);
4470                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4471                         assert_eq!(path.final_value_msat(), 10_000);
4472                 }
4473         }
4474
4475         #[test]
4476         fn available_liquidity_last_hop_test() {
4477                 // Check that available liquidity properly limits the path even when only
4478                 // one of the latter hops is limited.
4479                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4480                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4481                 let scorer = ln_test_utils::TestScorer::new();
4482                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4483                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4484                 let config = UserConfig::default();
4485                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4486
4487                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4488                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4489                 // Total capacity: 50 sats.
4490
4491                 // Disable other potential paths.
4492                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4493                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4494                         short_channel_id: 2,
4495                         timestamp: 2,
4496                         flags: 2,
4497                         cltv_expiry_delta: 0,
4498                         htlc_minimum_msat: 0,
4499                         htlc_maximum_msat: 100_000,
4500                         fee_base_msat: 0,
4501                         fee_proportional_millionths: 0,
4502                         excess_data: Vec::new()
4503                 });
4504                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4505                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4506                         short_channel_id: 7,
4507                         timestamp: 2,
4508                         flags: 2,
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
4517                 // Limit capacities
4518
4519                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4520                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4521                         short_channel_id: 12,
4522                         timestamp: 2,
4523                         flags: 0,
4524                         cltv_expiry_delta: 0,
4525                         htlc_minimum_msat: 0,
4526                         htlc_maximum_msat: 100_000,
4527                         fee_base_msat: 0,
4528                         fee_proportional_millionths: 0,
4529                         excess_data: Vec::new()
4530                 });
4531                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4532                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4533                         short_channel_id: 13,
4534                         timestamp: 2,
4535                         flags: 0,
4536                         cltv_expiry_delta: 0,
4537                         htlc_minimum_msat: 0,
4538                         htlc_maximum_msat: 100_000,
4539                         fee_base_msat: 0,
4540                         fee_proportional_millionths: 0,
4541                         excess_data: Vec::new()
4542                 });
4543
4544                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4545                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4546                         short_channel_id: 6,
4547                         timestamp: 2,
4548                         flags: 0,
4549                         cltv_expiry_delta: 0,
4550                         htlc_minimum_msat: 0,
4551                         htlc_maximum_msat: 50_000,
4552                         fee_base_msat: 0,
4553                         fee_proportional_millionths: 0,
4554                         excess_data: Vec::new()
4555                 });
4556                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4557                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4558                         short_channel_id: 11,
4559                         timestamp: 2,
4560                         flags: 0,
4561                         cltv_expiry_delta: 0,
4562                         htlc_minimum_msat: 0,
4563                         htlc_maximum_msat: 100_000,
4564                         fee_base_msat: 0,
4565                         fee_proportional_millionths: 0,
4566                         excess_data: Vec::new()
4567                 });
4568                 {
4569                         // Attempt to route more than available results in a failure.
4570                         let route_params = RouteParameters::from_payment_params_and_value(
4571                                 payment_params.clone(), 60_000);
4572                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4573                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4574                                         &scorer, &Default::default(), &random_seed_bytes) {
4575                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4576                         } else { panic!(); }
4577                 }
4578
4579                 {
4580                         // Now, attempt to route 49 sats (just a bit below the capacity).
4581                         let route_params = RouteParameters::from_payment_params_and_value(
4582                                 payment_params.clone(), 49_000);
4583                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4584                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4585                         assert_eq!(route.paths.len(), 1);
4586                         let mut total_amount_paid_msat = 0;
4587                         for path in &route.paths {
4588                                 assert_eq!(path.hops.len(), 4);
4589                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4590                                 total_amount_paid_msat += path.final_value_msat();
4591                         }
4592                         assert_eq!(total_amount_paid_msat, 49_000);
4593                 }
4594
4595                 {
4596                         // Attempt to route an exact amount is also fine
4597                         let route_params = RouteParameters::from_payment_params_and_value(
4598                                 payment_params, 50_000);
4599                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4600                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4601                         assert_eq!(route.paths.len(), 1);
4602                         let mut total_amount_paid_msat = 0;
4603                         for path in &route.paths {
4604                                 assert_eq!(path.hops.len(), 4);
4605                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4606                                 total_amount_paid_msat += path.final_value_msat();
4607                         }
4608                         assert_eq!(total_amount_paid_msat, 50_000);
4609                 }
4610         }
4611
4612         #[test]
4613         fn ignore_fee_first_hop_test() {
4614                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4615                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4616                 let scorer = ln_test_utils::TestScorer::new();
4617                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4618                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4619                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4620
4621                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4622                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4623                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4624                         short_channel_id: 1,
4625                         timestamp: 2,
4626                         flags: 0,
4627                         cltv_expiry_delta: 0,
4628                         htlc_minimum_msat: 0,
4629                         htlc_maximum_msat: 100_000,
4630                         fee_base_msat: 1_000_000,
4631                         fee_proportional_millionths: 0,
4632                         excess_data: Vec::new()
4633                 });
4634                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4635                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4636                         short_channel_id: 3,
4637                         timestamp: 2,
4638                         flags: 0,
4639                         cltv_expiry_delta: 0,
4640                         htlc_minimum_msat: 0,
4641                         htlc_maximum_msat: 50_000,
4642                         fee_base_msat: 0,
4643                         fee_proportional_millionths: 0,
4644                         excess_data: Vec::new()
4645                 });
4646
4647                 {
4648                         let route_params = RouteParameters::from_payment_params_and_value(
4649                                 payment_params, 50_000);
4650                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4651                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4652                         assert_eq!(route.paths.len(), 1);
4653                         let mut total_amount_paid_msat = 0;
4654                         for path in &route.paths {
4655                                 assert_eq!(path.hops.len(), 2);
4656                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4657                                 total_amount_paid_msat += path.final_value_msat();
4658                         }
4659                         assert_eq!(total_amount_paid_msat, 50_000);
4660                 }
4661         }
4662
4663         #[test]
4664         fn simple_mpp_route_test() {
4665                 let (secp_ctx, _, _, _, _) = build_graph();
4666                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
4667                 let config = UserConfig::default();
4668                 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4669                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4670                 do_simple_mpp_route_test(clear_payment_params);
4671
4672                 // MPP to a 1-hop blinded path for nodes[2]
4673                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
4674                 let blinded_path = BlindedPath {
4675                         introduction_node_id: nodes[2],
4676                         blinding_point: ln_test_utils::pubkey(42),
4677                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
4678                 };
4679                 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
4680                         fee_base_msat: 0,
4681                         fee_proportional_millionths: 0,
4682                         htlc_minimum_msat: 0,
4683                         htlc_maximum_msat: 0,
4684                         cltv_expiry_delta: 0,
4685                         features: BlindedHopFeatures::empty(),
4686                 };
4687                 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
4688                         .with_bolt12_features(bolt12_features.clone()).unwrap();
4689                 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
4690
4691                 // MPP to 3 2-hop blinded paths
4692                 let mut blinded_path_node_0 = blinded_path.clone();
4693                 blinded_path_node_0.introduction_node_id = nodes[0];
4694                 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
4695                 let mut node_0_payinfo = blinded_payinfo.clone();
4696                 node_0_payinfo.htlc_maximum_msat = 50_000;
4697
4698                 let mut blinded_path_node_7 = blinded_path_node_0.clone();
4699                 blinded_path_node_7.introduction_node_id = nodes[7];
4700                 let mut node_7_payinfo = blinded_payinfo.clone();
4701                 node_7_payinfo.htlc_maximum_msat = 60_000;
4702
4703                 let mut blinded_path_node_1 = blinded_path_node_0.clone();
4704                 blinded_path_node_1.introduction_node_id = nodes[1];
4705                 let mut node_1_payinfo = blinded_payinfo.clone();
4706                 node_1_payinfo.htlc_maximum_msat = 180_000;
4707
4708                 let two_hop_blinded_payment_params = PaymentParameters::blinded(
4709                         vec![
4710                                 (node_0_payinfo, blinded_path_node_0),
4711                                 (node_7_payinfo, blinded_path_node_7),
4712                                 (node_1_payinfo, blinded_path_node_1)
4713                         ])
4714                         .with_bolt12_features(bolt12_features).unwrap();
4715                 do_simple_mpp_route_test(two_hop_blinded_payment_params);
4716         }
4717
4718
4719         fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
4720                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4721                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4722                 let scorer = ln_test_utils::TestScorer::new();
4723                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4724                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4725
4726                 // We need a route consisting of 3 paths:
4727                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4728                 // To achieve this, the amount being transferred should be around
4729                 // the total capacity of these 3 paths.
4730
4731                 // First, we set limits on these (previously unlimited) channels.
4732                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4733
4734                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4735                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4736                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4737                         short_channel_id: 1,
4738                         timestamp: 2,
4739                         flags: 0,
4740                         cltv_expiry_delta: 0,
4741                         htlc_minimum_msat: 0,
4742                         htlc_maximum_msat: 100_000,
4743                         fee_base_msat: 0,
4744                         fee_proportional_millionths: 0,
4745                         excess_data: Vec::new()
4746                 });
4747                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4748                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4749                         short_channel_id: 3,
4750                         timestamp: 2,
4751                         flags: 0,
4752                         cltv_expiry_delta: 0,
4753                         htlc_minimum_msat: 0,
4754                         htlc_maximum_msat: 50_000,
4755                         fee_base_msat: 0,
4756                         fee_proportional_millionths: 0,
4757                         excess_data: Vec::new()
4758                 });
4759
4760                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4761                 // (total limit 60).
4762                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4763                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4764                         short_channel_id: 12,
4765                         timestamp: 2,
4766                         flags: 0,
4767                         cltv_expiry_delta: 0,
4768                         htlc_minimum_msat: 0,
4769                         htlc_maximum_msat: 60_000,
4770                         fee_base_msat: 0,
4771                         fee_proportional_millionths: 0,
4772                         excess_data: Vec::new()
4773                 });
4774                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4775                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4776                         short_channel_id: 13,
4777                         timestamp: 2,
4778                         flags: 0,
4779                         cltv_expiry_delta: 0,
4780                         htlc_minimum_msat: 0,
4781                         htlc_maximum_msat: 60_000,
4782                         fee_base_msat: 0,
4783                         fee_proportional_millionths: 0,
4784                         excess_data: Vec::new()
4785                 });
4786
4787                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4788                 // (total capacity 180 sats).
4789                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4790                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4791                         short_channel_id: 2,
4792                         timestamp: 2,
4793                         flags: 0,
4794                         cltv_expiry_delta: 0,
4795                         htlc_minimum_msat: 0,
4796                         htlc_maximum_msat: 200_000,
4797                         fee_base_msat: 0,
4798                         fee_proportional_millionths: 0,
4799                         excess_data: Vec::new()
4800                 });
4801                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4802                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4803                         short_channel_id: 4,
4804                         timestamp: 2,
4805                         flags: 0,
4806                         cltv_expiry_delta: 0,
4807                         htlc_minimum_msat: 0,
4808                         htlc_maximum_msat: 180_000,
4809                         fee_base_msat: 0,
4810                         fee_proportional_millionths: 0,
4811                         excess_data: Vec::new()
4812                 });
4813
4814                 {
4815                         // Attempt to route more than available results in a failure.
4816                         let route_params = RouteParameters::from_payment_params_and_value(
4817                                 payment_params.clone(), 300_000);
4818                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4819                                 &our_id, &route_params, &network_graph.read_only(), None,
4820                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4821                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
4822                         } else { panic!(); }
4823                 }
4824
4825                 {
4826                         // Attempt to route while setting max_path_count to 0 results in a failure.
4827                         let zero_payment_params = payment_params.clone().with_max_path_count(0);
4828                         let route_params = RouteParameters::from_payment_params_and_value(
4829                                 zero_payment_params, 100);
4830                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4831                                 &our_id, &route_params, &network_graph.read_only(), None,
4832                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4833                                         assert_eq!(err, "Can't find a route with no paths allowed.");
4834                         } else { panic!(); }
4835                 }
4836
4837                 {
4838                         // Attempt to route while setting max_path_count to 3 results in a failure.
4839                         // This is the case because the minimal_value_contribution_msat would require each path
4840                         // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4841                         let fail_payment_params = payment_params.clone().with_max_path_count(3);
4842                         let route_params = RouteParameters::from_payment_params_and_value(
4843                                 fail_payment_params, 250_000);
4844                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4845                                 &our_id, &route_params, &network_graph.read_only(), None,
4846                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4847                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
4848                         } else { panic!(); }
4849                 }
4850
4851                 {
4852                         // Now, attempt to route 250 sats (just a bit below the capacity).
4853                         // Our algorithm should provide us with these 3 paths.
4854                         let route_params = RouteParameters::from_payment_params_and_value(
4855                                 payment_params.clone(), 250_000);
4856                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4857                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4858                         assert_eq!(route.paths.len(), 3);
4859                         let mut total_amount_paid_msat = 0;
4860                         for path in &route.paths {
4861                                 if let Some(bt) = &path.blinded_tail {
4862                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4863                                 } else {
4864                                         assert_eq!(path.hops.len(), 2);
4865                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4866                                 }
4867                                 total_amount_paid_msat += path.final_value_msat();
4868                         }
4869                         assert_eq!(total_amount_paid_msat, 250_000);
4870                 }
4871
4872                 {
4873                         // Attempt to route an exact amount is also fine
4874                         let route_params = RouteParameters::from_payment_params_and_value(
4875                                 payment_params.clone(), 290_000);
4876                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4877                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4878                         assert_eq!(route.paths.len(), 3);
4879                         let mut total_amount_paid_msat = 0;
4880                         for path in &route.paths {
4881                                 if payment_params.payee.blinded_route_hints().len() != 0 {
4882                                         assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
4883                                 if let Some(bt) = &path.blinded_tail {
4884                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
4885                                         if bt.hops.len() > 1 {
4886                                                 assert_eq!(path.hops.last().unwrap().pubkey,
4887                                                         payment_params.payee.blinded_route_hints().iter()
4888                                                                 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
4889                                                                 .map(|(_, p)| p.introduction_node_id).unwrap());
4890                                         } else {
4891                                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4892                                         }
4893                                 } else {
4894                                         assert_eq!(path.hops.len(), 2);
4895                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4896                                 }
4897                                 total_amount_paid_msat += path.final_value_msat();
4898                         }
4899                         assert_eq!(total_amount_paid_msat, 290_000);
4900                 }
4901         }
4902
4903         #[test]
4904         fn long_mpp_route_test() {
4905                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4906                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4907                 let scorer = ln_test_utils::TestScorer::new();
4908                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4909                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4910                 let config = UserConfig::default();
4911                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4912                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4913
4914                 // We need a route consisting of 3 paths:
4915                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4916                 // Note that these paths overlap (channels 5, 12, 13).
4917                 // We will route 300 sats.
4918                 // Each path will have 100 sats capacity, those channels which
4919                 // are used twice will have 200 sats capacity.
4920
4921                 // Disable other potential paths.
4922                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4923                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4924                         short_channel_id: 2,
4925                         timestamp: 2,
4926                         flags: 2,
4927                         cltv_expiry_delta: 0,
4928                         htlc_minimum_msat: 0,
4929                         htlc_maximum_msat: 100_000,
4930                         fee_base_msat: 0,
4931                         fee_proportional_millionths: 0,
4932                         excess_data: Vec::new()
4933                 });
4934                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4935                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4936                         short_channel_id: 7,
4937                         timestamp: 2,
4938                         flags: 2,
4939                         cltv_expiry_delta: 0,
4940                         htlc_minimum_msat: 0,
4941                         htlc_maximum_msat: 100_000,
4942                         fee_base_msat: 0,
4943                         fee_proportional_millionths: 0,
4944                         excess_data: Vec::new()
4945                 });
4946
4947                 // Path via {node0, node2} is channels {1, 3, 5}.
4948                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4949                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4950                         short_channel_id: 1,
4951                         timestamp: 2,
4952                         flags: 0,
4953                         cltv_expiry_delta: 0,
4954                         htlc_minimum_msat: 0,
4955                         htlc_maximum_msat: 100_000,
4956                         fee_base_msat: 0,
4957                         fee_proportional_millionths: 0,
4958                         excess_data: Vec::new()
4959                 });
4960                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4961                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4962                         short_channel_id: 3,
4963                         timestamp: 2,
4964                         flags: 0,
4965                         cltv_expiry_delta: 0,
4966                         htlc_minimum_msat: 0,
4967                         htlc_maximum_msat: 100_000,
4968                         fee_base_msat: 0,
4969                         fee_proportional_millionths: 0,
4970                         excess_data: Vec::new()
4971                 });
4972
4973                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4974                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4975                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4976                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4977                         short_channel_id: 5,
4978                         timestamp: 2,
4979                         flags: 0,
4980                         cltv_expiry_delta: 0,
4981                         htlc_minimum_msat: 0,
4982                         htlc_maximum_msat: 200_000,
4983                         fee_base_msat: 0,
4984                         fee_proportional_millionths: 0,
4985                         excess_data: Vec::new()
4986                 });
4987
4988                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4989                 // Add 100 sats to the capacities of {12, 13}, because these channels
4990                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4991                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4992                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4993                         short_channel_id: 12,
4994                         timestamp: 2,
4995                         flags: 0,
4996                         cltv_expiry_delta: 0,
4997                         htlc_minimum_msat: 0,
4998                         htlc_maximum_msat: 200_000,
4999                         fee_base_msat: 0,
5000                         fee_proportional_millionths: 0,
5001                         excess_data: Vec::new()
5002                 });
5003                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5004                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5005                         short_channel_id: 13,
5006                         timestamp: 2,
5007                         flags: 0,
5008                         cltv_expiry_delta: 0,
5009                         htlc_minimum_msat: 0,
5010                         htlc_maximum_msat: 200_000,
5011                         fee_base_msat: 0,
5012                         fee_proportional_millionths: 0,
5013                         excess_data: Vec::new()
5014                 });
5015
5016                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5017                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5018                         short_channel_id: 6,
5019                         timestamp: 2,
5020                         flags: 0,
5021                         cltv_expiry_delta: 0,
5022                         htlc_minimum_msat: 0,
5023                         htlc_maximum_msat: 100_000,
5024                         fee_base_msat: 0,
5025                         fee_proportional_millionths: 0,
5026                         excess_data: Vec::new()
5027                 });
5028                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5029                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5030                         short_channel_id: 11,
5031                         timestamp: 2,
5032                         flags: 0,
5033                         cltv_expiry_delta: 0,
5034                         htlc_minimum_msat: 0,
5035                         htlc_maximum_msat: 100_000,
5036                         fee_base_msat: 0,
5037                         fee_proportional_millionths: 0,
5038                         excess_data: Vec::new()
5039                 });
5040
5041                 // Path via {node7, node2} is channels {12, 13, 5}.
5042                 // We already limited them to 200 sats (they are used twice for 100 sats).
5043                 // Nothing to do here.
5044
5045                 {
5046                         // Attempt to route more than available results in a failure.
5047                         let route_params = RouteParameters::from_payment_params_and_value(
5048                                 payment_params.clone(), 350_000);
5049                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5050                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5051                                         &scorer, &Default::default(), &random_seed_bytes) {
5052                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5053                         } else { panic!(); }
5054                 }
5055
5056                 {
5057                         // Now, attempt to route 300 sats (exact amount we can route).
5058                         // Our algorithm should provide us with these 3 paths, 100 sats each.
5059                         let route_params = RouteParameters::from_payment_params_and_value(
5060                                 payment_params, 300_000);
5061                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5062                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5063                         assert_eq!(route.paths.len(), 3);
5064
5065                         let mut total_amount_paid_msat = 0;
5066                         for path in &route.paths {
5067                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5068                                 total_amount_paid_msat += path.final_value_msat();
5069                         }
5070                         assert_eq!(total_amount_paid_msat, 300_000);
5071                 }
5072
5073         }
5074
5075         #[test]
5076         fn mpp_cheaper_route_test() {
5077                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5078                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5079                 let scorer = ln_test_utils::TestScorer::new();
5080                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5081                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5082                 let config = UserConfig::default();
5083                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5084
5085                 // This test checks that if we have two cheaper paths and one more expensive path,
5086                 // so that liquidity-wise any 2 of 3 combination is sufficient,
5087                 // two cheaper paths will be taken.
5088                 // These paths have equal available liquidity.
5089
5090                 // We need a combination of 3 paths:
5091                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5092                 // Note that these paths overlap (channels 5, 12, 13).
5093                 // Each path will have 100 sats capacity, those channels which
5094                 // are used twice will have 200 sats capacity.
5095
5096                 // Disable other potential paths.
5097                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5098                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5099                         short_channel_id: 2,
5100                         timestamp: 2,
5101                         flags: 2,
5102                         cltv_expiry_delta: 0,
5103                         htlc_minimum_msat: 0,
5104                         htlc_maximum_msat: 100_000,
5105                         fee_base_msat: 0,
5106                         fee_proportional_millionths: 0,
5107                         excess_data: Vec::new()
5108                 });
5109                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5110                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5111                         short_channel_id: 7,
5112                         timestamp: 2,
5113                         flags: 2,
5114                         cltv_expiry_delta: 0,
5115                         htlc_minimum_msat: 0,
5116                         htlc_maximum_msat: 100_000,
5117                         fee_base_msat: 0,
5118                         fee_proportional_millionths: 0,
5119                         excess_data: Vec::new()
5120                 });
5121
5122                 // Path via {node0, node2} is channels {1, 3, 5}.
5123                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5124                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5125                         short_channel_id: 1,
5126                         timestamp: 2,
5127                         flags: 0,
5128                         cltv_expiry_delta: 0,
5129                         htlc_minimum_msat: 0,
5130                         htlc_maximum_msat: 100_000,
5131                         fee_base_msat: 0,
5132                         fee_proportional_millionths: 0,
5133                         excess_data: Vec::new()
5134                 });
5135                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5136                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5137                         short_channel_id: 3,
5138                         timestamp: 2,
5139                         flags: 0,
5140                         cltv_expiry_delta: 0,
5141                         htlc_minimum_msat: 0,
5142                         htlc_maximum_msat: 100_000,
5143                         fee_base_msat: 0,
5144                         fee_proportional_millionths: 0,
5145                         excess_data: Vec::new()
5146                 });
5147
5148                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5149                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5150                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5151                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5152                         short_channel_id: 5,
5153                         timestamp: 2,
5154                         flags: 0,
5155                         cltv_expiry_delta: 0,
5156                         htlc_minimum_msat: 0,
5157                         htlc_maximum_msat: 200_000,
5158                         fee_base_msat: 0,
5159                         fee_proportional_millionths: 0,
5160                         excess_data: Vec::new()
5161                 });
5162
5163                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5164                 // Add 100 sats to the capacities of {12, 13}, because these channels
5165                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5166                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5167                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5168                         short_channel_id: 12,
5169                         timestamp: 2,
5170                         flags: 0,
5171                         cltv_expiry_delta: 0,
5172                         htlc_minimum_msat: 0,
5173                         htlc_maximum_msat: 200_000,
5174                         fee_base_msat: 0,
5175                         fee_proportional_millionths: 0,
5176                         excess_data: Vec::new()
5177                 });
5178                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5179                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5180                         short_channel_id: 13,
5181                         timestamp: 2,
5182                         flags: 0,
5183                         cltv_expiry_delta: 0,
5184                         htlc_minimum_msat: 0,
5185                         htlc_maximum_msat: 200_000,
5186                         fee_base_msat: 0,
5187                         fee_proportional_millionths: 0,
5188                         excess_data: Vec::new()
5189                 });
5190
5191                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5192                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5193                         short_channel_id: 6,
5194                         timestamp: 2,
5195                         flags: 0,
5196                         cltv_expiry_delta: 0,
5197                         htlc_minimum_msat: 0,
5198                         htlc_maximum_msat: 100_000,
5199                         fee_base_msat: 1_000,
5200                         fee_proportional_millionths: 0,
5201                         excess_data: Vec::new()
5202                 });
5203                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5204                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5205                         short_channel_id: 11,
5206                         timestamp: 2,
5207                         flags: 0,
5208                         cltv_expiry_delta: 0,
5209                         htlc_minimum_msat: 0,
5210                         htlc_maximum_msat: 100_000,
5211                         fee_base_msat: 0,
5212                         fee_proportional_millionths: 0,
5213                         excess_data: Vec::new()
5214                 });
5215
5216                 // Path via {node7, node2} is channels {12, 13, 5}.
5217                 // We already limited them to 200 sats (they are used twice for 100 sats).
5218                 // Nothing to do here.
5219
5220                 {
5221                         // Now, attempt to route 180 sats.
5222                         // Our algorithm should provide us with these 2 paths.
5223                         let route_params = RouteParameters::from_payment_params_and_value(
5224                                 payment_params, 180_000);
5225                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5226                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5227                         assert_eq!(route.paths.len(), 2);
5228
5229                         let mut total_value_transferred_msat = 0;
5230                         let mut total_paid_msat = 0;
5231                         for path in &route.paths {
5232                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5233                                 total_value_transferred_msat += path.final_value_msat();
5234                                 for hop in &path.hops {
5235                                         total_paid_msat += hop.fee_msat;
5236                                 }
5237                         }
5238                         // If we paid fee, this would be higher.
5239                         assert_eq!(total_value_transferred_msat, 180_000);
5240                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5241                         assert_eq!(total_fees_paid, 0);
5242                 }
5243         }
5244
5245         #[test]
5246         fn fees_on_mpp_route_test() {
5247                 // This test makes sure that MPP algorithm properly takes into account
5248                 // fees charged on the channels, by making the fees impactful:
5249                 // if the fee is not properly accounted for, the behavior is different.
5250                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5251                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5252                 let scorer = ln_test_utils::TestScorer::new();
5253                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5254                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5255                 let config = UserConfig::default();
5256                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5257
5258                 // We need a route consisting of 2 paths:
5259                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5260                 // We will route 200 sats, Each path will have 100 sats capacity.
5261
5262                 // This test is not particularly stable: e.g.,
5263                 // there's a way to route via {node0, node2, node4}.
5264                 // It works while pathfinding is deterministic, but can be broken otherwise.
5265                 // It's fine to ignore this concern for now.
5266
5267                 // Disable other potential paths.
5268                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5269                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5270                         short_channel_id: 2,
5271                         timestamp: 2,
5272                         flags: 2,
5273                         cltv_expiry_delta: 0,
5274                         htlc_minimum_msat: 0,
5275                         htlc_maximum_msat: 100_000,
5276                         fee_base_msat: 0,
5277                         fee_proportional_millionths: 0,
5278                         excess_data: Vec::new()
5279                 });
5280
5281                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5282                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5283                         short_channel_id: 7,
5284                         timestamp: 2,
5285                         flags: 2,
5286                         cltv_expiry_delta: 0,
5287                         htlc_minimum_msat: 0,
5288                         htlc_maximum_msat: 100_000,
5289                         fee_base_msat: 0,
5290                         fee_proportional_millionths: 0,
5291                         excess_data: Vec::new()
5292                 });
5293
5294                 // Path via {node0, node2} is channels {1, 3, 5}.
5295                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5296                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5297                         short_channel_id: 1,
5298                         timestamp: 2,
5299                         flags: 0,
5300                         cltv_expiry_delta: 0,
5301                         htlc_minimum_msat: 0,
5302                         htlc_maximum_msat: 100_000,
5303                         fee_base_msat: 0,
5304                         fee_proportional_millionths: 0,
5305                         excess_data: Vec::new()
5306                 });
5307                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5308                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5309                         short_channel_id: 3,
5310                         timestamp: 2,
5311                         flags: 0,
5312                         cltv_expiry_delta: 0,
5313                         htlc_minimum_msat: 0,
5314                         htlc_maximum_msat: 100_000,
5315                         fee_base_msat: 0,
5316                         fee_proportional_millionths: 0,
5317                         excess_data: Vec::new()
5318                 });
5319
5320                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5321                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5322                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5323                         short_channel_id: 5,
5324                         timestamp: 2,
5325                         flags: 0,
5326                         cltv_expiry_delta: 0,
5327                         htlc_minimum_msat: 0,
5328                         htlc_maximum_msat: 100_000,
5329                         fee_base_msat: 0,
5330                         fee_proportional_millionths: 0,
5331                         excess_data: Vec::new()
5332                 });
5333
5334                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5335                 // All channels should be 100 sats capacity. But for the fee experiment,
5336                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5337                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5338                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5339                 // so no matter how large are other channels,
5340                 // the whole path will be limited by 100 sats with just these 2 conditions:
5341                 // - channel 12 capacity is 250 sats
5342                 // - fee for channel 6 is 150 sats
5343                 // Let's test this by enforcing these 2 conditions and removing other limits.
5344                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5345                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5346                         short_channel_id: 12,
5347                         timestamp: 2,
5348                         flags: 0,
5349                         cltv_expiry_delta: 0,
5350                         htlc_minimum_msat: 0,
5351                         htlc_maximum_msat: 250_000,
5352                         fee_base_msat: 0,
5353                         fee_proportional_millionths: 0,
5354                         excess_data: Vec::new()
5355                 });
5356                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5357                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5358                         short_channel_id: 13,
5359                         timestamp: 2,
5360                         flags: 0,
5361                         cltv_expiry_delta: 0,
5362                         htlc_minimum_msat: 0,
5363                         htlc_maximum_msat: MAX_VALUE_MSAT,
5364                         fee_base_msat: 0,
5365                         fee_proportional_millionths: 0,
5366                         excess_data: Vec::new()
5367                 });
5368
5369                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5370                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5371                         short_channel_id: 6,
5372                         timestamp: 2,
5373                         flags: 0,
5374                         cltv_expiry_delta: 0,
5375                         htlc_minimum_msat: 0,
5376                         htlc_maximum_msat: MAX_VALUE_MSAT,
5377                         fee_base_msat: 150_000,
5378                         fee_proportional_millionths: 0,
5379                         excess_data: Vec::new()
5380                 });
5381                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5382                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5383                         short_channel_id: 11,
5384                         timestamp: 2,
5385                         flags: 0,
5386                         cltv_expiry_delta: 0,
5387                         htlc_minimum_msat: 0,
5388                         htlc_maximum_msat: MAX_VALUE_MSAT,
5389                         fee_base_msat: 0,
5390                         fee_proportional_millionths: 0,
5391                         excess_data: Vec::new()
5392                 });
5393
5394                 {
5395                         // Attempt to route more than available results in a failure.
5396                         let route_params = RouteParameters::from_payment_params_and_value(
5397                                 payment_params.clone(), 210_000);
5398                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5399                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5400                                         &scorer, &Default::default(), &random_seed_bytes) {
5401                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5402                         } else { panic!(); }
5403                 }
5404
5405                 {
5406                         // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5407                         let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5408                                 max_total_routing_fee_msat: Some(149_999) };
5409                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5410                                 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5411                                 &scorer, &(), &random_seed_bytes) {
5412                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
5413                         } else { panic!(); }
5414                 }
5415
5416                 {
5417                         // Now, attempt to route 200 sats (exact amount we can route).
5418                         let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5419                                 max_total_routing_fee_msat: Some(150_000) };
5420                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5421                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5422                         assert_eq!(route.paths.len(), 2);
5423
5424                         let mut total_amount_paid_msat = 0;
5425                         for path in &route.paths {
5426                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5427                                 total_amount_paid_msat += path.final_value_msat();
5428                         }
5429                         assert_eq!(total_amount_paid_msat, 200_000);
5430                         assert_eq!(route.get_total_fees(), 150_000);
5431                 }
5432         }
5433
5434         #[test]
5435         fn mpp_with_last_hops() {
5436                 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5437                 // via a single last-hop route hint, we'd fail to route if we first collected routes
5438                 // totaling close but not quite enough to fund the full payment.
5439                 //
5440                 // This was because we considered last-hop hints to have exactly the sought payment amount
5441                 // instead of the amount we were trying to collect, needlessly limiting our path searching
5442                 // at the very first hop.
5443                 //
5444                 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5445                 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5446                 // to only have the remaining to-collect amount in available liquidity.
5447                 //
5448                 // This bug appeared in production in some specific channel configurations.
5449                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5450                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5451                 let scorer = ln_test_utils::TestScorer::new();
5452                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5453                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5454                 let config = UserConfig::default();
5455                 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5456                         .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5457                                 src_node_id: nodes[2],
5458                                 short_channel_id: 42,
5459                                 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5460                                 cltv_expiry_delta: 42,
5461                                 htlc_minimum_msat: None,
5462                                 htlc_maximum_msat: None,
5463                         }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5464
5465                 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5466                 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5467                 // would first use the no-fee route and then fail to find a path along the second route as
5468                 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5469                 // under 5% of our payment amount.
5470                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5471                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5472                         short_channel_id: 1,
5473                         timestamp: 2,
5474                         flags: 0,
5475                         cltv_expiry_delta: (5 << 4) | 5,
5476                         htlc_minimum_msat: 0,
5477                         htlc_maximum_msat: 99_000,
5478                         fee_base_msat: u32::max_value(),
5479                         fee_proportional_millionths: u32::max_value(),
5480                         excess_data: Vec::new()
5481                 });
5482                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5483                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5484                         short_channel_id: 2,
5485                         timestamp: 2,
5486                         flags: 0,
5487                         cltv_expiry_delta: (5 << 4) | 3,
5488                         htlc_minimum_msat: 0,
5489                         htlc_maximum_msat: 99_000,
5490                         fee_base_msat: u32::max_value(),
5491                         fee_proportional_millionths: u32::max_value(),
5492                         excess_data: Vec::new()
5493                 });
5494                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5495                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5496                         short_channel_id: 4,
5497                         timestamp: 2,
5498                         flags: 0,
5499                         cltv_expiry_delta: (4 << 4) | 1,
5500                         htlc_minimum_msat: 0,
5501                         htlc_maximum_msat: MAX_VALUE_MSAT,
5502                         fee_base_msat: 1,
5503                         fee_proportional_millionths: 0,
5504                         excess_data: Vec::new()
5505                 });
5506                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5507                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5508                         short_channel_id: 13,
5509                         timestamp: 2,
5510                         flags: 0|2, // Channel disabled
5511                         cltv_expiry_delta: (13 << 4) | 1,
5512                         htlc_minimum_msat: 0,
5513                         htlc_maximum_msat: MAX_VALUE_MSAT,
5514                         fee_base_msat: 0,
5515                         fee_proportional_millionths: 2000000,
5516                         excess_data: Vec::new()
5517                 });
5518
5519                 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5520                 // overpay at all.
5521                 let route_params = RouteParameters::from_payment_params_and_value(
5522                         payment_params, 100_000);
5523                 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5524                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5525                 assert_eq!(route.paths.len(), 2);
5526                 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5527                 // Paths are manually ordered ordered by SCID, so:
5528                 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5529                 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5530                 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5531                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5532                 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5533                 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5534                 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5535                 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5536                 assert_eq!(route.get_total_fees(), 1);
5537                 assert_eq!(route.get_total_amount(), 100_000);
5538         }
5539
5540         #[test]
5541         fn drop_lowest_channel_mpp_route_test() {
5542                 // This test checks that low-capacity channel is dropped when after
5543                 // path finding we realize that we found more capacity than we need.
5544                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5545                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5546                 let scorer = ln_test_utils::TestScorer::new();
5547                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5548                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5549                 let config = UserConfig::default();
5550                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
5551                         .with_max_channel_saturation_power_of_half(0);
5552
5553                 // We need a route consisting of 3 paths:
5554                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5555
5556                 // The first and the second paths should be sufficient, but the third should be
5557                 // cheaper, so that we select it but drop later.
5558
5559                 // First, we set limits on these (previously unlimited) channels.
5560                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5561
5562                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5563                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5564                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5565                         short_channel_id: 1,
5566                         timestamp: 2,
5567                         flags: 0,
5568                         cltv_expiry_delta: 0,
5569                         htlc_minimum_msat: 0,
5570                         htlc_maximum_msat: 100_000,
5571                         fee_base_msat: 0,
5572                         fee_proportional_millionths: 0,
5573                         excess_data: Vec::new()
5574                 });
5575                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5576                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5577                         short_channel_id: 3,
5578                         timestamp: 2,
5579                         flags: 0,
5580                         cltv_expiry_delta: 0,
5581                         htlc_minimum_msat: 0,
5582                         htlc_maximum_msat: 50_000,
5583                         fee_base_msat: 100,
5584                         fee_proportional_millionths: 0,
5585                         excess_data: Vec::new()
5586                 });
5587
5588                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5589                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5590                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5591                         short_channel_id: 12,
5592                         timestamp: 2,
5593                         flags: 0,
5594                         cltv_expiry_delta: 0,
5595                         htlc_minimum_msat: 0,
5596                         htlc_maximum_msat: 60_000,
5597                         fee_base_msat: 100,
5598                         fee_proportional_millionths: 0,
5599                         excess_data: Vec::new()
5600                 });
5601                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5602                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5603                         short_channel_id: 13,
5604                         timestamp: 2,
5605                         flags: 0,
5606                         cltv_expiry_delta: 0,
5607                         htlc_minimum_msat: 0,
5608                         htlc_maximum_msat: 60_000,
5609                         fee_base_msat: 0,
5610                         fee_proportional_millionths: 0,
5611                         excess_data: Vec::new()
5612                 });
5613
5614                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5615                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5616                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5617                         short_channel_id: 2,
5618                         timestamp: 2,
5619                         flags: 0,
5620                         cltv_expiry_delta: 0,
5621                         htlc_minimum_msat: 0,
5622                         htlc_maximum_msat: 20_000,
5623                         fee_base_msat: 0,
5624                         fee_proportional_millionths: 0,
5625                         excess_data: Vec::new()
5626                 });
5627                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5628                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5629                         short_channel_id: 4,
5630                         timestamp: 2,
5631                         flags: 0,
5632                         cltv_expiry_delta: 0,
5633                         htlc_minimum_msat: 0,
5634                         htlc_maximum_msat: 20_000,
5635                         fee_base_msat: 0,
5636                         fee_proportional_millionths: 0,
5637                         excess_data: Vec::new()
5638                 });
5639
5640                 {
5641                         // Attempt to route more than available results in a failure.
5642                         let route_params = RouteParameters::from_payment_params_and_value(
5643                                 payment_params.clone(), 150_000);
5644                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5645                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5646                                         &scorer, &Default::default(), &random_seed_bytes) {
5647                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5648                         } else { panic!(); }
5649                 }
5650
5651                 {
5652                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5653                         // Our algorithm should provide us with these 3 paths.
5654                         let route_params = RouteParameters::from_payment_params_and_value(
5655                                 payment_params.clone(), 125_000);
5656                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5657                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5658                         assert_eq!(route.paths.len(), 3);
5659                         let mut total_amount_paid_msat = 0;
5660                         for path in &route.paths {
5661                                 assert_eq!(path.hops.len(), 2);
5662                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5663                                 total_amount_paid_msat += path.final_value_msat();
5664                         }
5665                         assert_eq!(total_amount_paid_msat, 125_000);
5666                 }
5667
5668                 {
5669                         // Attempt to route without the last small cheap channel
5670                         let route_params = RouteParameters::from_payment_params_and_value(
5671                                 payment_params, 90_000);
5672                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5673                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5674                         assert_eq!(route.paths.len(), 2);
5675                         let mut total_amount_paid_msat = 0;
5676                         for path in &route.paths {
5677                                 assert_eq!(path.hops.len(), 2);
5678                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5679                                 total_amount_paid_msat += path.final_value_msat();
5680                         }
5681                         assert_eq!(total_amount_paid_msat, 90_000);
5682                 }
5683         }
5684
5685         #[test]
5686         fn min_criteria_consistency() {
5687                 // Test that we don't use an inconsistent metric between updating and walking nodes during
5688                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5689                 // was updated with a different criterion from the heap sorting, resulting in loops in
5690                 // calculated paths. We test for that specific case here.
5691
5692                 // We construct a network that looks like this:
5693                 //
5694                 //            node2 -1(3)2- node3
5695                 //              2          2
5696                 //               (2)     (4)
5697                 //                  1   1
5698                 //    node1 -1(5)2- node4 -1(1)2- node6
5699                 //    2
5700                 //   (6)
5701                 //        1
5702                 // our_node
5703                 //
5704                 // We create a loop on the side of our real path - our destination is node 6, with a
5705                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5706                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5707                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5708                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5709                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5710                 // "previous hop" being set to node 3, creating a loop in the path.
5711                 let secp_ctx = Secp256k1::new();
5712                 let logger = Arc::new(ln_test_utils::TestLogger::new());
5713                 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5714                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5715                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5716                 let scorer = ln_test_utils::TestScorer::new();
5717                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5718                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5719                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5720
5721                 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5722                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5723                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5724                         short_channel_id: 6,
5725                         timestamp: 1,
5726                         flags: 0,
5727                         cltv_expiry_delta: (6 << 4) | 0,
5728                         htlc_minimum_msat: 0,
5729                         htlc_maximum_msat: MAX_VALUE_MSAT,
5730                         fee_base_msat: 0,
5731                         fee_proportional_millionths: 0,
5732                         excess_data: Vec::new()
5733                 });
5734                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5735
5736                 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5737                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5738                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5739                         short_channel_id: 5,
5740                         timestamp: 1,
5741                         flags: 0,
5742                         cltv_expiry_delta: (5 << 4) | 0,
5743                         htlc_minimum_msat: 0,
5744                         htlc_maximum_msat: MAX_VALUE_MSAT,
5745                         fee_base_msat: 100,
5746                         fee_proportional_millionths: 0,
5747                         excess_data: Vec::new()
5748                 });
5749                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5750
5751                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5752                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5753                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5754                         short_channel_id: 4,
5755                         timestamp: 1,
5756                         flags: 0,
5757                         cltv_expiry_delta: (4 << 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[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5765
5766                 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5767                 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5768                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5769                         short_channel_id: 3,
5770                         timestamp: 1,
5771                         flags: 0,
5772                         cltv_expiry_delta: (3 << 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                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5780
5781                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5782                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5783                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5784                         short_channel_id: 2,
5785                         timestamp: 1,
5786                         flags: 0,
5787                         cltv_expiry_delta: (2 << 4) | 0,
5788                         htlc_minimum_msat: 0,
5789                         htlc_maximum_msat: MAX_VALUE_MSAT,
5790                         fee_base_msat: 0,
5791                         fee_proportional_millionths: 0,
5792                         excess_data: Vec::new()
5793                 });
5794
5795                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5796                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5797                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5798                         short_channel_id: 1,
5799                         timestamp: 1,
5800                         flags: 0,
5801                         cltv_expiry_delta: (1 << 4) | 0,
5802                         htlc_minimum_msat: 100,
5803                         htlc_maximum_msat: MAX_VALUE_MSAT,
5804                         fee_base_msat: 0,
5805                         fee_proportional_millionths: 0,
5806                         excess_data: Vec::new()
5807                 });
5808                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5809
5810                 {
5811                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
5812                         let route_params = RouteParameters::from_payment_params_and_value(
5813                                 payment_params, 10_000);
5814                         let route = get_route(&our_id, &route_params, &network.read_only(), None,
5815                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5816                         assert_eq!(route.paths.len(), 1);
5817                         assert_eq!(route.paths[0].hops.len(), 3);
5818
5819                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5820                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5821                         assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5822                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5823                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5824                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5825
5826                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5827                         assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5828                         assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5829                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5830                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5831                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5832
5833                         assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5834                         assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5835                         assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5836                         assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5837                         assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5838                         assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5839                 }
5840         }
5841
5842
5843         #[test]
5844         fn exact_fee_liquidity_limit() {
5845                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5846                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5847                 // we calculated fees on a higher value, resulting in us ignoring such paths.
5848                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5849                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5850                 let scorer = ln_test_utils::TestScorer::new();
5851                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5852                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5853                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5854
5855                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5856                 // send.
5857                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5858                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5859                         short_channel_id: 2,
5860                         timestamp: 2,
5861                         flags: 0,
5862                         cltv_expiry_delta: 0,
5863                         htlc_minimum_msat: 0,
5864                         htlc_maximum_msat: 85_000,
5865                         fee_base_msat: 0,
5866                         fee_proportional_millionths: 0,
5867                         excess_data: Vec::new()
5868                 });
5869
5870                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5871                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5872                         short_channel_id: 12,
5873                         timestamp: 2,
5874                         flags: 0,
5875                         cltv_expiry_delta: (4 << 4) | 1,
5876                         htlc_minimum_msat: 0,
5877                         htlc_maximum_msat: 270_000,
5878                         fee_base_msat: 0,
5879                         fee_proportional_millionths: 1000000,
5880                         excess_data: Vec::new()
5881                 });
5882
5883                 {
5884                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5885                         // 200% fee charged channel 13 in the 1-to-2 direction.
5886                         let mut route_params = RouteParameters::from_payment_params_and_value(
5887                                 payment_params, 90_000);
5888                         route_params.max_total_routing_fee_msat = Some(90_000*2);
5889                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5890                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5891                         assert_eq!(route.paths.len(), 1);
5892                         assert_eq!(route.paths[0].hops.len(), 2);
5893
5894                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5895                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5896                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5897                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5898                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5899                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5900
5901                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5902                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5903                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5904                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5905                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5906                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5907                 }
5908         }
5909
5910         #[test]
5911         fn htlc_max_reduction_below_min() {
5912                 // Test that if, while walking the graph, we reduce the value being sent to meet an
5913                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5914                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5915                 // resulting in us thinking there is no possible path, even if other paths exist.
5916                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5917                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5918                 let scorer = ln_test_utils::TestScorer::new();
5919                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5920                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5921                 let config = UserConfig::default();
5922                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5923
5924                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5925                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5926                 // then try to send 90_000.
5927                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5928                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5929                         short_channel_id: 2,
5930                         timestamp: 2,
5931                         flags: 0,
5932                         cltv_expiry_delta: 0,
5933                         htlc_minimum_msat: 0,
5934                         htlc_maximum_msat: 80_000,
5935                         fee_base_msat: 0,
5936                         fee_proportional_millionths: 0,
5937                         excess_data: Vec::new()
5938                 });
5939                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5940                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5941                         short_channel_id: 4,
5942                         timestamp: 2,
5943                         flags: 0,
5944                         cltv_expiry_delta: (4 << 4) | 1,
5945                         htlc_minimum_msat: 90_000,
5946                         htlc_maximum_msat: MAX_VALUE_MSAT,
5947                         fee_base_msat: 0,
5948                         fee_proportional_millionths: 0,
5949                         excess_data: Vec::new()
5950                 });
5951
5952                 {
5953                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5954                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5955                         // expensive) channels 12-13 path.
5956                         let mut route_params = RouteParameters::from_payment_params_and_value(
5957                                 payment_params, 90_000);
5958                         route_params.max_total_routing_fee_msat = Some(90_000*2);
5959                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5960                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5961                         assert_eq!(route.paths.len(), 1);
5962                         assert_eq!(route.paths[0].hops.len(), 2);
5963
5964                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5965                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5966                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5967                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5968                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5969                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5970
5971                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5972                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5973                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5974                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5975                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5976                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5977                 }
5978         }
5979
5980         #[test]
5981         fn multiple_direct_first_hops() {
5982                 // Previously we'd only ever considered one first hop path per counterparty.
5983                 // However, as we don't restrict users to one channel per peer, we really need to support
5984                 // looking at all first hop paths.
5985                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5986                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5987                 // route over multiple channels with the same first hop.
5988                 let secp_ctx = Secp256k1::new();
5989                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5990                 let logger = Arc::new(ln_test_utils::TestLogger::new());
5991                 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5992                 let scorer = ln_test_utils::TestScorer::new();
5993                 let config = UserConfig::default();
5994                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5995                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5996                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5997
5998                 {
5999                         let route_params = RouteParameters::from_payment_params_and_value(
6000                                 payment_params.clone(), 100_000);
6001                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6002                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6003                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6004                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6005                         assert_eq!(route.paths.len(), 1);
6006                         assert_eq!(route.paths[0].hops.len(), 1);
6007
6008                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6009                         assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6010                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6011                 }
6012                 {
6013                         let route_params = RouteParameters::from_payment_params_and_value(
6014                                 payment_params.clone(), 100_000);
6015                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6016                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6017                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6018                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6019                         assert_eq!(route.paths.len(), 2);
6020                         assert_eq!(route.paths[0].hops.len(), 1);
6021                         assert_eq!(route.paths[1].hops.len(), 1);
6022
6023                         assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6024                                 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6025
6026                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6027                         assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6028
6029                         assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6030                         assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6031                 }
6032
6033                 {
6034                         // If we have a bunch of outbound channels to the same node, where most are not
6035                         // sufficient to pay the full payment, but one is, we should default to just using the
6036                         // one single channel that has sufficient balance, avoiding MPP.
6037                         //
6038                         // If we have several options above the 3xpayment value threshold, we should pick the
6039                         // smallest of them, avoiding further fragmenting our available outbound balance to
6040                         // this node.
6041                         let route_params = RouteParameters::from_payment_params_and_value(
6042                                 payment_params, 100_000);
6043                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6044                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6045                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6046                                 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6047                                 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6048                                 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6049                                 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6050                                 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6051                                 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6052                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6053                         assert_eq!(route.paths.len(), 1);
6054                         assert_eq!(route.paths[0].hops.len(), 1);
6055
6056                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6057                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6058                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6059                 }
6060         }
6061
6062         #[test]
6063         fn prefers_shorter_route_with_higher_fees() {
6064                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6065                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6066                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6067
6068                 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6069                 let scorer = ln_test_utils::TestScorer::new();
6070                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6071                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6072                 let route_params = RouteParameters::from_payment_params_and_value(
6073                         payment_params.clone(), 100);
6074                 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6075                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6076                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6077
6078                 assert_eq!(route.get_total_fees(), 100);
6079                 assert_eq!(route.get_total_amount(), 100);
6080                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6081
6082                 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6083                 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6084                 let scorer = FixedPenaltyScorer::with_penalty(100);
6085                 let route_params = RouteParameters::from_payment_params_and_value(
6086                         payment_params, 100);
6087                 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6088                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6089                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6090
6091                 assert_eq!(route.get_total_fees(), 300);
6092                 assert_eq!(route.get_total_amount(), 100);
6093                 assert_eq!(path, vec![2, 4, 7, 10]);
6094         }
6095
6096         struct BadChannelScorer {
6097                 short_channel_id: u64,
6098         }
6099
6100         #[cfg(c_bindings)]
6101         impl Writeable for BadChannelScorer {
6102                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6103         }
6104         impl ScoreLookUp for BadChannelScorer {
6105                 type ScoreParams = ();
6106                 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6107                         if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
6108                 }
6109         }
6110
6111         struct BadNodeScorer {
6112                 node_id: NodeId,
6113         }
6114
6115         #[cfg(c_bindings)]
6116         impl Writeable for BadNodeScorer {
6117                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6118         }
6119
6120         impl ScoreLookUp for BadNodeScorer {
6121                 type ScoreParams = ();
6122                 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6123                         if *target == self.node_id { u64::max_value() } else { 0 }
6124                 }
6125         }
6126
6127         #[test]
6128         fn avoids_routing_through_bad_channels_and_nodes() {
6129                 let (secp_ctx, network, _, _, logger) = build_graph();
6130                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6131                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6132                 let network_graph = network.read_only();
6133
6134                 // A path to nodes[6] exists when no penalties are applied to any channel.
6135                 let scorer = ln_test_utils::TestScorer::new();
6136                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6137                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6138                 let route_params = RouteParameters::from_payment_params_and_value(
6139                         payment_params, 100);
6140                 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6141                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6142                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6143
6144                 assert_eq!(route.get_total_fees(), 100);
6145                 assert_eq!(route.get_total_amount(), 100);
6146                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6147
6148                 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6149                 let scorer = BadChannelScorer { short_channel_id: 6 };
6150                 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6151                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6152                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6153
6154                 assert_eq!(route.get_total_fees(), 300);
6155                 assert_eq!(route.get_total_amount(), 100);
6156                 assert_eq!(path, vec![2, 4, 7, 10]);
6157
6158                 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6159                 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6160                 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6161                         &scorer, &Default::default(), &random_seed_bytes) {
6162                                 Err(LightningError { err, .. } ) => {
6163                                         assert_eq!(err, "Failed to find a path to the given destination");
6164                                 },
6165                                 Ok(_) => panic!("Expected error"),
6166                 }
6167         }
6168
6169         #[test]
6170         fn total_fees_single_path() {
6171                 let route = Route {
6172                         paths: vec![Path { hops: vec![
6173                                 RouteHop {
6174                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6175                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6176                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6177                                 },
6178                                 RouteHop {
6179                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6180                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6181                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6182                                 },
6183                                 RouteHop {
6184                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6185                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6186                                         short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6187                                 },
6188                         ], blinded_tail: None }],
6189                         route_params: None,
6190                 };
6191
6192                 assert_eq!(route.get_total_fees(), 250);
6193                 assert_eq!(route.get_total_amount(), 225);
6194         }
6195
6196         #[test]
6197         fn total_fees_multi_path() {
6198                 let route = Route {
6199                         paths: vec![Path { hops: vec![
6200                                 RouteHop {
6201                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6202                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6203                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6204                                 },
6205                                 RouteHop {
6206                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6207                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6208                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6209                                 },
6210                         ], blinded_tail: None }, Path { hops: vec![
6211                                 RouteHop {
6212                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6213                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6214                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6215                                 },
6216                                 RouteHop {
6217                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6218                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6219                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6220                                 },
6221                         ], blinded_tail: None }],
6222                         route_params: None,
6223                 };
6224
6225                 assert_eq!(route.get_total_fees(), 200);
6226                 assert_eq!(route.get_total_amount(), 300);
6227         }
6228
6229         #[test]
6230         fn total_empty_route_no_panic() {
6231                 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6232                 // would both panic if the route was completely empty. We test to ensure they return 0
6233                 // here, even though its somewhat nonsensical as a route.
6234                 let route = Route { paths: Vec::new(), route_params: None };
6235
6236                 assert_eq!(route.get_total_fees(), 0);
6237                 assert_eq!(route.get_total_amount(), 0);
6238         }
6239
6240         #[test]
6241         fn limits_total_cltv_delta() {
6242                 let (secp_ctx, network, _, _, logger) = build_graph();
6243                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6244                 let network_graph = network.read_only();
6245
6246                 let scorer = ln_test_utils::TestScorer::new();
6247
6248                 // Make sure that generally there is at least one route available
6249                 let feasible_max_total_cltv_delta = 1008;
6250                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6251                         .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6252                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6253                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6254                 let route_params = RouteParameters::from_payment_params_and_value(
6255                         feasible_payment_params, 100);
6256                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6257                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6258                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6259                 assert_ne!(path.len(), 0);
6260
6261                 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6262                 let fail_max_total_cltv_delta = 23;
6263                 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6264                         .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6265                 let route_params = RouteParameters::from_payment_params_and_value(
6266                         fail_payment_params, 100);
6267                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6268                         &Default::default(), &random_seed_bytes)
6269                 {
6270                         Err(LightningError { err, .. } ) => {
6271                                 assert_eq!(err, "Failed to find a path to the given destination");
6272                         },
6273                         Ok(_) => panic!("Expected error"),
6274                 }
6275         }
6276
6277         #[test]
6278         fn avoids_recently_failed_paths() {
6279                 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6280                 // randomly inserting channels into it until we can't find a route anymore.
6281                 let (secp_ctx, network, _, _, logger) = build_graph();
6282                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6283                 let network_graph = network.read_only();
6284
6285                 let scorer = ln_test_utils::TestScorer::new();
6286                 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6287                         .with_max_path_count(1);
6288                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6289                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6290
6291                 // We should be able to find a route initially, and then after we fail a few random
6292                 // channels eventually we won't be able to any longer.
6293                 let route_params = RouteParameters::from_payment_params_and_value(
6294                         payment_params.clone(), 100);
6295                 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6296                         &scorer, &Default::default(), &random_seed_bytes).is_ok());
6297                 loop {
6298                         let route_params = RouteParameters::from_payment_params_and_value(
6299                                 payment_params.clone(), 100);
6300                         if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6301                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6302                         {
6303                                 for chan in route.paths[0].hops.iter() {
6304                                         assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6305                                 }
6306                                 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6307                                         % route.paths[0].hops.len();
6308                                 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6309                         } else { break; }
6310                 }
6311         }
6312
6313         #[test]
6314         fn limits_path_length() {
6315                 let (secp_ctx, network, _, _, logger) = build_line_graph();
6316                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6317                 let network_graph = network.read_only();
6318
6319                 let scorer = ln_test_utils::TestScorer::new();
6320                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6321                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6322
6323                 // First check we can actually create a long route on this graph.
6324                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6325                 let route_params = RouteParameters::from_payment_params_and_value(
6326                         feasible_payment_params, 100);
6327                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6328                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6329                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6330                 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6331
6332                 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6333                 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6334                 let route_params = RouteParameters::from_payment_params_and_value(
6335                         fail_payment_params, 100);
6336                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6337                         &Default::default(), &random_seed_bytes)
6338                 {
6339                         Err(LightningError { err, .. } ) => {
6340                                 assert_eq!(err, "Failed to find a path to the given destination");
6341                         },
6342                         Ok(_) => panic!("Expected error"),
6343                 }
6344         }
6345
6346         #[test]
6347         fn adds_and_limits_cltv_offset() {
6348                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6349                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6350
6351                 let scorer = ln_test_utils::TestScorer::new();
6352
6353                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6354                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6355                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6356                 let route_params = RouteParameters::from_payment_params_and_value(
6357                         payment_params.clone(), 100);
6358                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6359                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6360                 assert_eq!(route.paths.len(), 1);
6361
6362                 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6363
6364                 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6365                 let mut route_default = route.clone();
6366                 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6367                 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6368                 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6369                 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6370                 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6371
6372                 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6373                 let mut route_limited = route.clone();
6374                 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6375                 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6376                 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6377                 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6378                 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6379         }
6380
6381         #[test]
6382         fn adds_plausible_cltv_offset() {
6383                 let (secp_ctx, network, _, _, logger) = build_graph();
6384                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6385                 let network_graph = network.read_only();
6386                 let network_nodes = network_graph.nodes();
6387                 let network_channels = network_graph.channels();
6388                 let scorer = ln_test_utils::TestScorer::new();
6389                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6390                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6391                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6392
6393                 let route_params = RouteParameters::from_payment_params_and_value(
6394                         payment_params.clone(), 100);
6395                 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6396                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6397                 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6398
6399                 let mut path_plausibility = vec![];
6400
6401                 for p in route.paths {
6402                         // 1. Select random observation point
6403                         let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6404                         let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6405
6406                         prng.process_in_place(&mut random_bytes);
6407                         let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6408                         let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6409
6410                         // 2. Calculate what CLTV expiry delta we would observe there
6411                         let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6412
6413                         // 3. Starting from the observation point, find candidate paths
6414                         let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6415                         candidates.push_back((observation_point, vec![]));
6416
6417                         let mut found_plausible_candidate = false;
6418
6419                         'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6420                                 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6421                                         if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6422                                                 found_plausible_candidate = true;
6423                                                 break 'candidate_loop;
6424                                         }
6425                                 }
6426
6427                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6428                                         for channel_id in &cur_node.channels {
6429                                                 if let Some(channel_info) = network_channels.get(&channel_id) {
6430                                                         if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6431                                                                 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6432                                                                 if cur_path_cltv_deltas.iter().sum::<u32>()
6433                                                                         .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6434                                                                         let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6435                                                                         new_path_cltv_deltas.push(next_cltv_expiry_delta);
6436                                                                         candidates.push_back((*next_id, new_path_cltv_deltas));
6437                                                                 }
6438                                                         }
6439                                                 }
6440                                         }
6441                                 }
6442                         }
6443
6444                         path_plausibility.push(found_plausible_candidate);
6445                 }
6446                 assert!(path_plausibility.iter().all(|x| *x));
6447         }
6448
6449         #[test]
6450         fn builds_correct_path_from_hops() {
6451                 let (secp_ctx, network, _, _, logger) = build_graph();
6452                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6453                 let network_graph = network.read_only();
6454
6455                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6456                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6457
6458                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6459                 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6460                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6461                 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6462                         Arc::clone(&logger), &random_seed_bytes).unwrap();
6463                 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6464                 assert_eq!(hops.len(), route.paths[0].hops.len());
6465                 for (idx, hop_pubkey) in hops.iter().enumerate() {
6466                         assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6467                 }
6468         }
6469
6470         #[test]
6471         fn avoids_saturating_channels() {
6472                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6473                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6474                 let decay_params = ProbabilisticScoringDecayParameters::default();
6475                 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6476
6477                 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6478                 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6479                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6480                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6481                         short_channel_id: 4,
6482                         timestamp: 2,
6483                         flags: 0,
6484                         cltv_expiry_delta: (4 << 4) | 1,
6485                         htlc_minimum_msat: 0,
6486                         htlc_maximum_msat: 250_000_000,
6487                         fee_base_msat: 0,
6488                         fee_proportional_millionths: 0,
6489                         excess_data: Vec::new()
6490                 });
6491                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6492                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
6493                         short_channel_id: 13,
6494                         timestamp: 2,
6495                         flags: 0,
6496                         cltv_expiry_delta: (13 << 4) | 1,
6497                         htlc_minimum_msat: 0,
6498                         htlc_maximum_msat: 250_000_000,
6499                         fee_base_msat: 0,
6500                         fee_proportional_millionths: 0,
6501                         excess_data: Vec::new()
6502                 });
6503
6504                 let config = UserConfig::default();
6505                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6506                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6507                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6508                 // 100,000 sats is less than the available liquidity on each channel, set above.
6509                 let route_params = RouteParameters::from_payment_params_and_value(
6510                         payment_params, 100_000_000);
6511                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6512                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6513                 assert_eq!(route.paths.len(), 2);
6514                 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6515                         (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6516         }
6517
6518         #[cfg(not(feature = "no-std"))]
6519         pub(super) fn random_init_seed() -> u64 {
6520                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6521                 use core::hash::{BuildHasher, Hasher};
6522                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6523                 println!("Using seed of {}", seed);
6524                 seed
6525         }
6526
6527         #[test]
6528         #[cfg(not(feature = "no-std"))]
6529         fn generate_routes() {
6530                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6531
6532                 let logger = ln_test_utils::TestLogger::new();
6533                 let graph = match super::bench_utils::read_network_graph(&logger) {
6534                         Ok(f) => f,
6535                         Err(e) => {
6536                                 eprintln!("{}", e);
6537                                 return;
6538                         },
6539                 };
6540
6541                 let params = ProbabilisticScoringFeeParameters::default();
6542                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6543                 let features = super::Bolt11InvoiceFeatures::empty();
6544
6545                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
6546         }
6547
6548         #[test]
6549         #[cfg(not(feature = "no-std"))]
6550         fn generate_routes_mpp() {
6551                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6552
6553                 let logger = ln_test_utils::TestLogger::new();
6554                 let graph = match super::bench_utils::read_network_graph(&logger) {
6555                         Ok(f) => f,
6556                         Err(e) => {
6557                                 eprintln!("{}", e);
6558                                 return;
6559                         },
6560                 };
6561
6562                 let params = ProbabilisticScoringFeeParameters::default();
6563                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6564                 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6565
6566                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
6567         }
6568
6569         #[test]
6570         #[cfg(not(feature = "no-std"))]
6571         fn generate_large_mpp_routes() {
6572                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6573
6574                 let logger = ln_test_utils::TestLogger::new();
6575                 let graph = match super::bench_utils::read_network_graph(&logger) {
6576                         Ok(f) => f,
6577                         Err(e) => {
6578                                 eprintln!("{}", e);
6579                                 return;
6580                         },
6581                 };
6582
6583                 let params = ProbabilisticScoringFeeParameters::default();
6584                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6585                 let features = channelmanager::provided_invoice_features(&UserConfig::default());
6586
6587                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 1_000_000, 2);
6588         }
6589
6590         #[test]
6591         fn honors_manual_penalties() {
6592                 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6593                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6594
6595                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6596                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6597
6598                 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6599                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6600
6601                 // First check set manual penalties are returned by the scorer.
6602                 let usage = ChannelUsage {
6603                         amount_msat: 0,
6604                         inflight_htlc_msat: 0,
6605                         effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6606                 };
6607                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6608                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6609                 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6610
6611                 // Then check we can get a normal route
6612                 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6613                 let route_params = RouteParameters::from_payment_params_and_value(
6614                         payment_params, 100);
6615                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6616                         Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6617                 assert!(route.is_ok());
6618
6619                 // Then check that we can't get a route if we ban an intermediate node.
6620                 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6621                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6622                         Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6623                 assert!(route.is_err());
6624
6625                 // Finally make sure we can route again, when we remove the ban.
6626                 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6627                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6628                         Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
6629                 assert!(route.is_ok());
6630         }
6631
6632         #[test]
6633         fn abide_by_route_hint_max_htlc() {
6634                 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6635                 // params in the final route.
6636                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6637                 let netgraph = network_graph.read_only();
6638                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6639                 let scorer = ln_test_utils::TestScorer::new();
6640                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6641                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6642                 let config = UserConfig::default();
6643
6644                 let max_htlc_msat = 50_000;
6645                 let route_hint_1 = RouteHint(vec![RouteHintHop {
6646                         src_node_id: nodes[2],
6647                         short_channel_id: 42,
6648                         fees: RoutingFees {
6649                                 base_msat: 100,
6650                                 proportional_millionths: 0,
6651                         },
6652                         cltv_expiry_delta: 10,
6653                         htlc_minimum_msat: None,
6654                         htlc_maximum_msat: Some(max_htlc_msat),
6655                 }]);
6656                 let dest_node_id = ln_test_utils::pubkey(42);
6657                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6658                         .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6659                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6660
6661                 // Make sure we'll error if our route hints don't have enough liquidity according to their
6662                 // htlc_maximum_msat.
6663                 let mut route_params = RouteParameters::from_payment_params_and_value(
6664                         payment_params, max_htlc_msat + 1);
6665                 route_params.max_total_routing_fee_msat = None;
6666                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6667                         &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
6668                         &random_seed_bytes)
6669                 {
6670                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
6671                 } else { panic!(); }
6672
6673                 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6674                 let mut route_hint_2 = route_hint_1.clone();
6675                 route_hint_2.0[0].short_channel_id = 43;
6676                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6677                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6678                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6679                 let mut route_params = RouteParameters::from_payment_params_and_value(
6680                         payment_params, max_htlc_msat + 1);
6681                 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
6682                 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
6683                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6684                 assert_eq!(route.paths.len(), 2);
6685                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6686                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6687         }
6688
6689         #[test]
6690         fn direct_channel_to_hints_with_max_htlc() {
6691                 // Check that if we have a first hop channel peer that's connected to multiple provided route
6692                 // hints, that we properly split the payment between the route hints if needed.
6693                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6694                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6695                 let scorer = ln_test_utils::TestScorer::new();
6696                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6697                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6698                 let config = UserConfig::default();
6699
6700                 let our_node_id = ln_test_utils::pubkey(42);
6701                 let intermed_node_id = ln_test_utils::pubkey(43);
6702                 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6703
6704                 let amt_msat = 900_000;
6705                 let max_htlc_msat = 500_000;
6706                 let route_hint_1 = RouteHint(vec![RouteHintHop {
6707                         src_node_id: intermed_node_id,
6708                         short_channel_id: 44,
6709                         fees: RoutingFees {
6710                                 base_msat: 100,
6711                                 proportional_millionths: 0,
6712                         },
6713                         cltv_expiry_delta: 10,
6714                         htlc_minimum_msat: None,
6715                         htlc_maximum_msat: Some(max_htlc_msat),
6716                 }, RouteHintHop {
6717                         src_node_id: intermed_node_id,
6718                         short_channel_id: 45,
6719                         fees: RoutingFees {
6720                                 base_msat: 100,
6721                                 proportional_millionths: 0,
6722                         },
6723                         cltv_expiry_delta: 10,
6724                         htlc_minimum_msat: None,
6725                         // Check that later route hint max htlcs don't override earlier ones
6726                         htlc_maximum_msat: Some(max_htlc_msat - 50),
6727                 }]);
6728                 let mut route_hint_2 = route_hint_1.clone();
6729                 route_hint_2.0[0].short_channel_id = 46;
6730                 route_hint_2.0[1].short_channel_id = 47;
6731                 let dest_node_id = ln_test_utils::pubkey(44);
6732                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6733                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6734                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6735
6736                 let route_params = RouteParameters::from_payment_params_and_value(
6737                         payment_params, amt_msat);
6738                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6739                         Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6740                         &Default::default(), &random_seed_bytes).unwrap();
6741                 assert_eq!(route.paths.len(), 2);
6742                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6743                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6744                 assert_eq!(route.get_total_amount(), amt_msat);
6745
6746                 // Re-run but with two first hop channels connected to the same route hint peers that must be
6747                 // split between.
6748                 let first_hops = vec![
6749                         get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6750                         get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6751                 ];
6752                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6753                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6754                         &Default::default(), &random_seed_bytes).unwrap();
6755                 assert_eq!(route.paths.len(), 2);
6756                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6757                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6758                 assert_eq!(route.get_total_amount(), amt_msat);
6759
6760                 // Make sure this works for blinded route hints.
6761                 let blinded_path = BlindedPath {
6762                         introduction_node_id: intermed_node_id,
6763                         blinding_point: ln_test_utils::pubkey(42),
6764                         blinded_hops: vec![
6765                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
6766                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
6767                         ],
6768                 };
6769                 let blinded_payinfo = BlindedPayInfo {
6770                         fee_base_msat: 100,
6771                         fee_proportional_millionths: 0,
6772                         htlc_minimum_msat: 1,
6773                         htlc_maximum_msat: max_htlc_msat,
6774                         cltv_expiry_delta: 10,
6775                         features: BlindedHopFeatures::empty(),
6776                 };
6777                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
6778                 let payment_params = PaymentParameters::blinded(vec![
6779                         (blinded_payinfo.clone(), blinded_path.clone()),
6780                         (blinded_payinfo.clone(), blinded_path.clone())])
6781                         .with_bolt12_features(bolt12_features).unwrap();
6782                 let route_params = RouteParameters::from_payment_params_and_value(
6783                         payment_params, amt_msat);
6784                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
6785                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
6786                         &Default::default(), &random_seed_bytes).unwrap();
6787                 assert_eq!(route.paths.len(), 2);
6788                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6789                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6790                 assert_eq!(route.get_total_amount(), amt_msat);
6791         }
6792
6793         #[test]
6794         fn blinded_route_ser() {
6795                 let blinded_path_1 = BlindedPath {
6796                         introduction_node_id: ln_test_utils::pubkey(42),
6797                         blinding_point: ln_test_utils::pubkey(43),
6798                         blinded_hops: vec![
6799                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6800                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6801                         ],
6802                 };
6803                 let blinded_path_2 = BlindedPath {
6804                         introduction_node_id: ln_test_utils::pubkey(46),
6805                         blinding_point: ln_test_utils::pubkey(47),
6806                         blinded_hops: vec![
6807                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6808                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6809                         ],
6810                 };
6811                 // (De)serialize a Route with 1 blinded path out of two total paths.
6812                 let mut route = Route { paths: vec![Path {
6813                         hops: vec![RouteHop {
6814                                 pubkey: ln_test_utils::pubkey(50),
6815                                 node_features: NodeFeatures::empty(),
6816                                 short_channel_id: 42,
6817                                 channel_features: ChannelFeatures::empty(),
6818                                 fee_msat: 100,
6819                                 cltv_expiry_delta: 0,
6820                                 maybe_announced_channel: true,
6821                         }],
6822                         blinded_tail: Some(BlindedTail {
6823                                 hops: blinded_path_1.blinded_hops,
6824                                 blinding_point: blinded_path_1.blinding_point,
6825                                 excess_final_cltv_expiry_delta: 40,
6826                                 final_value_msat: 100,
6827                         })}, Path {
6828                         hops: vec![RouteHop {
6829                                 pubkey: ln_test_utils::pubkey(51),
6830                                 node_features: NodeFeatures::empty(),
6831                                 short_channel_id: 43,
6832                                 channel_features: ChannelFeatures::empty(),
6833                                 fee_msat: 100,
6834                                 cltv_expiry_delta: 0,
6835                                 maybe_announced_channel: true,
6836                         }], blinded_tail: None }],
6837                         route_params: None,
6838                 };
6839                 let encoded_route = route.encode();
6840                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6841                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6842                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6843
6844                 // (De)serialize a Route with two paths, each containing a blinded tail.
6845                 route.paths[1].blinded_tail = Some(BlindedTail {
6846                         hops: blinded_path_2.blinded_hops,
6847                         blinding_point: blinded_path_2.blinding_point,
6848                         excess_final_cltv_expiry_delta: 41,
6849                         final_value_msat: 101,
6850                 });
6851                 let encoded_route = route.encode();
6852                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6853                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6854                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6855         }
6856
6857         #[test]
6858         fn blinded_path_inflight_processing() {
6859                 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6860                 // account for the blinded tail's final amount_msat.
6861                 let mut inflight_htlcs = InFlightHtlcs::new();
6862                 let blinded_path = BlindedPath {
6863                         introduction_node_id: ln_test_utils::pubkey(43),
6864                         blinding_point: ln_test_utils::pubkey(48),
6865                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6866                 };
6867                 let path = Path {
6868                         hops: vec![RouteHop {
6869                                 pubkey: ln_test_utils::pubkey(42),
6870                                 node_features: NodeFeatures::empty(),
6871                                 short_channel_id: 42,
6872                                 channel_features: ChannelFeatures::empty(),
6873                                 fee_msat: 100,
6874                                 cltv_expiry_delta: 0,
6875                                 maybe_announced_channel: false,
6876                         },
6877                         RouteHop {
6878                                 pubkey: blinded_path.introduction_node_id,
6879                                 node_features: NodeFeatures::empty(),
6880                                 short_channel_id: 43,
6881                                 channel_features: ChannelFeatures::empty(),
6882                                 fee_msat: 1,
6883                                 cltv_expiry_delta: 0,
6884                                 maybe_announced_channel: false,
6885                         }],
6886                         blinded_tail: Some(BlindedTail {
6887                                 hops: blinded_path.blinded_hops,
6888                                 blinding_point: blinded_path.blinding_point,
6889                                 excess_final_cltv_expiry_delta: 0,
6890                                 final_value_msat: 200,
6891                         }),
6892                 };
6893                 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6894                 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6895                 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6896         }
6897
6898         #[test]
6899         fn blinded_path_cltv_shadow_offset() {
6900                 // Make sure we add a shadow offset when sending to blinded paths.
6901                 let blinded_path = BlindedPath {
6902                         introduction_node_id: ln_test_utils::pubkey(43),
6903                         blinding_point: ln_test_utils::pubkey(44),
6904                         blinded_hops: vec![
6905                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6906                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6907                         ],
6908                 };
6909                 let mut route = Route { paths: vec![Path {
6910                         hops: vec![RouteHop {
6911                                 pubkey: ln_test_utils::pubkey(42),
6912                                 node_features: NodeFeatures::empty(),
6913                                 short_channel_id: 42,
6914                                 channel_features: ChannelFeatures::empty(),
6915                                 fee_msat: 100,
6916                                 cltv_expiry_delta: 0,
6917                                 maybe_announced_channel: false,
6918                         },
6919                         RouteHop {
6920                                 pubkey: blinded_path.introduction_node_id,
6921                                 node_features: NodeFeatures::empty(),
6922                                 short_channel_id: 43,
6923                                 channel_features: ChannelFeatures::empty(),
6924                                 fee_msat: 1,
6925                                 cltv_expiry_delta: 0,
6926                                 maybe_announced_channel: false,
6927                         }
6928                         ],
6929                         blinded_tail: Some(BlindedTail {
6930                                 hops: blinded_path.blinded_hops,
6931                                 blinding_point: blinded_path.blinding_point,
6932                                 excess_final_cltv_expiry_delta: 0,
6933                                 final_value_msat: 200,
6934                         }),
6935                 }], route_params: None};
6936
6937                 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6938                 let (_, network_graph, _, _, _) = build_line_graph();
6939                 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6940                 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6941                 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6942         }
6943
6944         #[test]
6945         fn simple_blinded_route_hints() {
6946                 do_simple_blinded_route_hints(1);
6947                 do_simple_blinded_route_hints(2);
6948                 do_simple_blinded_route_hints(3);
6949         }
6950
6951         fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
6952                 // Check that we can generate a route to a blinded path with the expected hops.
6953                 let (secp_ctx, network, _, _, logger) = build_graph();
6954                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6955                 let network_graph = network.read_only();
6956
6957                 let scorer = ln_test_utils::TestScorer::new();
6958                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6959                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6960
6961                 let mut blinded_path = BlindedPath {
6962                         introduction_node_id: nodes[2],
6963                         blinding_point: ln_test_utils::pubkey(42),
6964                         blinded_hops: Vec::with_capacity(num_blinded_hops),
6965                 };
6966                 for i in 0..num_blinded_hops {
6967                         blinded_path.blinded_hops.push(
6968                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
6969                         );
6970                 }
6971                 let blinded_payinfo = BlindedPayInfo {
6972                         fee_base_msat: 100,
6973                         fee_proportional_millionths: 500,
6974                         htlc_minimum_msat: 1000,
6975                         htlc_maximum_msat: 100_000_000,
6976                         cltv_expiry_delta: 15,
6977                         features: BlindedHopFeatures::empty(),
6978                 };
6979
6980                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
6981                 let route_params = RouteParameters::from_payment_params_and_value(
6982                         payment_params, 1001);
6983                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6984                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6985                 assert_eq!(route.paths.len(), 1);
6986                 assert_eq!(route.paths[0].hops.len(), 2);
6987
6988                 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
6989                 assert_eq!(tail.hops, blinded_path.blinded_hops);
6990                 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
6991                 assert_eq!(tail.final_value_msat, 1001);
6992
6993                 let final_hop = route.paths[0].hops.last().unwrap();
6994                 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
6995                 if tail.hops.len() > 1 {
6996                         assert_eq!(final_hop.fee_msat,
6997                                 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
6998                         assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
6999                 } else {
7000                         assert_eq!(final_hop.fee_msat, 0);
7001                         assert_eq!(final_hop.cltv_expiry_delta, 0);
7002                 }
7003         }
7004
7005         #[test]
7006         fn blinded_path_routing_errors() {
7007                 // Check that we can generate a route to a blinded path with the expected hops.
7008                 let (secp_ctx, network, _, _, logger) = build_graph();
7009                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7010                 let network_graph = network.read_only();
7011
7012                 let scorer = ln_test_utils::TestScorer::new();
7013                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7014                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7015
7016                 let mut invalid_blinded_path = BlindedPath {
7017                         introduction_node_id: nodes[2],
7018                         blinding_point: ln_test_utils::pubkey(42),
7019                         blinded_hops: vec![
7020                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7021                         ],
7022                 };
7023                 let blinded_payinfo = BlindedPayInfo {
7024                         fee_base_msat: 100,
7025                         fee_proportional_millionths: 500,
7026                         htlc_minimum_msat: 1000,
7027                         htlc_maximum_msat: 100_000_000,
7028                         cltv_expiry_delta: 15,
7029                         features: BlindedHopFeatures::empty(),
7030                 };
7031
7032                 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7033                 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7034                 let payment_params = PaymentParameters::blinded(vec![
7035                         (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7036                         (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7037                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7038                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7039                         &scorer, &Default::default(), &random_seed_bytes)
7040                 {
7041                         Err(LightningError { err, .. }) => {
7042                                 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7043                         },
7044                         _ => panic!("Expected error")
7045                 }
7046
7047                 invalid_blinded_path.introduction_node_id = our_id;
7048                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7049                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7050                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7051                         &Default::default(), &random_seed_bytes)
7052                 {
7053                         Err(LightningError { err, .. }) => {
7054                                 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7055                         },
7056                         _ => panic!("Expected error")
7057                 }
7058
7059                 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7060                 invalid_blinded_path.blinded_hops.clear();
7061                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7062                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7063                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7064                         &Default::default(), &random_seed_bytes)
7065                 {
7066                         Err(LightningError { err, .. }) => {
7067                                 assert_eq!(err, "0-hop blinded path provided");
7068                         },
7069                         _ => panic!("Expected error")
7070                 }
7071         }
7072
7073         #[test]
7074         fn matching_intro_node_paths_provided() {
7075                 // Check that if multiple blinded paths with the same intro node are provided in payment
7076                 // parameters, we'll return the correct paths in the resulting MPP route.
7077                 let (secp_ctx, network, _, _, logger) = build_graph();
7078                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7079                 let network_graph = network.read_only();
7080
7081                 let scorer = ln_test_utils::TestScorer::new();
7082                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7083                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7084                 let config = UserConfig::default();
7085
7086                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7087                 let blinded_path_1 = BlindedPath {
7088                         introduction_node_id: nodes[2],
7089                         blinding_point: ln_test_utils::pubkey(42),
7090                         blinded_hops: vec![
7091                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7092                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7093                         ],
7094                 };
7095                 let blinded_payinfo_1 = BlindedPayInfo {
7096                         fee_base_msat: 0,
7097                         fee_proportional_millionths: 0,
7098                         htlc_minimum_msat: 0,
7099                         htlc_maximum_msat: 30_000,
7100                         cltv_expiry_delta: 0,
7101                         features: BlindedHopFeatures::empty(),
7102                 };
7103
7104                 let mut blinded_path_2 = blinded_path_1.clone();
7105                 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7106                 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7107                 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7108
7109                 let blinded_hints = vec![
7110                         (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7111                         (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7112                 ];
7113                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7114                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7115
7116                 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7117                 route_params.max_total_routing_fee_msat = Some(100_000);
7118                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7119                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
7120                 assert_eq!(route.paths.len(), 2);
7121                 let mut total_amount_paid_msat = 0;
7122                 for path in route.paths.into_iter() {
7123                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7124                         if let Some(bt) = &path.blinded_tail {
7125                                 assert_eq!(bt.blinding_point,
7126                                         blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7127                                                 .map(|(_, bp)| bp.blinding_point).unwrap());
7128                         } else { panic!(); }
7129                         total_amount_paid_msat += path.final_value_msat();
7130                 }
7131                 assert_eq!(total_amount_paid_msat, 100_000);
7132         }
7133
7134         #[test]
7135         fn direct_to_intro_node() {
7136                 // This previously caused a debug panic in the router when asserting
7137                 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7138                 // direct channels we failed to account for the fee charged for use of the blinded path.
7139
7140                 // Build a graph:
7141                 // node0 -1(1)2 - node1
7142                 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7143                 // doesn't account for the blinded path fee.
7144
7145                 let secp_ctx = Secp256k1::new();
7146                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7147                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7148                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7149                 let scorer = ln_test_utils::TestScorer::new();
7150                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7151                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7152
7153                 let amt_msat = 10_000_000;
7154                 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7155                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7156                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7157                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7158                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7159                         short_channel_id: 1,
7160                         timestamp: 1,
7161                         flags: 0,
7162                         cltv_expiry_delta: 42,
7163                         htlc_minimum_msat: 1_000,
7164                         htlc_maximum_msat: 10_000_000,
7165                         fee_base_msat: 800,
7166                         fee_proportional_millionths: 0,
7167                         excess_data: Vec::new()
7168                 });
7169                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7170                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7171                         short_channel_id: 1,
7172                         timestamp: 1,
7173                         flags: 1,
7174                         cltv_expiry_delta: 42,
7175                         htlc_minimum_msat: 1_000,
7176                         htlc_maximum_msat: 10_000_000,
7177                         fee_base_msat: 800,
7178                         fee_proportional_millionths: 0,
7179                         excess_data: Vec::new()
7180                 });
7181                 let first_hops = vec![
7182                         get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7183
7184                 let blinded_path = BlindedPath {
7185                         introduction_node_id: nodes[1],
7186                         blinding_point: ln_test_utils::pubkey(42),
7187                         blinded_hops: vec![
7188                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7189                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7190                         ],
7191                 };
7192                 let blinded_payinfo = BlindedPayInfo {
7193                         fee_base_msat: 1000,
7194                         fee_proportional_millionths: 0,
7195                         htlc_minimum_msat: 1000,
7196                         htlc_maximum_msat: MAX_VALUE_MSAT,
7197                         cltv_expiry_delta: 0,
7198                         features: BlindedHopFeatures::empty(),
7199                 };
7200                 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7201
7202                 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7203
7204                 let netgraph = network_graph.read_only();
7205                 let route_params = RouteParameters::from_payment_params_and_value(
7206                         payment_params.clone(), amt_msat);
7207                 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7208                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7209                         &Default::default(), &random_seed_bytes) {
7210                                 assert_eq!(err, "Failed to find a path to the given destination");
7211                 } else { panic!("Expected error") }
7212
7213                 // Sending an exact amount accounting for the blinded path fee works.
7214                 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7215                 let route_params = RouteParameters::from_payment_params_and_value(
7216                         payment_params, amt_minus_blinded_path_fee);
7217                 let route = get_route(&nodes[0], &route_params, &netgraph,
7218                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7219                         &Default::default(), &random_seed_bytes).unwrap();
7220                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7221                 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7222         }
7223
7224         #[test]
7225         fn direct_to_matching_intro_nodes() {
7226                 // This previously caused us to enter `unreachable` code in the following situation:
7227                 // 1. We add a route candidate for intro_node contributing a high amount
7228                 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7229                 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7230                 //    amount, and update our route candidate for intro_node for the lower amount
7231                 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7232                 //    lower contribution amount, but fail (this was previously caused by failure to account for
7233                 //    blinded path fees when adding first_hop<>intro_node candidates)
7234                 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7235                 //    candidate still thinks its path is contributing the original higher amount. This caused us
7236                 //    to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7237                 //    larger amount
7238                 let secp_ctx = Secp256k1::new();
7239                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7240                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7241                 let scorer = ln_test_utils::TestScorer::new();
7242                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7243                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7244                 let config = UserConfig::default();
7245
7246                 // Values are taken from the fuzz input that uncovered this panic.
7247                 let amt_msat = 21_7020_5185_1403_2640;
7248                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7249                 let first_hops = vec![
7250                         get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7251                                 18446744073709551615)];
7252
7253                 let blinded_path = BlindedPath {
7254                         introduction_node_id: nodes[1],
7255                         blinding_point: ln_test_utils::pubkey(42),
7256                         blinded_hops: vec![
7257                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7258                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7259                         ],
7260                 };
7261                 let blinded_payinfo = BlindedPayInfo {
7262                         fee_base_msat: 5046_2720,
7263                         fee_proportional_millionths: 0,
7264                         htlc_minimum_msat: 4503_5996_2737_0496,
7265                         htlc_maximum_msat: 45_0359_9627_3704_9600,
7266                         cltv_expiry_delta: 0,
7267                         features: BlindedHopFeatures::empty(),
7268                 };
7269                 let mut blinded_hints = vec![
7270                         (blinded_payinfo.clone(), blinded_path.clone()),
7271                         (blinded_payinfo.clone(), blinded_path.clone()),
7272                 ];
7273                 blinded_hints[1].0.fee_base_msat = 419_4304;
7274                 blinded_hints[1].0.fee_proportional_millionths = 257;
7275                 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7276                 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7277                 blinded_hints[1].0.cltv_expiry_delta = 0;
7278
7279                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7280                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7281                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7282
7283                 let netgraph = network_graph.read_only();
7284                 let route_params = RouteParameters::from_payment_params_and_value(
7285                         payment_params, amt_msat);
7286                 let route = get_route(&nodes[0], &route_params, &netgraph,
7287                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7288                         &Default::default(), &random_seed_bytes).unwrap();
7289                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7290                 assert_eq!(route.get_total_amount(), amt_msat);
7291         }
7292
7293         #[test]
7294         fn we_are_intro_node_candidate_hops() {
7295                 // This previously led to a panic in the router because we'd generate a Path with only a
7296                 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7297                 // where the origin node is the intro node. We now fully disallow considering candidate hops
7298                 // where the origin node is the intro node.
7299                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7300                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7301                 let scorer = ln_test_utils::TestScorer::new();
7302                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7303                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7304                 let config = UserConfig::default();
7305
7306                 // Values are taken from the fuzz input that uncovered this panic.
7307                 let amt_msat = 21_7020_5185_1423_0019;
7308
7309                 let blinded_path = BlindedPath {
7310                         introduction_node_id: our_id,
7311                         blinding_point: ln_test_utils::pubkey(42),
7312                         blinded_hops: vec![
7313                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7314                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7315                         ],
7316                 };
7317                 let blinded_payinfo = BlindedPayInfo {
7318                         fee_base_msat: 5052_9027,
7319                         fee_proportional_millionths: 0,
7320                         htlc_minimum_msat: 21_7020_5185_1423_0019,
7321                         htlc_maximum_msat: 1844_6744_0737_0955_1615,
7322                         cltv_expiry_delta: 0,
7323                         features: BlindedHopFeatures::empty(),
7324                 };
7325                 let mut blinded_hints = vec![
7326                         (blinded_payinfo.clone(), blinded_path.clone()),
7327                         (blinded_payinfo.clone(), blinded_path.clone()),
7328                 ];
7329                 blinded_hints[1].1.introduction_node_id = nodes[6];
7330
7331                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7332                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7333                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7334
7335                 let netgraph = network_graph.read_only();
7336                 let route_params = RouteParameters::from_payment_params_and_value(
7337                         payment_params, amt_msat);
7338                 if let Err(LightningError { err, .. }) = get_route(
7339                         &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7340                 ) {
7341                         assert_eq!(err, "Failed to find a path to the given destination");
7342                 } else { panic!() }
7343         }
7344
7345         #[test]
7346         fn we_are_intro_node_bp_in_final_path_fee_calc() {
7347                 // This previously led to a debug panic in the router because we'd find an invalid Path with
7348                 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7349                 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7350                 // the payment, when it was intended to only include the final value of the payment.
7351                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7352                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7353                 let scorer = ln_test_utils::TestScorer::new();
7354                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7355                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7356                 let config = UserConfig::default();
7357
7358                 // Values are taken from the fuzz input that uncovered this panic.
7359                 let amt_msat = 21_7020_5185_1423_0019;
7360
7361                 let blinded_path = BlindedPath {
7362                         introduction_node_id: our_id,
7363                         blinding_point: ln_test_utils::pubkey(42),
7364                         blinded_hops: vec![
7365                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7366                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7367                         ],
7368                 };
7369                 let blinded_payinfo = BlindedPayInfo {
7370                         fee_base_msat: 10_4425_1395,
7371                         fee_proportional_millionths: 0,
7372                         htlc_minimum_msat: 21_7301_9934_9094_0931,
7373                         htlc_maximum_msat: 1844_6744_0737_0955_1615,
7374                         cltv_expiry_delta: 0,
7375                         features: BlindedHopFeatures::empty(),
7376                 };
7377                 let mut blinded_hints = vec![
7378                         (blinded_payinfo.clone(), blinded_path.clone()),
7379                         (blinded_payinfo.clone(), blinded_path.clone()),
7380                         (blinded_payinfo.clone(), blinded_path.clone()),
7381                 ];
7382                 blinded_hints[1].0.fee_base_msat = 5052_9027;
7383                 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7384                 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7385
7386                 blinded_hints[2].1.introduction_node_id = nodes[6];
7387
7388                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7389                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7390                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7391
7392                 let netgraph = network_graph.read_only();
7393                 let route_params = RouteParameters::from_payment_params_and_value(
7394                         payment_params, amt_msat);
7395                 if let Err(LightningError { err, .. }) = get_route(
7396                         &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7397                 ) {
7398                         assert_eq!(err, "Failed to find a path to the given destination");
7399                 } else { panic!() }
7400         }
7401
7402         #[test]
7403         fn min_htlc_overpay_violates_max_htlc() {
7404                 do_min_htlc_overpay_violates_max_htlc(true);
7405                 do_min_htlc_overpay_violates_max_htlc(false);
7406         }
7407         fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7408                 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7409                 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7410                 // to `targets` and build an invalid path with it, and subsquently hit a debug panic asserting
7411                 // that the used liquidity for a hop was less than its available liquidity limit.
7412                 let secp_ctx = Secp256k1::new();
7413                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7414                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7415                 let scorer = ln_test_utils::TestScorer::new();
7416                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7417                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7418                 let config = UserConfig::default();
7419
7420                 // Values are taken from the fuzz input that uncovered this panic.
7421                 let amt_msat = 7_4009_8048;
7422                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7423                 let first_hop_outbound_capacity = 2_7345_2000;
7424                 let first_hops = vec![get_channel_details(
7425                         Some(200), nodes[0], channelmanager::provided_init_features(&config),
7426                         first_hop_outbound_capacity
7427                 )];
7428
7429                 let base_fee = 1_6778_3453;
7430                 let htlc_min = 2_5165_8240;
7431                 let payment_params = if blinded_payee {
7432                         let blinded_path = BlindedPath {
7433                                 introduction_node_id: nodes[0],
7434                                 blinding_point: ln_test_utils::pubkey(42),
7435                                 blinded_hops: vec![
7436                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7437                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7438                                 ],
7439                         };
7440                         let blinded_payinfo = BlindedPayInfo {
7441                                 fee_base_msat: base_fee,
7442                                 fee_proportional_millionths: 0,
7443                                 htlc_minimum_msat: htlc_min,
7444                                 htlc_maximum_msat: htlc_min * 1000,
7445                                 cltv_expiry_delta: 0,
7446                                 features: BlindedHopFeatures::empty(),
7447                         };
7448                         let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7449                         PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7450                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
7451                 } else {
7452                         let route_hint = RouteHint(vec![RouteHintHop {
7453                                 src_node_id: nodes[0],
7454                                 short_channel_id: 42,
7455                                 fees: RoutingFees {
7456                                         base_msat: base_fee,
7457                                         proportional_millionths: 0,
7458                                 },
7459                                 cltv_expiry_delta: 10,
7460                                 htlc_minimum_msat: Some(htlc_min),
7461                                 htlc_maximum_msat: None,
7462                         }]);
7463
7464                         PaymentParameters::from_node_id(nodes[1], 42)
7465                                 .with_route_hints(vec![route_hint]).unwrap()
7466                                 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
7467                 };
7468
7469                 let netgraph = network_graph.read_only();
7470                 let route_params = RouteParameters::from_payment_params_and_value(
7471                         payment_params, amt_msat);
7472                 if let Err(LightningError { err, .. }) = get_route(
7473                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7474                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7475                 ) {
7476                         assert_eq!(err, "Failed to find a path to the given destination");
7477                 } else { panic!() }
7478         }
7479
7480         #[test]
7481         fn previously_used_liquidity_violates_max_htlc() {
7482                 do_previously_used_liquidity_violates_max_htlc(true);
7483                 do_previously_used_liquidity_violates_max_htlc(false);
7484
7485         }
7486         fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7487                 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7488                 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7489                 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7490                 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7491                 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7492                 let secp_ctx = Secp256k1::new();
7493                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7494                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7495                 let scorer = ln_test_utils::TestScorer::new();
7496                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7497                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7498                 let config = UserConfig::default();
7499
7500                 // Values are taken from the fuzz input that uncovered this panic.
7501                 let amt_msat = 52_4288;
7502                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7503                 let first_hops = vec![get_channel_details(
7504                         Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7505                 ), get_channel_details(
7506                         Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7507                 )];
7508
7509                 let base_fees = [0, 425_9840, 0, 0];
7510                 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7511                 let payment_params = if blinded_payee {
7512                         let blinded_path = BlindedPath {
7513                                 introduction_node_id: nodes[0],
7514                                 blinding_point: ln_test_utils::pubkey(42),
7515                                 blinded_hops: vec![
7516                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7517                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7518                                 ],
7519                         };
7520                         let mut blinded_hints = Vec::new();
7521                         for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7522                                 blinded_hints.push((BlindedPayInfo {
7523                                         fee_base_msat: *base_fee,
7524                                         fee_proportional_millionths: 0,
7525                                         htlc_minimum_msat: *htlc_min,
7526                                         htlc_maximum_msat: htlc_min * 100,
7527                                         cltv_expiry_delta: 10,
7528                                         features: BlindedHopFeatures::empty(),
7529                                 }, blinded_path.clone()));
7530                         }
7531                         let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7532                         PaymentParameters::blinded(blinded_hints.clone())
7533                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
7534                 } else {
7535                         let mut route_hints = Vec::new();
7536                         for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7537                                 route_hints.push(RouteHint(vec![RouteHintHop {
7538                                         src_node_id: nodes[0],
7539                                         short_channel_id: 42 + idx as u64,
7540                                         fees: RoutingFees {
7541                                                 base_msat: *base_fee,
7542                                                 proportional_millionths: 0,
7543                                         },
7544                                         cltv_expiry_delta: 10,
7545                                         htlc_minimum_msat: Some(*htlc_min),
7546                                         htlc_maximum_msat: Some(htlc_min * 100),
7547                                 }]));
7548                         }
7549                         PaymentParameters::from_node_id(nodes[1], 42)
7550                                 .with_route_hints(route_hints).unwrap()
7551                                 .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
7552                 };
7553
7554                 let netgraph = network_graph.read_only();
7555                 let route_params = RouteParameters::from_payment_params_and_value(
7556                         payment_params, amt_msat);
7557
7558                 let route = get_route(
7559                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7560                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
7561                 ).unwrap();
7562                 assert_eq!(route.paths.len(), 1);
7563                 assert_eq!(route.get_total_amount(), amt_msat);
7564         }
7565
7566         #[test]
7567         fn candidate_path_min() {
7568                 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
7569                 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
7570                 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
7571                 // would add a connecting first_hop node that did not have enough contribution amount, leading
7572                 // to a debug panic upon invalid path construction.
7573                 let secp_ctx = Secp256k1::new();
7574                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7575                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7576                 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
7577                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7578                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7579                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7580                 let config = UserConfig::default();
7581
7582                 // Values are taken from the fuzz input that uncovered this panic.
7583                 let amt_msat = 7_4009_8048;
7584                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7585                 let first_hops = vec![get_channel_details(
7586                         Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
7587                 )];
7588
7589                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
7590                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7591                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
7592                         short_channel_id: 6,
7593                         timestamp: 1,
7594                         flags: 0,
7595                         cltv_expiry_delta: (6 << 4) | 0,
7596                         htlc_minimum_msat: 0,
7597                         htlc_maximum_msat: MAX_VALUE_MSAT,
7598                         fee_base_msat: 0,
7599                         fee_proportional_millionths: 0,
7600                         excess_data: Vec::new()
7601                 });
7602                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
7603
7604                 let htlc_min = 2_5165_8240;
7605                 let blinded_hints = vec![
7606                         (BlindedPayInfo {
7607                                 fee_base_msat: 1_6778_3453,
7608                                 fee_proportional_millionths: 0,
7609                                 htlc_minimum_msat: htlc_min,
7610                                 htlc_maximum_msat: htlc_min * 100,
7611                                 cltv_expiry_delta: 10,
7612                                 features: BlindedHopFeatures::empty(),
7613                         }, BlindedPath {
7614                                 introduction_node_id: nodes[0],
7615                                 blinding_point: ln_test_utils::pubkey(42),
7616                                 blinded_hops: vec![
7617                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7618                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7619                                 ],
7620                         })
7621                 ];
7622                 let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7623                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7624                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7625                 let route_params = RouteParameters::from_payment_params_and_value(
7626                         payment_params, amt_msat);
7627                 let netgraph = network_graph.read_only();
7628
7629                 if let Err(LightningError { err, .. }) = get_route(
7630                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7631                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7632                         &random_seed_bytes
7633                 ) {
7634                         assert_eq!(err, "Failed to find a path to the given destination");
7635                 } else { panic!() }
7636         }
7637
7638         #[test]
7639         fn path_contribution_includes_min_htlc_overpay() {
7640                 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
7641                 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
7642                 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
7643                 // selection, both tested here.
7644                 let secp_ctx = Secp256k1::new();
7645                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7646                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7647                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
7648                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7649                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7650                 let config = UserConfig::default();
7651
7652                 // Values are taken from the fuzz input that uncovered this panic.
7653                 let amt_msat = 562_0000;
7654                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7655                 let first_hops = vec![
7656                         get_channel_details(
7657                                 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
7658                         ),
7659                 ];
7660
7661                 let htlc_mins = [49_0000, 1125_0000];
7662                 let payment_params = {
7663                         let blinded_path = BlindedPath {
7664                                 introduction_node_id: nodes[0],
7665                                 blinding_point: ln_test_utils::pubkey(42),
7666                                 blinded_hops: vec![
7667                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7668                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7669                                 ],
7670                         };
7671                         let mut blinded_hints = Vec::new();
7672                         for htlc_min in htlc_mins.iter() {
7673                                 blinded_hints.push((BlindedPayInfo {
7674                                         fee_base_msat: 0,
7675                                         fee_proportional_millionths: 0,
7676                                         htlc_minimum_msat: *htlc_min,
7677                                         htlc_maximum_msat: *htlc_min * 100,
7678                                         cltv_expiry_delta: 10,
7679                                         features: BlindedHopFeatures::empty(),
7680                                 }, blinded_path.clone()));
7681                         }
7682                         let bolt12_features: Bolt12InvoiceFeatures = channelmanager::provided_invoice_features(&config).to_context();
7683                         PaymentParameters::blinded(blinded_hints.clone())
7684                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
7685                 };
7686
7687                 let netgraph = network_graph.read_only();
7688                 let route_params = RouteParameters::from_payment_params_and_value(
7689                         payment_params, amt_msat);
7690                 let route = get_route(
7691                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7692                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
7693                         &random_seed_bytes
7694                 ).unwrap();
7695                 assert_eq!(route.paths.len(), 1);
7696                 assert_eq!(route.get_total_amount(), amt_msat);
7697         }
7698 }
7699
7700 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
7701 pub(crate) mod bench_utils {
7702         use super::*;
7703         use std::fs::File;
7704
7705         use bitcoin::hashes::Hash;
7706         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
7707
7708         use crate::chain::transaction::OutPoint;
7709         use crate::routing::scoring::ScoreUpdate;
7710         use crate::sign::{EntropySource, KeysManager};
7711         use crate::ln::ChannelId;
7712         use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
7713         use crate::ln::features::Bolt11InvoiceFeatures;
7714         use crate::routing::gossip::NetworkGraph;
7715         use crate::util::config::UserConfig;
7716         use crate::util::ser::ReadableArgs;
7717         use crate::util::test_utils::TestLogger;
7718
7719         /// Tries to open a network graph file, or panics with a URL to fetch it.
7720         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
7721                 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
7722                         .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
7723                         .or_else(|_| { // Fall back to guessing based on the binary location
7724                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
7725                                 let mut path = std::env::current_exe().unwrap();
7726                                 path.pop(); // lightning-...
7727                                 path.pop(); // deps
7728                                 path.pop(); // debug
7729                                 path.pop(); // target
7730                                 path.push("lightning");
7731                                 path.push("net_graph-2023-01-18.bin");
7732                                 File::open(path)
7733                         })
7734                         .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
7735                                 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
7736                                 let mut path = std::env::current_exe().unwrap();
7737                                 path.pop(); // bench...
7738                                 path.pop(); // deps
7739                                 path.pop(); // debug
7740                                 path.pop(); // target
7741                                 path.pop(); // bench
7742                                 path.push("lightning");
7743                                 path.push("net_graph-2023-01-18.bin");
7744                                 File::open(path)
7745                         })
7746                 .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");
7747                 #[cfg(require_route_graph_test)]
7748                 return Ok(res.unwrap());
7749                 #[cfg(not(require_route_graph_test))]
7750                 return res;
7751         }
7752
7753         pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
7754                 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
7755         }
7756
7757         pub(crate) fn payer_pubkey() -> PublicKey {
7758                 let secp_ctx = Secp256k1::new();
7759                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
7760         }
7761
7762         #[inline]
7763         pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
7764                 ChannelDetails {
7765                         channel_id: ChannelId::new_zero(),
7766                         counterparty: ChannelCounterparty {
7767                                 features: channelmanager::provided_init_features(&UserConfig::default()),
7768                                 node_id,
7769                                 unspendable_punishment_reserve: 0,
7770                                 forwarding_info: None,
7771                                 outbound_htlc_minimum_msat: None,
7772                                 outbound_htlc_maximum_msat: None,
7773                         },
7774                         funding_txo: Some(OutPoint {
7775                                 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
7776                         }),
7777                         channel_type: None,
7778                         short_channel_id: Some(1),
7779                         inbound_scid_alias: None,
7780                         outbound_scid_alias: None,
7781                         channel_value_satoshis: 10_000_000_000,
7782                         user_channel_id: 0,
7783                         outbound_capacity_msat: 10_000_000_000,
7784                         next_outbound_htlc_minimum_msat: 0,
7785                         next_outbound_htlc_limit_msat: 10_000_000_000,
7786                         inbound_capacity_msat: 0,
7787                         unspendable_punishment_reserve: None,
7788                         confirmations_required: None,
7789                         confirmations: None,
7790                         force_close_spend_delay: None,
7791                         is_outbound: true,
7792                         is_channel_ready: true,
7793                         is_usable: true,
7794                         is_public: true,
7795                         inbound_htlc_minimum_msat: None,
7796                         inbound_htlc_maximum_msat: None,
7797                         config: None,
7798                         feerate_sat_per_1000_weight: None,
7799                         channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
7800                 }
7801         }
7802
7803         pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
7804                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
7805                 starting_amount: u64, route_count: usize,
7806         ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
7807                 let payer = payer_pubkey();
7808                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7809                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7810
7811                 let nodes = graph.read_only().nodes().clone();
7812                 let mut route_endpoints = Vec::new();
7813                 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
7814                 // with some routes we picked being un-routable.
7815                 for _ in 0..route_count * 3 / 2 {
7816                         loop {
7817                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7818                                 let src = PublicKey::from_slice(nodes.unordered_keys()
7819                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7820                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7821                                 let dst = PublicKey::from_slice(nodes.unordered_keys()
7822                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
7823                                 let params = PaymentParameters::from_node_id(dst, 42)
7824                                         .with_bolt11_features(features.clone()).unwrap();
7825                                 let first_hop = first_hop(src);
7826                                 let amt_msat = starting_amount + seed % 1_000_000;
7827                                 let route_params = RouteParameters::from_payment_params_and_value(
7828                                         params.clone(), amt_msat);
7829                                 let path_exists =
7830                                         get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
7831                                                 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
7832                                 if path_exists {
7833                                         // ...and seed the scorer with success and failure data...
7834                                         seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7835                                         let mut score_amt = seed % 1_000_000_000;
7836                                         loop {
7837                                                 // Generate fail/success paths for a wider range of potential amounts with
7838                                                 // MPP enabled to give us a chance to apply penalties for more potential
7839                                                 // routes.
7840                                                 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
7841                                                 let params = PaymentParameters::from_node_id(dst, 42)
7842                                                         .with_bolt11_features(mpp_features).unwrap();
7843                                                 let route_params = RouteParameters::from_payment_params_and_value(
7844                                                         params.clone(), score_amt);
7845                                                 let route_res = get_route(&payer, &route_params, &graph.read_only(),
7846                                                         Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
7847                                                         &random_seed_bytes);
7848                                                 if let Ok(route) = route_res {
7849                                                         for path in route.paths {
7850                                                                 if seed & 0x80 == 0 {
7851                                                                         scorer.payment_path_successful(&path);
7852                                                                 } else {
7853                                                                         let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
7854                                                                         scorer.payment_path_failed(&path, short_channel_id);
7855                                                                 }
7856                                                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
7857                                                         }
7858                                                         break;
7859                                                 }
7860                                                 // If we couldn't find a path with a higer amount, reduce and try again.
7861                                                 score_amt /= 100;
7862                                         }
7863
7864                                         route_endpoints.push((first_hop, params, amt_msat));
7865                                         break;
7866                                 }
7867                         }
7868                 }
7869
7870                 // Because we've changed channel scores, it's possible we'll take different routes to the
7871                 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
7872                 // requires a too-high CLTV delta.
7873                 route_endpoints.retain(|(first_hop, params, amt_msat)| {
7874                         let route_params = RouteParameters::from_payment_params_and_value(
7875                                 params.clone(), *amt_msat);
7876                         get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
7877                                 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
7878                 });
7879                 route_endpoints.truncate(route_count);
7880                 assert_eq!(route_endpoints.len(), route_count);
7881                 route_endpoints
7882         }
7883 }
7884
7885 #[cfg(ldk_bench)]
7886 pub mod benches {
7887         use super::*;
7888         use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
7889         use crate::sign::{EntropySource, KeysManager};
7890         use crate::ln::channelmanager;
7891         use crate::ln::features::Bolt11InvoiceFeatures;
7892         use crate::routing::gossip::NetworkGraph;
7893         use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
7894         use crate::util::config::UserConfig;
7895         use crate::util::logger::{Logger, Record};
7896         use crate::util::test_utils::TestLogger;
7897
7898         use criterion::Criterion;
7899
7900         struct DummyLogger {}
7901         impl Logger for DummyLogger {
7902                 fn log(&self, _record: &Record) {}
7903         }
7904
7905         pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7906                 let logger = TestLogger::new();
7907                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7908                 let scorer = FixedPenaltyScorer::with_penalty(0);
7909                 generate_routes(bench, &network_graph, scorer, &Default::default(),
7910                         Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
7911         }
7912
7913         pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
7914                 let logger = TestLogger::new();
7915                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7916                 let scorer = FixedPenaltyScorer::with_penalty(0);
7917                 generate_routes(bench, &network_graph, scorer, &Default::default(),
7918                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7919                         "generate_mpp_routes_with_zero_penalty_scorer");
7920         }
7921
7922         pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7923                 let logger = TestLogger::new();
7924                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7925                 let params = ProbabilisticScoringFeeParameters::default();
7926                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7927                 generate_routes(bench, &network_graph, scorer, &params, Bolt11InvoiceFeatures::empty(), 0,
7928                         "generate_routes_with_probabilistic_scorer");
7929         }
7930
7931         pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7932                 let logger = TestLogger::new();
7933                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7934                 let params = ProbabilisticScoringFeeParameters::default();
7935                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7936                 generate_routes(bench, &network_graph, scorer, &params,
7937                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7938                         "generate_mpp_routes_with_probabilistic_scorer");
7939         }
7940
7941         pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
7942                 let logger = TestLogger::new();
7943                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7944                 let params = ProbabilisticScoringFeeParameters::default();
7945                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7946                 generate_routes(bench, &network_graph, scorer, &params,
7947                         channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7948                         "generate_large_mpp_routes_with_probabilistic_scorer");
7949         }
7950
7951         pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7952                 let logger = TestLogger::new();
7953                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7954                 let mut params = ProbabilisticScoringFeeParameters::default();
7955                 params.linear_success_probability = false;
7956                 let scorer = ProbabilisticScorer::new(
7957                         ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7958                 generate_routes(bench, &network_graph, scorer, &params,
7959                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7960                         "generate_routes_with_nonlinear_probabilistic_scorer");
7961         }
7962
7963         pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7964                 let logger = TestLogger::new();
7965                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7966                 let mut params = ProbabilisticScoringFeeParameters::default();
7967                 params.linear_success_probability = false;
7968                 let scorer = ProbabilisticScorer::new(
7969                         ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7970                 generate_routes(bench, &network_graph, scorer, &params,
7971                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
7972                         "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
7973         }
7974
7975         pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
7976                 let logger = TestLogger::new();
7977                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
7978                 let mut params = ProbabilisticScoringFeeParameters::default();
7979                 params.linear_success_probability = false;
7980                 let scorer = ProbabilisticScorer::new(
7981                         ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
7982                 generate_routes(bench, &network_graph, scorer, &params,
7983                         channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
7984                         "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
7985         }
7986
7987         fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
7988                 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
7989                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
7990                 bench_name: &'static str,
7991         ) {
7992                 let payer = bench_utils::payer_pubkey();
7993                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
7994                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7995
7996                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
7997                 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
7998
7999                 // ...then benchmark finding paths between the nodes we learned.
8000                 let mut idx = 0;
8001                 bench.bench_function(bench_name, |b| b.iter(|| {
8002                         let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8003                         let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8004                         assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8005                                 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());
8006                         idx += 1;
8007                 }));
8008         }
8009 }