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