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