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