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