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