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