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