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