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