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