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