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