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