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