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