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