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