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