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