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