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