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