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