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