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