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