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