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