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