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