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