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