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