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