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