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