Merge pull request #2847 from TheBlueMatt/2024-01-bindings-upstream
[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(HashMap::new()) }
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                 HashMap::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 = HashMap::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> = HashMap::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                 HashMap::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                 }
3298         }
3299
3300         #[test]
3301         fn simple_route_test() {
3302                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3303                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3304                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3305                 let scorer = ln_test_utils::TestScorer::new();
3306                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3307                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3308
3309                 // Simple route to 2 via 1
3310
3311                 let route_params = RouteParameters::from_payment_params_and_value(
3312                         payment_params.clone(), 0);
3313                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3314                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3315                         &Default::default(), &random_seed_bytes) {
3316                                 assert_eq!(err, "Cannot send a payment of 0 msat");
3317                 } else { panic!(); }
3318
3319                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3320                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3321                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3322                 assert_eq!(route.paths[0].hops.len(), 2);
3323
3324                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3325                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3326                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3327                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3328                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3329                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3330
3331                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3332                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3333                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3334                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3335                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3336                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3337         }
3338
3339         #[test]
3340         fn invalid_first_hop_test() {
3341                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3342                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3343                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3344                 let scorer = ln_test_utils::TestScorer::new();
3345                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3346                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3347
3348                 // Simple route to 2 via 1
3349
3350                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3351
3352                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3353                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3354                         &route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3355                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3356                                 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3357                 } else { panic!(); }
3358
3359                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3360                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3361                 assert_eq!(route.paths[0].hops.len(), 2);
3362         }
3363
3364         #[test]
3365         fn htlc_minimum_test() {
3366                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3367                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3368                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3369                 let scorer = ln_test_utils::TestScorer::new();
3370                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3371                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3372
3373                 // Simple route to 2 via 1
3374
3375                 // Disable other paths
3376                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3377                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3378                         short_channel_id: 12,
3379                         timestamp: 2,
3380                         flags: 2, // to disable
3381                         cltv_expiry_delta: 0,
3382                         htlc_minimum_msat: 0,
3383                         htlc_maximum_msat: MAX_VALUE_MSAT,
3384                         fee_base_msat: 0,
3385                         fee_proportional_millionths: 0,
3386                         excess_data: Vec::new()
3387                 });
3388                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3389                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3390                         short_channel_id: 3,
3391                         timestamp: 2,
3392                         flags: 2, // to disable
3393                         cltv_expiry_delta: 0,
3394                         htlc_minimum_msat: 0,
3395                         htlc_maximum_msat: MAX_VALUE_MSAT,
3396                         fee_base_msat: 0,
3397                         fee_proportional_millionths: 0,
3398                         excess_data: Vec::new()
3399                 });
3400                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3401                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3402                         short_channel_id: 13,
3403                         timestamp: 2,
3404                         flags: 2, // to disable
3405                         cltv_expiry_delta: 0,
3406                         htlc_minimum_msat: 0,
3407                         htlc_maximum_msat: MAX_VALUE_MSAT,
3408                         fee_base_msat: 0,
3409                         fee_proportional_millionths: 0,
3410                         excess_data: Vec::new()
3411                 });
3412                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3413                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3414                         short_channel_id: 6,
3415                         timestamp: 2,
3416                         flags: 2, // to disable
3417                         cltv_expiry_delta: 0,
3418                         htlc_minimum_msat: 0,
3419                         htlc_maximum_msat: MAX_VALUE_MSAT,
3420                         fee_base_msat: 0,
3421                         fee_proportional_millionths: 0,
3422                         excess_data: Vec::new()
3423                 });
3424                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3425                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3426                         short_channel_id: 7,
3427                         timestamp: 2,
3428                         flags: 2, // to disable
3429                         cltv_expiry_delta: 0,
3430                         htlc_minimum_msat: 0,
3431                         htlc_maximum_msat: MAX_VALUE_MSAT,
3432                         fee_base_msat: 0,
3433                         fee_proportional_millionths: 0,
3434                         excess_data: Vec::new()
3435                 });
3436
3437                 // Check against amount_to_transfer_over_msat.
3438                 // Set minimal HTLC of 200_000_000 msat.
3439                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3440                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3441                         short_channel_id: 2,
3442                         timestamp: 3,
3443                         flags: 0,
3444                         cltv_expiry_delta: 0,
3445                         htlc_minimum_msat: 200_000_000,
3446                         htlc_maximum_msat: MAX_VALUE_MSAT,
3447                         fee_base_msat: 0,
3448                         fee_proportional_millionths: 0,
3449                         excess_data: Vec::new()
3450                 });
3451
3452                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3453                 // be used.
3454                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3455                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3456                         short_channel_id: 4,
3457                         timestamp: 3,
3458                         flags: 0,
3459                         cltv_expiry_delta: 0,
3460                         htlc_minimum_msat: 0,
3461                         htlc_maximum_msat: 199_999_999,
3462                         fee_base_msat: 0,
3463                         fee_proportional_millionths: 0,
3464                         excess_data: Vec::new()
3465                 });
3466
3467                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3468                 let route_params = RouteParameters::from_payment_params_and_value(
3469                         payment_params, 199_999_999);
3470                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3471                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3472                         &Default::default(), &random_seed_bytes) {
3473                                 assert_eq!(err, "Failed to find a path to the given destination");
3474                 } else { panic!(); }
3475
3476                 // Lift the restriction on the first hop.
3477                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3478                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3479                         short_channel_id: 2,
3480                         timestamp: 4,
3481                         flags: 0,
3482                         cltv_expiry_delta: 0,
3483                         htlc_minimum_msat: 0,
3484                         htlc_maximum_msat: MAX_VALUE_MSAT,
3485                         fee_base_msat: 0,
3486                         fee_proportional_millionths: 0,
3487                         excess_data: Vec::new()
3488                 });
3489
3490                 // A payment above the minimum should pass
3491                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3492                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3493                 assert_eq!(route.paths[0].hops.len(), 2);
3494         }
3495
3496         #[test]
3497         fn htlc_minimum_overpay_test() {
3498                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3499                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3500                 let config = UserConfig::default();
3501                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3502                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3503                         .unwrap();
3504                 let scorer = ln_test_utils::TestScorer::new();
3505                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3506                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3507
3508                 // A route to node#2 via two paths.
3509                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3510                 // Thus, they can't send 60 without overpaying.
3511                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3512                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3513                         short_channel_id: 2,
3514                         timestamp: 2,
3515                         flags: 0,
3516                         cltv_expiry_delta: 0,
3517                         htlc_minimum_msat: 35_000,
3518                         htlc_maximum_msat: 40_000,
3519                         fee_base_msat: 0,
3520                         fee_proportional_millionths: 0,
3521                         excess_data: Vec::new()
3522                 });
3523                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3524                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3525                         short_channel_id: 12,
3526                         timestamp: 3,
3527                         flags: 0,
3528                         cltv_expiry_delta: 0,
3529                         htlc_minimum_msat: 35_000,
3530                         htlc_maximum_msat: 40_000,
3531                         fee_base_msat: 0,
3532                         fee_proportional_millionths: 0,
3533                         excess_data: Vec::new()
3534                 });
3535
3536                 // Make 0 fee.
3537                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3538                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3539                         short_channel_id: 13,
3540                         timestamp: 2,
3541                         flags: 0,
3542                         cltv_expiry_delta: 0,
3543                         htlc_minimum_msat: 0,
3544                         htlc_maximum_msat: MAX_VALUE_MSAT,
3545                         fee_base_msat: 0,
3546                         fee_proportional_millionths: 0,
3547                         excess_data: Vec::new()
3548                 });
3549                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3550                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3551                         short_channel_id: 4,
3552                         timestamp: 2,
3553                         flags: 0,
3554                         cltv_expiry_delta: 0,
3555                         htlc_minimum_msat: 0,
3556                         htlc_maximum_msat: MAX_VALUE_MSAT,
3557                         fee_base_msat: 0,
3558                         fee_proportional_millionths: 0,
3559                         excess_data: Vec::new()
3560                 });
3561
3562                 // Disable other paths
3563                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3564                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3565                         short_channel_id: 1,
3566                         timestamp: 3,
3567                         flags: 2, // to disable
3568                         cltv_expiry_delta: 0,
3569                         htlc_minimum_msat: 0,
3570                         htlc_maximum_msat: MAX_VALUE_MSAT,
3571                         fee_base_msat: 0,
3572                         fee_proportional_millionths: 0,
3573                         excess_data: Vec::new()
3574                 });
3575
3576                 let mut route_params = RouteParameters::from_payment_params_and_value(
3577                         payment_params.clone(), 60_000);
3578                 route_params.max_total_routing_fee_msat = Some(15_000);
3579                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3580                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3581                 // Overpay fees to hit htlc_minimum_msat.
3582                 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
3583                 // TODO: this could be better balanced to overpay 10k and not 15k.
3584                 assert_eq!(overpaid_fees, 15_000);
3585
3586                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
3587                 // while taking even more fee to match htlc_minimum_msat.
3588                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3589                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3590                         short_channel_id: 12,
3591                         timestamp: 4,
3592                         flags: 0,
3593                         cltv_expiry_delta: 0,
3594                         htlc_minimum_msat: 65_000,
3595                         htlc_maximum_msat: 80_000,
3596                         fee_base_msat: 0,
3597                         fee_proportional_millionths: 0,
3598                         excess_data: Vec::new()
3599                 });
3600                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3601                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3602                         short_channel_id: 2,
3603                         timestamp: 3,
3604                         flags: 0,
3605                         cltv_expiry_delta: 0,
3606                         htlc_minimum_msat: 0,
3607                         htlc_maximum_msat: MAX_VALUE_MSAT,
3608                         fee_base_msat: 0,
3609                         fee_proportional_millionths: 0,
3610                         excess_data: Vec::new()
3611                 });
3612                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3613                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3614                         short_channel_id: 4,
3615                         timestamp: 4,
3616                         flags: 0,
3617                         cltv_expiry_delta: 0,
3618                         htlc_minimum_msat: 0,
3619                         htlc_maximum_msat: MAX_VALUE_MSAT,
3620                         fee_base_msat: 0,
3621                         fee_proportional_millionths: 100_000,
3622                         excess_data: Vec::new()
3623                 });
3624
3625                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3626                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3627                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
3628                 assert_eq!(route.paths.len(), 1);
3629                 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
3630                 let fees = route.paths[0].hops[0].fee_msat;
3631                 assert_eq!(fees, 5_000);
3632
3633                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
3634                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3635                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3636                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
3637                 // the other channel.
3638                 assert_eq!(route.paths.len(), 1);
3639                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3640                 let fees = route.paths[0].hops[0].fee_msat;
3641                 assert_eq!(fees, 5_000);
3642         }
3643
3644         #[test]
3645         fn htlc_minimum_recipient_overpay_test() {
3646                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3647                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3648                 let config = UserConfig::default();
3649                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
3650                 let scorer = ln_test_utils::TestScorer::new();
3651                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3652                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3653
3654                 // Route to node2 over a single path which requires overpaying the recipient themselves.
3655
3656                 // First disable all paths except the us -> node1 -> node2 path
3657                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3658                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3659                         short_channel_id: 13,
3660                         timestamp: 2,
3661                         flags: 3,
3662                         cltv_expiry_delta: 0,
3663                         htlc_minimum_msat: 0,
3664                         htlc_maximum_msat: 0,
3665                         fee_base_msat: 0,
3666                         fee_proportional_millionths: 0,
3667                         excess_data: Vec::new()
3668                 });
3669
3670                 // Set channel 4 to free but with a high htlc_minimum_msat
3671                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3672                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3673                         short_channel_id: 4,
3674                         timestamp: 2,
3675                         flags: 0,
3676                         cltv_expiry_delta: 0,
3677                         htlc_minimum_msat: 15_000,
3678                         htlc_maximum_msat: MAX_VALUE_MSAT,
3679                         fee_base_msat: 0,
3680                         fee_proportional_millionths: 0,
3681                         excess_data: Vec::new()
3682                 });
3683
3684                 // Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
3685                 // is overrun. Note that the fees are actually calculated on 3*payment amount as that's
3686                 // what we try to find a route for, so this test only just happens to work out to exactly
3687                 // the fee limit.
3688                 let mut route_params = RouteParameters::from_payment_params_and_value(
3689                         payment_params.clone(), 5_000);
3690                 route_params.max_total_routing_fee_msat = Some(9_999);
3691                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3692                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3693                         &Default::default(), &random_seed_bytes) {
3694                                 assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
3695                 } else { panic!(); }
3696
3697                 let mut route_params = RouteParameters::from_payment_params_and_value(
3698                         payment_params.clone(), 5_000);
3699                 route_params.max_total_routing_fee_msat = Some(10_000);
3700                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3701                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3702                 assert_eq!(route.get_total_fees(), 10_000);
3703         }
3704
3705         #[test]
3706         fn disable_channels_test() {
3707                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3708                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3709                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3710                 let scorer = ln_test_utils::TestScorer::new();
3711                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3712                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3713
3714                 // // Disable channels 4 and 12 by flags=2
3715                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3716                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3717                         short_channel_id: 4,
3718                         timestamp: 2,
3719                         flags: 2, // to disable
3720                         cltv_expiry_delta: 0,
3721                         htlc_minimum_msat: 0,
3722                         htlc_maximum_msat: MAX_VALUE_MSAT,
3723                         fee_base_msat: 0,
3724                         fee_proportional_millionths: 0,
3725                         excess_data: Vec::new()
3726                 });
3727                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3728                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3729                         short_channel_id: 12,
3730                         timestamp: 2,
3731                         flags: 2, // to disable
3732                         cltv_expiry_delta: 0,
3733                         htlc_minimum_msat: 0,
3734                         htlc_maximum_msat: MAX_VALUE_MSAT,
3735                         fee_base_msat: 0,
3736                         fee_proportional_millionths: 0,
3737                         excess_data: Vec::new()
3738                 });
3739
3740                 // If all the channels require some features we don't understand, route should fail
3741                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3742                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3743                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3744                         &Default::default(), &random_seed_bytes) {
3745                                 assert_eq!(err, "Failed to find a path to the given destination");
3746                 } else { panic!(); }
3747
3748                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3749                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3750                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3751                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3752                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3753                         &Default::default(), &random_seed_bytes).unwrap();
3754                 assert_eq!(route.paths[0].hops.len(), 2);
3755
3756                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3757                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3758                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3759                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3760                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3761                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3762
3763                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3764                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3765                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3766                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3767                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3768                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3769         }
3770
3771         #[test]
3772         fn disable_node_test() {
3773                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3774                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3775                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3776                 let scorer = ln_test_utils::TestScorer::new();
3777                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3778                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3779
3780                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3781                 let mut unknown_features = NodeFeatures::empty();
3782                 unknown_features.set_unknown_feature_required();
3783                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3784                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3785                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3786
3787                 // If all nodes require some features we don't understand, route should fail
3788                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3789                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3790                         &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3791                         &Default::default(), &random_seed_bytes) {
3792                                 assert_eq!(err, "Failed to find a path to the given destination");
3793                 } else { panic!(); }
3794
3795                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3796                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3797                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3798                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3799                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3800                         &Default::default(), &random_seed_bytes).unwrap();
3801                 assert_eq!(route.paths[0].hops.len(), 2);
3802
3803                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3804                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3805                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3806                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3807                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3808                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3809
3810                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3811                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3812                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3813                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3814                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3815                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3816
3817                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3818                 // naively) assume that the user checked the feature bits on the invoice, which override
3819                 // the node_announcement.
3820         }
3821
3822         #[test]
3823         fn our_chans_test() {
3824                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3825                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3826                 let scorer = ln_test_utils::TestScorer::new();
3827                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3828                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3829
3830                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3831                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3832                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3833                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3834                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3835                 assert_eq!(route.paths[0].hops.len(), 3);
3836
3837                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3838                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3839                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3840                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3841                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3842                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3843
3844                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3845                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3846                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3847                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3848                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3849                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3850
3851                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3852                 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3853                 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3854                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3855                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3856                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3857
3858                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3859                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3860                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3861                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
3862                         InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3863                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
3864                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
3865                         &Default::default(), &random_seed_bytes).unwrap();
3866                 assert_eq!(route.paths[0].hops.len(), 2);
3867
3868                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3869                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3870                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3871                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3872                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3873                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3874
3875                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3876                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3877                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3878                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3879                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3880                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3881         }
3882
3883         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3884                 let zero_fees = RoutingFees {
3885                         base_msat: 0,
3886                         proportional_millionths: 0,
3887                 };
3888                 vec![RouteHint(vec![RouteHintHop {
3889                         src_node_id: nodes[3],
3890                         short_channel_id: 8,
3891                         fees: zero_fees,
3892                         cltv_expiry_delta: (8 << 4) | 1,
3893                         htlc_minimum_msat: None,
3894                         htlc_maximum_msat: None,
3895                 }
3896                 ]), RouteHint(vec![RouteHintHop {
3897                         src_node_id: nodes[4],
3898                         short_channel_id: 9,
3899                         fees: RoutingFees {
3900                                 base_msat: 1001,
3901                                 proportional_millionths: 0,
3902                         },
3903                         cltv_expiry_delta: (9 << 4) | 1,
3904                         htlc_minimum_msat: None,
3905                         htlc_maximum_msat: None,
3906                 }]), RouteHint(vec![RouteHintHop {
3907                         src_node_id: nodes[5],
3908                         short_channel_id: 10,
3909                         fees: zero_fees,
3910                         cltv_expiry_delta: (10 << 4) | 1,
3911                         htlc_minimum_msat: None,
3912                         htlc_maximum_msat: None,
3913                 }])]
3914         }
3915
3916         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3917                 let zero_fees = RoutingFees {
3918                         base_msat: 0,
3919                         proportional_millionths: 0,
3920                 };
3921                 vec![RouteHint(vec![RouteHintHop {
3922                         src_node_id: nodes[2],
3923                         short_channel_id: 5,
3924                         fees: RoutingFees {
3925                                 base_msat: 100,
3926                                 proportional_millionths: 0,
3927                         },
3928                         cltv_expiry_delta: (5 << 4) | 1,
3929                         htlc_minimum_msat: None,
3930                         htlc_maximum_msat: None,
3931                 }, RouteHintHop {
3932                         src_node_id: nodes[3],
3933                         short_channel_id: 8,
3934                         fees: zero_fees,
3935                         cltv_expiry_delta: (8 << 4) | 1,
3936                         htlc_minimum_msat: None,
3937                         htlc_maximum_msat: None,
3938                 }
3939                 ]), RouteHint(vec![RouteHintHop {
3940                         src_node_id: nodes[4],
3941                         short_channel_id: 9,
3942                         fees: RoutingFees {
3943                                 base_msat: 1001,
3944                                 proportional_millionths: 0,
3945                         },
3946                         cltv_expiry_delta: (9 << 4) | 1,
3947                         htlc_minimum_msat: None,
3948                         htlc_maximum_msat: None,
3949                 }]), RouteHint(vec![RouteHintHop {
3950                         src_node_id: nodes[5],
3951                         short_channel_id: 10,
3952                         fees: zero_fees,
3953                         cltv_expiry_delta: (10 << 4) | 1,
3954                         htlc_minimum_msat: None,
3955                         htlc_maximum_msat: None,
3956                 }])]
3957         }
3958
3959         #[test]
3960         fn partial_route_hint_test() {
3961                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3962                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3963                 let scorer = ln_test_utils::TestScorer::new();
3964                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3965                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3966
3967                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3968                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3969                 // RouteHint may be partially used by the algo to build the best path.
3970
3971                 // First check that last hop can't have its source as the payee.
3972                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3973                         src_node_id: nodes[6],
3974                         short_channel_id: 8,
3975                         fees: RoutingFees {
3976                                 base_msat: 1000,
3977                                 proportional_millionths: 0,
3978                         },
3979                         cltv_expiry_delta: (8 << 4) | 1,
3980                         htlc_minimum_msat: None,
3981                         htlc_maximum_msat: None,
3982                 }]);
3983
3984                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3985                 invalid_last_hops.push(invalid_last_hop);
3986                 {
3987                         let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3988                                 .with_route_hints(invalid_last_hops).unwrap();
3989                         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3990                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3991                                 &route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3992                                 &Default::default(), &random_seed_bytes) {
3993                                         assert_eq!(err, "Route hint cannot have the payee as the source.");
3994                         } else { panic!(); }
3995                 }
3996
3997                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
3998                         .with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3999                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4000                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4001                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4002                 assert_eq!(route.paths[0].hops.len(), 5);
4003
4004                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4005                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4006                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4007                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4008                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4009                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4010
4011                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4012                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4013                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4014                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4015                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4016                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4017
4018                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4019                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4020                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4021                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4022                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4023                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4024
4025                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4026                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4027                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4028                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4029                 // If we have a peer in the node map, we'll use their features here since we don't have
4030                 // a way of figuring out their features from the invoice:
4031                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4032                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4033
4034                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4035                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4036                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4037                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4038                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4039                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4040         }
4041
4042         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4043                 let zero_fees = RoutingFees {
4044                         base_msat: 0,
4045                         proportional_millionths: 0,
4046                 };
4047                 vec![RouteHint(vec![RouteHintHop {
4048                         src_node_id: nodes[3],
4049                         short_channel_id: 8,
4050                         fees: zero_fees,
4051                         cltv_expiry_delta: (8 << 4) | 1,
4052                         htlc_minimum_msat: None,
4053                         htlc_maximum_msat: None,
4054                 }]), RouteHint(vec![
4055
4056                 ]), RouteHint(vec![RouteHintHop {
4057                         src_node_id: nodes[5],
4058                         short_channel_id: 10,
4059                         fees: zero_fees,
4060                         cltv_expiry_delta: (10 << 4) | 1,
4061                         htlc_minimum_msat: None,
4062                         htlc_maximum_msat: None,
4063                 }])]
4064         }
4065
4066         #[test]
4067         fn ignores_empty_last_hops_test() {
4068                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4069                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4070                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4071                 let scorer = ln_test_utils::TestScorer::new();
4072                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4073                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4074
4075                 // Test handling of an empty RouteHint passed in Invoice.
4076                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4077                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4078                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4079                 assert_eq!(route.paths[0].hops.len(), 5);
4080
4081                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4082                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4083                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4084                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4085                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4086                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4087
4088                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4089                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4090                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4091                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4092                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4093                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4094
4095                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4096                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4097                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4098                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4099                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4100                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4101
4102                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4103                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4104                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4105                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4106                 // If we have a peer in the node map, we'll use their features here since we don't have
4107                 // a way of figuring out their features from the invoice:
4108                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4109                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4110
4111                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4112                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4113                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4114                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4115                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4116                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4117         }
4118
4119         /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4120         /// and 0xff01.
4121         fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4122                 let zero_fees = RoutingFees {
4123                         base_msat: 0,
4124                         proportional_millionths: 0,
4125                 };
4126                 vec![RouteHint(vec![RouteHintHop {
4127                         src_node_id: hint_hops[0],
4128                         short_channel_id: 0xff00,
4129                         fees: RoutingFees {
4130                                 base_msat: 100,
4131                                 proportional_millionths: 0,
4132                         },
4133                         cltv_expiry_delta: (5 << 4) | 1,
4134                         htlc_minimum_msat: None,
4135                         htlc_maximum_msat: None,
4136                 }, RouteHintHop {
4137                         src_node_id: hint_hops[1],
4138                         short_channel_id: 0xff01,
4139                         fees: zero_fees,
4140                         cltv_expiry_delta: (8 << 4) | 1,
4141                         htlc_minimum_msat: None,
4142                         htlc_maximum_msat: None,
4143                 }])]
4144         }
4145
4146         #[test]
4147         fn multi_hint_last_hops_test() {
4148                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4149                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4150                 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4151                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4152                 let scorer = ln_test_utils::TestScorer::new();
4153                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4154                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4155                 // Test through channels 2, 3, 0xff00, 0xff01.
4156                 // Test shows that multiple hop hints are considered.
4157
4158                 // Disabling channels 6 & 7 by flags=2
4159                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4160                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4161                         short_channel_id: 6,
4162                         timestamp: 2,
4163                         flags: 2, // to disable
4164                         cltv_expiry_delta: 0,
4165                         htlc_minimum_msat: 0,
4166                         htlc_maximum_msat: MAX_VALUE_MSAT,
4167                         fee_base_msat: 0,
4168                         fee_proportional_millionths: 0,
4169                         excess_data: Vec::new()
4170                 });
4171                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4172                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4173                         short_channel_id: 7,
4174                         timestamp: 2,
4175                         flags: 2, // to disable
4176                         cltv_expiry_delta: 0,
4177                         htlc_minimum_msat: 0,
4178                         htlc_maximum_msat: MAX_VALUE_MSAT,
4179                         fee_base_msat: 0,
4180                         fee_proportional_millionths: 0,
4181                         excess_data: Vec::new()
4182                 });
4183
4184                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4185                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4186                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4187                 assert_eq!(route.paths[0].hops.len(), 4);
4188
4189                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4190                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4191                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4192                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4193                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4194                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4195
4196                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4197                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4198                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4199                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4200                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4201                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4202
4203                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4204                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4205                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4206                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4207                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4208                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4209
4210                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4211                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4212                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4213                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4214                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4215                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4216         }
4217
4218         #[test]
4219         fn private_multi_hint_last_hops_test() {
4220                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4221                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4222
4223                 let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4224                 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4225
4226                 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4227                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4228                 let scorer = ln_test_utils::TestScorer::new();
4229                 // Test through channels 2, 3, 0xff00, 0xff01.
4230                 // Test shows that multiple hop hints are considered.
4231
4232                 // Disabling channels 6 & 7 by flags=2
4233                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4234                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4235                         short_channel_id: 6,
4236                         timestamp: 2,
4237                         flags: 2, // to disable
4238                         cltv_expiry_delta: 0,
4239                         htlc_minimum_msat: 0,
4240                         htlc_maximum_msat: MAX_VALUE_MSAT,
4241                         fee_base_msat: 0,
4242                         fee_proportional_millionths: 0,
4243                         excess_data: Vec::new()
4244                 });
4245                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4246                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4247                         short_channel_id: 7,
4248                         timestamp: 2,
4249                         flags: 2, // to disable
4250                         cltv_expiry_delta: 0,
4251                         htlc_minimum_msat: 0,
4252                         htlc_maximum_msat: MAX_VALUE_MSAT,
4253                         fee_base_msat: 0,
4254                         fee_proportional_millionths: 0,
4255                         excess_data: Vec::new()
4256                 });
4257
4258                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4259                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4260                         Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4261                 assert_eq!(route.paths[0].hops.len(), 4);
4262
4263                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4264                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4265                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4266                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4267                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4268                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4269
4270                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4271                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4272                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4273                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4274                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4275                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4276
4277                 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4278                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4279                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4280                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4281                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4282                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4283
4284                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4285                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4286                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4287                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4288                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4289                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4290         }
4291
4292         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4293                 let zero_fees = RoutingFees {
4294                         base_msat: 0,
4295                         proportional_millionths: 0,
4296                 };
4297                 vec![RouteHint(vec![RouteHintHop {
4298                         src_node_id: nodes[4],
4299                         short_channel_id: 11,
4300                         fees: zero_fees,
4301                         cltv_expiry_delta: (11 << 4) | 1,
4302                         htlc_minimum_msat: None,
4303                         htlc_maximum_msat: None,
4304                 }, RouteHintHop {
4305                         src_node_id: nodes[3],
4306                         short_channel_id: 8,
4307                         fees: zero_fees,
4308                         cltv_expiry_delta: (8 << 4) | 1,
4309                         htlc_minimum_msat: None,
4310                         htlc_maximum_msat: None,
4311                 }]), RouteHint(vec![RouteHintHop {
4312                         src_node_id: nodes[4],
4313                         short_channel_id: 9,
4314                         fees: RoutingFees {
4315                                 base_msat: 1001,
4316                                 proportional_millionths: 0,
4317                         },
4318                         cltv_expiry_delta: (9 << 4) | 1,
4319                         htlc_minimum_msat: None,
4320                         htlc_maximum_msat: None,
4321                 }]), RouteHint(vec![RouteHintHop {
4322                         src_node_id: nodes[5],
4323                         short_channel_id: 10,
4324                         fees: zero_fees,
4325                         cltv_expiry_delta: (10 << 4) | 1,
4326                         htlc_minimum_msat: None,
4327                         htlc_maximum_msat: None,
4328                 }])]
4329         }
4330
4331         #[test]
4332         fn last_hops_with_public_channel_test() {
4333                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4334                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4335                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4336                 let scorer = ln_test_utils::TestScorer::new();
4337                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4338                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4339                 // This test shows that public routes can be present in the invoice
4340                 // which would be handled in the same manner.
4341
4342                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4343                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4344                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4345                 assert_eq!(route.paths[0].hops.len(), 5);
4346
4347                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4348                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4349                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4350                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4351                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4352                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4353
4354                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4355                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4356                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4357                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4358                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4359                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4360
4361                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4362                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4363                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4364                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4365                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4366                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4367
4368                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4369                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4370                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4371                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4372                 // If we have a peer in the node map, we'll use their features here since we don't have
4373                 // a way of figuring out their features from the invoice:
4374                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4375                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4376
4377                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4378                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4379                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4380                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4381                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4382                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4383         }
4384
4385         #[test]
4386         fn our_chans_last_hop_connect_test() {
4387                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4388                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4389                 let scorer = ln_test_utils::TestScorer::new();
4390                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4391                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4392
4393                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4394                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4395                 let mut last_hops = last_hops(&nodes);
4396                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4397                         .with_route_hints(last_hops.clone()).unwrap();
4398                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4399                 let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4400                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4401                         &Default::default(), &random_seed_bytes).unwrap();
4402                 assert_eq!(route.paths[0].hops.len(), 2);
4403
4404                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4405                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4406                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4407                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4408                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4409                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4410
4411                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4412                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4413                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4414                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4415                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4416                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4417
4418                 last_hops[0].0[0].fees.base_msat = 1000;
4419
4420                 // Revert to via 6 as the fee on 8 goes up
4421                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4422                         .with_route_hints(last_hops).unwrap();
4423                 let route_params = RouteParameters::from_payment_params_and_value(
4424                         payment_params.clone(), 100);
4425                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4426                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4427                 assert_eq!(route.paths[0].hops.len(), 4);
4428
4429                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4430                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4431                 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4432                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4433                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4434                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4435
4436                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4437                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4438                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4439                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4440                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4441                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4442
4443                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4444                 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4445                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4446                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4447                 // If we have a peer in the node map, we'll use their features here since we don't have
4448                 // a way of figuring out their features from the invoice:
4449                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4450                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4451
4452                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4453                 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4454                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4455                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4456                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4457                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4458
4459                 // ...but still use 8 for larger payments as 6 has a variable feerate
4460                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4461                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4462                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4463                 assert_eq!(route.paths[0].hops.len(), 5);
4464
4465                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4466                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4467                 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4468                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4469                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4470                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4471
4472                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4473                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4474                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4475                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4476                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4477                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4478
4479                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4480                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4481                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4482                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4483                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4484                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4485
4486                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4487                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4488                 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4489                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4490                 // If we have a peer in the node map, we'll use their features here since we don't have
4491                 // a way of figuring out their features from the invoice:
4492                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4493                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4494
4495                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4496                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4497                 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4498                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4499                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4500                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4501         }
4502
4503         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> {
4504                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4505                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4506                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4507
4508                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4509                 let last_hops = RouteHint(vec![RouteHintHop {
4510                         src_node_id: middle_node_id,
4511                         short_channel_id: 8,
4512                         fees: RoutingFees {
4513                                 base_msat: 1000,
4514                                 proportional_millionths: last_hop_fee_prop,
4515                         },
4516                         cltv_expiry_delta: (8 << 4) | 1,
4517                         htlc_minimum_msat: None,
4518                         htlc_maximum_msat: last_hop_htlc_max,
4519                 }]);
4520                 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4521                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4522                 let scorer = ln_test_utils::TestScorer::new();
4523                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4524                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4525                 let logger = ln_test_utils::TestLogger::new();
4526                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4527                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4528                 let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4529                                 Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4530                                 &random_seed_bytes);
4531                 route
4532         }
4533
4534         #[test]
4535         fn unannounced_path_test() {
4536                 // We should be able to send a payment to a destination without any help of a routing graph
4537                 // if we have a channel with a common counterparty that appears in the first and last hop
4538                 // hints.
4539                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4540
4541                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4542                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4543                 assert_eq!(route.paths[0].hops.len(), 2);
4544
4545                 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4546                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4547                 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
4548                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4549                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
4550                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4551
4552                 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
4553                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4554                 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
4555                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4556                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4557                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
4558         }
4559
4560         #[test]
4561         fn overflow_unannounced_path_test_liquidity_underflow() {
4562                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
4563                 // the last-hop had a fee which overflowed a u64, we'd panic.
4564                 // This was due to us adding the first-hop from us unconditionally, causing us to think
4565                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
4566                 // In this test, we previously hit a subtraction underflow due to having less available
4567                 // liquidity at the last hop than 0.
4568                 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());
4569         }
4570
4571         #[test]
4572         fn overflow_unannounced_path_test_feerate_overflow() {
4573                 // This tests for the same case as above, except instead of hitting a subtraction
4574                 // underflow, we hit a case where the fee charged at a hop overflowed.
4575                 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());
4576         }
4577
4578         #[test]
4579         fn available_amount_while_routing_test() {
4580                 // Tests whether we choose the correct available channel amount while routing.
4581
4582                 let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
4583                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4584                 let scorer = ln_test_utils::TestScorer::new();
4585                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4586                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4587                 let config = UserConfig::default();
4588                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4589                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4590                         .unwrap();
4591
4592                 // We will use a simple single-path route from
4593                 // our node to node2 via node0: channels {1, 3}.
4594
4595                 // First disable all other paths.
4596                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4597                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4598                         short_channel_id: 2,
4599                         timestamp: 2,
4600                         flags: 2,
4601                         cltv_expiry_delta: 0,
4602                         htlc_minimum_msat: 0,
4603                         htlc_maximum_msat: 100_000,
4604                         fee_base_msat: 0,
4605                         fee_proportional_millionths: 0,
4606                         excess_data: Vec::new()
4607                 });
4608                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4609                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4610                         short_channel_id: 12,
4611                         timestamp: 2,
4612                         flags: 2,
4613                         cltv_expiry_delta: 0,
4614                         htlc_minimum_msat: 0,
4615                         htlc_maximum_msat: 100_000,
4616                         fee_base_msat: 0,
4617                         fee_proportional_millionths: 0,
4618                         excess_data: Vec::new()
4619                 });
4620
4621                 // Make the first channel (#1) very permissive,
4622                 // and we will be testing all limits on the second channel.
4623                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4624                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4625                         short_channel_id: 1,
4626                         timestamp: 2,
4627                         flags: 0,
4628                         cltv_expiry_delta: 0,
4629                         htlc_minimum_msat: 0,
4630                         htlc_maximum_msat: 1_000_000_000,
4631                         fee_base_msat: 0,
4632                         fee_proportional_millionths: 0,
4633                         excess_data: Vec::new()
4634                 });
4635
4636                 // First, let's see if routing works if we have absolutely no idea about the available amount.
4637                 // In this case, it should be set to 250_000 sats.
4638                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4639                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4640                         short_channel_id: 3,
4641                         timestamp: 2,
4642                         flags: 0,
4643                         cltv_expiry_delta: 0,
4644                         htlc_minimum_msat: 0,
4645                         htlc_maximum_msat: 250_000_000,
4646                         fee_base_msat: 0,
4647                         fee_proportional_millionths: 0,
4648                         excess_data: Vec::new()
4649                 });
4650
4651                 {
4652                         // Attempt to route more than available results in a failure.
4653                         let route_params = RouteParameters::from_payment_params_and_value(
4654                                 payment_params.clone(), 250_000_001);
4655                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4656                                         &our_id, &route_params, &network_graph.read_only(), None,
4657                                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
4658                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4659                         } else { panic!(); }
4660                 }
4661
4662                 {
4663                         // Now, attempt to route an exact amount we have should be fine.
4664                         let route_params = RouteParameters::from_payment_params_and_value(
4665                                 payment_params.clone(), 250_000_000);
4666                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4667                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4668                         assert_eq!(route.paths.len(), 1);
4669                         let path = route.paths.last().unwrap();
4670                         assert_eq!(path.hops.len(), 2);
4671                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4672                         assert_eq!(path.final_value_msat(), 250_000_000);
4673                 }
4674
4675                 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
4676                 // Disable channel #1 and use another first hop.
4677                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4678                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4679                         short_channel_id: 1,
4680                         timestamp: 3,
4681                         flags: 2,
4682                         cltv_expiry_delta: 0,
4683                         htlc_minimum_msat: 0,
4684                         htlc_maximum_msat: 1_000_000_000,
4685                         fee_base_msat: 0,
4686                         fee_proportional_millionths: 0,
4687                         excess_data: Vec::new()
4688                 });
4689
4690                 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
4691                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
4692
4693                 {
4694                         // Attempt to route more than available results in a failure.
4695                         let route_params = RouteParameters::from_payment_params_and_value(
4696                                 payment_params.clone(), 200_000_001);
4697                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4698                                         &our_id, &route_params, &network_graph.read_only(),
4699                                         Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4700                                         &Default::default(), &random_seed_bytes) {
4701                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4702                         } else { panic!(); }
4703                 }
4704
4705                 {
4706                         // Now, attempt to route an exact amount we have should be fine.
4707                         let route_params = RouteParameters::from_payment_params_and_value(
4708                                 payment_params.clone(), 200_000_000);
4709                         let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4710                                 Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4711                                 &Default::default(), &random_seed_bytes).unwrap();
4712                         assert_eq!(route.paths.len(), 1);
4713                         let path = route.paths.last().unwrap();
4714                         assert_eq!(path.hops.len(), 2);
4715                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4716                         assert_eq!(path.final_value_msat(), 200_000_000);
4717                 }
4718
4719                 // Enable channel #1 back.
4720                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4721                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4722                         short_channel_id: 1,
4723                         timestamp: 4,
4724                         flags: 0,
4725                         cltv_expiry_delta: 0,
4726                         htlc_minimum_msat: 0,
4727                         htlc_maximum_msat: 1_000_000_000,
4728                         fee_base_msat: 0,
4729                         fee_proportional_millionths: 0,
4730                         excess_data: Vec::new()
4731                 });
4732
4733
4734                 // Now let's see if routing works if we know only htlc_maximum_msat.
4735                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4736                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4737                         short_channel_id: 3,
4738                         timestamp: 3,
4739                         flags: 0,
4740                         cltv_expiry_delta: 0,
4741                         htlc_minimum_msat: 0,
4742                         htlc_maximum_msat: 15_000,
4743                         fee_base_msat: 0,
4744                         fee_proportional_millionths: 0,
4745                         excess_data: Vec::new()
4746                 });
4747
4748                 {
4749                         // Attempt to route more than available results in a failure.
4750                         let route_params = RouteParameters::from_payment_params_and_value(
4751                                 payment_params.clone(), 15_001);
4752                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4753                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4754                                         &scorer, &Default::default(), &random_seed_bytes) {
4755                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4756                         } else { panic!(); }
4757                 }
4758
4759                 {
4760                         // Now, attempt to route an exact amount we have should be fine.
4761                         let route_params = RouteParameters::from_payment_params_and_value(
4762                                 payment_params.clone(), 15_000);
4763                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4764                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4765                         assert_eq!(route.paths.len(), 1);
4766                         let path = route.paths.last().unwrap();
4767                         assert_eq!(path.hops.len(), 2);
4768                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4769                         assert_eq!(path.final_value_msat(), 15_000);
4770                 }
4771
4772                 // Now let's see if routing works if we know only capacity from the UTXO.
4773
4774                 // We can't change UTXO capacity on the fly, so we'll disable
4775                 // the existing channel and add another one with the capacity we need.
4776                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4777                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4778                         short_channel_id: 3,
4779                         timestamp: 4,
4780                         flags: 2,
4781                         cltv_expiry_delta: 0,
4782                         htlc_minimum_msat: 0,
4783                         htlc_maximum_msat: MAX_VALUE_MSAT,
4784                         fee_base_msat: 0,
4785                         fee_proportional_millionths: 0,
4786                         excess_data: Vec::new()
4787                 });
4788
4789                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
4790                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
4791                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
4792                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
4793                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
4794
4795                 *chain_monitor.utxo_ret.lock().unwrap() =
4796                         UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
4797                 gossip_sync.add_utxo_lookup(Some(chain_monitor));
4798
4799                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
4800                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4801                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4802                         short_channel_id: 333,
4803                         timestamp: 1,
4804                         flags: 0,
4805                         cltv_expiry_delta: (3 << 4) | 1,
4806                         htlc_minimum_msat: 0,
4807                         htlc_maximum_msat: 15_000,
4808                         fee_base_msat: 0,
4809                         fee_proportional_millionths: 0,
4810                         excess_data: Vec::new()
4811                 });
4812                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4813                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4814                         short_channel_id: 333,
4815                         timestamp: 1,
4816                         flags: 1,
4817                         cltv_expiry_delta: (3 << 4) | 2,
4818                         htlc_minimum_msat: 0,
4819                         htlc_maximum_msat: 15_000,
4820                         fee_base_msat: 100,
4821                         fee_proportional_millionths: 0,
4822                         excess_data: Vec::new()
4823                 });
4824
4825                 {
4826                         // Attempt to route more than available results in a failure.
4827                         let route_params = RouteParameters::from_payment_params_and_value(
4828                                 payment_params.clone(), 15_001);
4829                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4830                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4831                                         &scorer, &Default::default(), &random_seed_bytes) {
4832                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4833                         } else { panic!(); }
4834                 }
4835
4836                 {
4837                         // Now, attempt to route an exact amount we have should be fine.
4838                         let route_params = RouteParameters::from_payment_params_and_value(
4839                                 payment_params.clone(), 15_000);
4840                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4841                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4842                         assert_eq!(route.paths.len(), 1);
4843                         let path = route.paths.last().unwrap();
4844                         assert_eq!(path.hops.len(), 2);
4845                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4846                         assert_eq!(path.final_value_msat(), 15_000);
4847                 }
4848
4849                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4850                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4851                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4852                         short_channel_id: 333,
4853                         timestamp: 6,
4854                         flags: 0,
4855                         cltv_expiry_delta: 0,
4856                         htlc_minimum_msat: 0,
4857                         htlc_maximum_msat: 10_000,
4858                         fee_base_msat: 0,
4859                         fee_proportional_millionths: 0,
4860                         excess_data: Vec::new()
4861                 });
4862
4863                 {
4864                         // Attempt to route more than available results in a failure.
4865                         let route_params = RouteParameters::from_payment_params_and_value(
4866                                 payment_params.clone(), 10_001);
4867                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4868                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4869                                         &scorer, &Default::default(), &random_seed_bytes) {
4870                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4871                         } else { panic!(); }
4872                 }
4873
4874                 {
4875                         // Now, attempt to route an exact amount we have should be fine.
4876                         let route_params = RouteParameters::from_payment_params_and_value(
4877                                 payment_params.clone(), 10_000);
4878                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4879                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4880                         assert_eq!(route.paths.len(), 1);
4881                         let path = route.paths.last().unwrap();
4882                         assert_eq!(path.hops.len(), 2);
4883                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4884                         assert_eq!(path.final_value_msat(), 10_000);
4885                 }
4886         }
4887
4888         #[test]
4889         fn available_liquidity_last_hop_test() {
4890                 // Check that available liquidity properly limits the path even when only
4891                 // one of the latter hops is limited.
4892                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4893                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4894                 let scorer = ln_test_utils::TestScorer::new();
4895                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4896                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4897                 let config = UserConfig::default();
4898                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
4899                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
4900                         .unwrap();
4901
4902                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4903                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4904                 // Total capacity: 50 sats.
4905
4906                 // Disable other potential paths.
4907                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4908                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4909                         short_channel_id: 2,
4910                         timestamp: 2,
4911                         flags: 2,
4912                         cltv_expiry_delta: 0,
4913                         htlc_minimum_msat: 0,
4914                         htlc_maximum_msat: 100_000,
4915                         fee_base_msat: 0,
4916                         fee_proportional_millionths: 0,
4917                         excess_data: Vec::new()
4918                 });
4919                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4920                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4921                         short_channel_id: 7,
4922                         timestamp: 2,
4923                         flags: 2,
4924                         cltv_expiry_delta: 0,
4925                         htlc_minimum_msat: 0,
4926                         htlc_maximum_msat: 100_000,
4927                         fee_base_msat: 0,
4928                         fee_proportional_millionths: 0,
4929                         excess_data: Vec::new()
4930                 });
4931
4932                 // Limit capacities
4933
4934                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4935                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4936                         short_channel_id: 12,
4937                         timestamp: 2,
4938                         flags: 0,
4939                         cltv_expiry_delta: 0,
4940                         htlc_minimum_msat: 0,
4941                         htlc_maximum_msat: 100_000,
4942                         fee_base_msat: 0,
4943                         fee_proportional_millionths: 0,
4944                         excess_data: Vec::new()
4945                 });
4946                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4947                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4948                         short_channel_id: 13,
4949                         timestamp: 2,
4950                         flags: 0,
4951                         cltv_expiry_delta: 0,
4952                         htlc_minimum_msat: 0,
4953                         htlc_maximum_msat: 100_000,
4954                         fee_base_msat: 0,
4955                         fee_proportional_millionths: 0,
4956                         excess_data: Vec::new()
4957                 });
4958
4959                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4960                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4961                         short_channel_id: 6,
4962                         timestamp: 2,
4963                         flags: 0,
4964                         cltv_expiry_delta: 0,
4965                         htlc_minimum_msat: 0,
4966                         htlc_maximum_msat: 50_000,
4967                         fee_base_msat: 0,
4968                         fee_proportional_millionths: 0,
4969                         excess_data: Vec::new()
4970                 });
4971                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4972                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4973                         short_channel_id: 11,
4974                         timestamp: 2,
4975                         flags: 0,
4976                         cltv_expiry_delta: 0,
4977                         htlc_minimum_msat: 0,
4978                         htlc_maximum_msat: 100_000,
4979                         fee_base_msat: 0,
4980                         fee_proportional_millionths: 0,
4981                         excess_data: Vec::new()
4982                 });
4983                 {
4984                         // Attempt to route more than available results in a failure.
4985                         let route_params = RouteParameters::from_payment_params_and_value(
4986                                 payment_params.clone(), 60_000);
4987                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4988                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
4989                                         &scorer, &Default::default(), &random_seed_bytes) {
4990                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4991                         } else { panic!(); }
4992                 }
4993
4994                 {
4995                         // Now, attempt to route 49 sats (just a bit below the capacity).
4996                         let route_params = RouteParameters::from_payment_params_and_value(
4997                                 payment_params.clone(), 49_000);
4998                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4999                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5000                         assert_eq!(route.paths.len(), 1);
5001                         let mut total_amount_paid_msat = 0;
5002                         for path in &route.paths {
5003                                 assert_eq!(path.hops.len(), 4);
5004                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5005                                 total_amount_paid_msat += path.final_value_msat();
5006                         }
5007                         assert_eq!(total_amount_paid_msat, 49_000);
5008                 }
5009
5010                 {
5011                         // Attempt to route an exact amount is also fine
5012                         let route_params = RouteParameters::from_payment_params_and_value(
5013                                 payment_params, 50_000);
5014                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5015                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5016                         assert_eq!(route.paths.len(), 1);
5017                         let mut total_amount_paid_msat = 0;
5018                         for path in &route.paths {
5019                                 assert_eq!(path.hops.len(), 4);
5020                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5021                                 total_amount_paid_msat += path.final_value_msat();
5022                         }
5023                         assert_eq!(total_amount_paid_msat, 50_000);
5024                 }
5025         }
5026
5027         #[test]
5028         fn ignore_fee_first_hop_test() {
5029                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5030                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5031                 let scorer = ln_test_utils::TestScorer::new();
5032                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5033                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5034                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5035
5036                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5037                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5038                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5039                         short_channel_id: 1,
5040                         timestamp: 2,
5041                         flags: 0,
5042                         cltv_expiry_delta: 0,
5043                         htlc_minimum_msat: 0,
5044                         htlc_maximum_msat: 100_000,
5045                         fee_base_msat: 1_000_000,
5046                         fee_proportional_millionths: 0,
5047                         excess_data: Vec::new()
5048                 });
5049                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5050                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5051                         short_channel_id: 3,
5052                         timestamp: 2,
5053                         flags: 0,
5054                         cltv_expiry_delta: 0,
5055                         htlc_minimum_msat: 0,
5056                         htlc_maximum_msat: 50_000,
5057                         fee_base_msat: 0,
5058                         fee_proportional_millionths: 0,
5059                         excess_data: Vec::new()
5060                 });
5061
5062                 {
5063                         let route_params = RouteParameters::from_payment_params_and_value(
5064                                 payment_params, 50_000);
5065                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5066                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5067                         assert_eq!(route.paths.len(), 1);
5068                         let mut total_amount_paid_msat = 0;
5069                         for path in &route.paths {
5070                                 assert_eq!(path.hops.len(), 2);
5071                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5072                                 total_amount_paid_msat += path.final_value_msat();
5073                         }
5074                         assert_eq!(total_amount_paid_msat, 50_000);
5075                 }
5076         }
5077
5078         #[test]
5079         fn simple_mpp_route_test() {
5080                 let (secp_ctx, _, _, _, _) = build_graph();
5081                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
5082                 let config = UserConfig::default();
5083                 let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5084                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5085                         .unwrap();
5086                 do_simple_mpp_route_test(clear_payment_params);
5087
5088                 // MPP to a 1-hop blinded path for nodes[2]
5089                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5090                 let blinded_path = BlindedPath {
5091                         introduction_node_id: nodes[2],
5092                         blinding_point: ln_test_utils::pubkey(42),
5093                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }],
5094                 };
5095                 let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5096                         fee_base_msat: 0,
5097                         fee_proportional_millionths: 0,
5098                         htlc_minimum_msat: 0,
5099                         htlc_maximum_msat: 0,
5100                         cltv_expiry_delta: 0,
5101                         features: BlindedHopFeatures::empty(),
5102                 };
5103                 let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())])
5104                         .with_bolt12_features(bolt12_features.clone()).unwrap();
5105                 do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5106
5107                 // MPP to 3 2-hop blinded paths
5108                 let mut blinded_path_node_0 = blinded_path.clone();
5109                 blinded_path_node_0.introduction_node_id = nodes[0];
5110                 blinded_path_node_0.blinded_hops.push(blinded_path.blinded_hops[0].clone());
5111                 let mut node_0_payinfo = blinded_payinfo.clone();
5112                 node_0_payinfo.htlc_maximum_msat = 50_000;
5113
5114                 let mut blinded_path_node_7 = blinded_path_node_0.clone();
5115                 blinded_path_node_7.introduction_node_id = nodes[7];
5116                 let mut node_7_payinfo = blinded_payinfo.clone();
5117                 node_7_payinfo.htlc_maximum_msat = 60_000;
5118
5119                 let mut blinded_path_node_1 = blinded_path_node_0.clone();
5120                 blinded_path_node_1.introduction_node_id = nodes[1];
5121                 let mut node_1_payinfo = blinded_payinfo.clone();
5122                 node_1_payinfo.htlc_maximum_msat = 180_000;
5123
5124                 let two_hop_blinded_payment_params = PaymentParameters::blinded(
5125                         vec![
5126                                 (node_0_payinfo, blinded_path_node_0),
5127                                 (node_7_payinfo, blinded_path_node_7),
5128                                 (node_1_payinfo, blinded_path_node_1)
5129                         ])
5130                         .with_bolt12_features(bolt12_features).unwrap();
5131                 do_simple_mpp_route_test(two_hop_blinded_payment_params);
5132         }
5133
5134
5135         fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5136                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5137                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5138                 let scorer = ln_test_utils::TestScorer::new();
5139                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5140                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5141
5142                 // We need a route consisting of 3 paths:
5143                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5144                 // To achieve this, the amount being transferred should be around
5145                 // the total capacity of these 3 paths.
5146
5147                 // First, we set limits on these (previously unlimited) channels.
5148                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5149
5150                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5151                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5152                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5153                         short_channel_id: 1,
5154                         timestamp: 2,
5155                         flags: 0,
5156                         cltv_expiry_delta: 0,
5157                         htlc_minimum_msat: 0,
5158                         htlc_maximum_msat: 100_000,
5159                         fee_base_msat: 0,
5160                         fee_proportional_millionths: 0,
5161                         excess_data: Vec::new()
5162                 });
5163                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5164                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5165                         short_channel_id: 3,
5166                         timestamp: 2,
5167                         flags: 0,
5168                         cltv_expiry_delta: 0,
5169                         htlc_minimum_msat: 0,
5170                         htlc_maximum_msat: 50_000,
5171                         fee_base_msat: 0,
5172                         fee_proportional_millionths: 0,
5173                         excess_data: Vec::new()
5174                 });
5175
5176                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5177                 // (total limit 60).
5178                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5179                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5180                         short_channel_id: 12,
5181                         timestamp: 2,
5182                         flags: 0,
5183                         cltv_expiry_delta: 0,
5184                         htlc_minimum_msat: 0,
5185                         htlc_maximum_msat: 60_000,
5186                         fee_base_msat: 0,
5187                         fee_proportional_millionths: 0,
5188                         excess_data: Vec::new()
5189                 });
5190                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5191                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5192                         short_channel_id: 13,
5193                         timestamp: 2,
5194                         flags: 0,
5195                         cltv_expiry_delta: 0,
5196                         htlc_minimum_msat: 0,
5197                         htlc_maximum_msat: 60_000,
5198                         fee_base_msat: 0,
5199                         fee_proportional_millionths: 0,
5200                         excess_data: Vec::new()
5201                 });
5202
5203                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5204                 // (total capacity 180 sats).
5205                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5206                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5207                         short_channel_id: 2,
5208                         timestamp: 2,
5209                         flags: 0,
5210                         cltv_expiry_delta: 0,
5211                         htlc_minimum_msat: 0,
5212                         htlc_maximum_msat: 200_000,
5213                         fee_base_msat: 0,
5214                         fee_proportional_millionths: 0,
5215                         excess_data: Vec::new()
5216                 });
5217                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5218                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5219                         short_channel_id: 4,
5220                         timestamp: 2,
5221                         flags: 0,
5222                         cltv_expiry_delta: 0,
5223                         htlc_minimum_msat: 0,
5224                         htlc_maximum_msat: 180_000,
5225                         fee_base_msat: 0,
5226                         fee_proportional_millionths: 0,
5227                         excess_data: Vec::new()
5228                 });
5229
5230                 {
5231                         // Attempt to route more than available results in a failure.
5232                         let route_params = RouteParameters::from_payment_params_and_value(
5233                                 payment_params.clone(), 300_000);
5234                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5235                                 &our_id, &route_params, &network_graph.read_only(), None,
5236                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5237                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
5238                         } else { panic!(); }
5239                 }
5240
5241                 {
5242                         // Attempt to route while setting max_path_count to 0 results in a failure.
5243                         let zero_payment_params = payment_params.clone().with_max_path_count(0);
5244                         let route_params = RouteParameters::from_payment_params_and_value(
5245                                 zero_payment_params, 100);
5246                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5247                                 &our_id, &route_params, &network_graph.read_only(), None,
5248                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5249                                         assert_eq!(err, "Can't find a route with no paths allowed.");
5250                         } else { panic!(); }
5251                 }
5252
5253                 {
5254                         // Attempt to route while setting max_path_count to 3 results in a failure.
5255                         // This is the case because the minimal_value_contribution_msat would require each path
5256                         // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5257                         let fail_payment_params = payment_params.clone().with_max_path_count(3);
5258                         let route_params = RouteParameters::from_payment_params_and_value(
5259                                 fail_payment_params, 250_000);
5260                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5261                                 &our_id, &route_params, &network_graph.read_only(), None,
5262                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5263                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
5264                         } else { panic!(); }
5265                 }
5266
5267                 {
5268                         // Now, attempt to route 250 sats (just a bit below the capacity).
5269                         // Our algorithm should provide us with these 3 paths.
5270                         let route_params = RouteParameters::from_payment_params_and_value(
5271                                 payment_params.clone(), 250_000);
5272                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5273                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5274                         assert_eq!(route.paths.len(), 3);
5275                         let mut total_amount_paid_msat = 0;
5276                         for path in &route.paths {
5277                                 if let Some(bt) = &path.blinded_tail {
5278                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5279                                 } else {
5280                                         assert_eq!(path.hops.len(), 2);
5281                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5282                                 }
5283                                 total_amount_paid_msat += path.final_value_msat();
5284                         }
5285                         assert_eq!(total_amount_paid_msat, 250_000);
5286                 }
5287
5288                 {
5289                         // Attempt to route an exact amount is also fine
5290                         let route_params = RouteParameters::from_payment_params_and_value(
5291                                 payment_params.clone(), 290_000);
5292                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5293                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5294                         assert_eq!(route.paths.len(), 3);
5295                         let mut total_amount_paid_msat = 0;
5296                         for path in &route.paths {
5297                                 if payment_params.payee.blinded_route_hints().len() != 0 {
5298                                         assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5299                                 if let Some(bt) = &path.blinded_tail {
5300                                         assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5301                                         if bt.hops.len() > 1 {
5302                                                 assert_eq!(path.hops.last().unwrap().pubkey,
5303                                                         payment_params.payee.blinded_route_hints().iter()
5304                                                                 .find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
5305                                                                 .map(|(_, p)| p.introduction_node_id).unwrap());
5306                                         } else {
5307                                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5308                                         }
5309                                 } else {
5310                                         assert_eq!(path.hops.len(), 2);
5311                                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5312                                 }
5313                                 total_amount_paid_msat += path.final_value_msat();
5314                         }
5315                         assert_eq!(total_amount_paid_msat, 290_000);
5316                 }
5317         }
5318
5319         #[test]
5320         fn long_mpp_route_test() {
5321                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5322                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5323                 let scorer = ln_test_utils::TestScorer::new();
5324                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5325                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5326                 let config = UserConfig::default();
5327                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5328                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5329                         .unwrap();
5330
5331                 // We need a route consisting of 3 paths:
5332                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5333                 // Note that these paths overlap (channels 5, 12, 13).
5334                 // We will route 300 sats.
5335                 // Each path will have 100 sats capacity, those channels which
5336                 // are used twice will have 200 sats capacity.
5337
5338                 // Disable other potential paths.
5339                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5340                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5341                         short_channel_id: 2,
5342                         timestamp: 2,
5343                         flags: 2,
5344                         cltv_expiry_delta: 0,
5345                         htlc_minimum_msat: 0,
5346                         htlc_maximum_msat: 100_000,
5347                         fee_base_msat: 0,
5348                         fee_proportional_millionths: 0,
5349                         excess_data: Vec::new()
5350                 });
5351                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5352                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5353                         short_channel_id: 7,
5354                         timestamp: 2,
5355                         flags: 2,
5356                         cltv_expiry_delta: 0,
5357                         htlc_minimum_msat: 0,
5358                         htlc_maximum_msat: 100_000,
5359                         fee_base_msat: 0,
5360                         fee_proportional_millionths: 0,
5361                         excess_data: Vec::new()
5362                 });
5363
5364                 // Path via {node0, node2} is channels {1, 3, 5}.
5365                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5366                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5367                         short_channel_id: 1,
5368                         timestamp: 2,
5369                         flags: 0,
5370                         cltv_expiry_delta: 0,
5371                         htlc_minimum_msat: 0,
5372                         htlc_maximum_msat: 100_000,
5373                         fee_base_msat: 0,
5374                         fee_proportional_millionths: 0,
5375                         excess_data: Vec::new()
5376                 });
5377                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5378                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5379                         short_channel_id: 3,
5380                         timestamp: 2,
5381                         flags: 0,
5382                         cltv_expiry_delta: 0,
5383                         htlc_minimum_msat: 0,
5384                         htlc_maximum_msat: 100_000,
5385                         fee_base_msat: 0,
5386                         fee_proportional_millionths: 0,
5387                         excess_data: Vec::new()
5388                 });
5389
5390                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5391                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5392                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5393                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5394                         short_channel_id: 5,
5395                         timestamp: 2,
5396                         flags: 0,
5397                         cltv_expiry_delta: 0,
5398                         htlc_minimum_msat: 0,
5399                         htlc_maximum_msat: 200_000,
5400                         fee_base_msat: 0,
5401                         fee_proportional_millionths: 0,
5402                         excess_data: Vec::new()
5403                 });
5404
5405                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5406                 // Add 100 sats to the capacities of {12, 13}, because these channels
5407                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5408                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5409                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5410                         short_channel_id: 12,
5411                         timestamp: 2,
5412                         flags: 0,
5413                         cltv_expiry_delta: 0,
5414                         htlc_minimum_msat: 0,
5415                         htlc_maximum_msat: 200_000,
5416                         fee_base_msat: 0,
5417                         fee_proportional_millionths: 0,
5418                         excess_data: Vec::new()
5419                 });
5420                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5421                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5422                         short_channel_id: 13,
5423                         timestamp: 2,
5424                         flags: 0,
5425                         cltv_expiry_delta: 0,
5426                         htlc_minimum_msat: 0,
5427                         htlc_maximum_msat: 200_000,
5428                         fee_base_msat: 0,
5429                         fee_proportional_millionths: 0,
5430                         excess_data: Vec::new()
5431                 });
5432
5433                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5434                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5435                         short_channel_id: 6,
5436                         timestamp: 2,
5437                         flags: 0,
5438                         cltv_expiry_delta: 0,
5439                         htlc_minimum_msat: 0,
5440                         htlc_maximum_msat: 100_000,
5441                         fee_base_msat: 0,
5442                         fee_proportional_millionths: 0,
5443                         excess_data: Vec::new()
5444                 });
5445                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5446                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5447                         short_channel_id: 11,
5448                         timestamp: 2,
5449                         flags: 0,
5450                         cltv_expiry_delta: 0,
5451                         htlc_minimum_msat: 0,
5452                         htlc_maximum_msat: 100_000,
5453                         fee_base_msat: 0,
5454                         fee_proportional_millionths: 0,
5455                         excess_data: Vec::new()
5456                 });
5457
5458                 // Path via {node7, node2} is channels {12, 13, 5}.
5459                 // We already limited them to 200 sats (they are used twice for 100 sats).
5460                 // Nothing to do here.
5461
5462                 {
5463                         // Attempt to route more than available results in a failure.
5464                         let route_params = RouteParameters::from_payment_params_and_value(
5465                                 payment_params.clone(), 350_000);
5466                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5467                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5468                                         &scorer, &Default::default(), &random_seed_bytes) {
5469                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5470                         } else { panic!(); }
5471                 }
5472
5473                 {
5474                         // Now, attempt to route 300 sats (exact amount we can route).
5475                         // Our algorithm should provide us with these 3 paths, 100 sats each.
5476                         let route_params = RouteParameters::from_payment_params_and_value(
5477                                 payment_params, 300_000);
5478                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5479                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5480                         assert_eq!(route.paths.len(), 3);
5481
5482                         let mut total_amount_paid_msat = 0;
5483                         for path in &route.paths {
5484                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5485                                 total_amount_paid_msat += path.final_value_msat();
5486                         }
5487                         assert_eq!(total_amount_paid_msat, 300_000);
5488                 }
5489
5490         }
5491
5492         #[test]
5493         fn mpp_cheaper_route_test() {
5494                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5495                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5496                 let scorer = ln_test_utils::TestScorer::new();
5497                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5498                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5499                 let config = UserConfig::default();
5500                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5501                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5502                         .unwrap();
5503
5504                 // This test checks that if we have two cheaper paths and one more expensive path,
5505                 // so that liquidity-wise any 2 of 3 combination is sufficient,
5506                 // two cheaper paths will be taken.
5507                 // These paths have equal available liquidity.
5508
5509                 // We need a combination of 3 paths:
5510                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
5511                 // Note that these paths overlap (channels 5, 12, 13).
5512                 // Each path will have 100 sats capacity, those channels which
5513                 // are used twice will have 200 sats capacity.
5514
5515                 // Disable other potential paths.
5516                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5517                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5518                         short_channel_id: 2,
5519                         timestamp: 2,
5520                         flags: 2,
5521                         cltv_expiry_delta: 0,
5522                         htlc_minimum_msat: 0,
5523                         htlc_maximum_msat: 100_000,
5524                         fee_base_msat: 0,
5525                         fee_proportional_millionths: 0,
5526                         excess_data: Vec::new()
5527                 });
5528                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5529                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5530                         short_channel_id: 7,
5531                         timestamp: 2,
5532                         flags: 2,
5533                         cltv_expiry_delta: 0,
5534                         htlc_minimum_msat: 0,
5535                         htlc_maximum_msat: 100_000,
5536                         fee_base_msat: 0,
5537                         fee_proportional_millionths: 0,
5538                         excess_data: Vec::new()
5539                 });
5540
5541                 // Path via {node0, node2} is channels {1, 3, 5}.
5542                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5543                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5544                         short_channel_id: 1,
5545                         timestamp: 2,
5546                         flags: 0,
5547                         cltv_expiry_delta: 0,
5548                         htlc_minimum_msat: 0,
5549                         htlc_maximum_msat: 100_000,
5550                         fee_base_msat: 0,
5551                         fee_proportional_millionths: 0,
5552                         excess_data: Vec::new()
5553                 });
5554                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5555                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5556                         short_channel_id: 3,
5557                         timestamp: 2,
5558                         flags: 0,
5559                         cltv_expiry_delta: 0,
5560                         htlc_minimum_msat: 0,
5561                         htlc_maximum_msat: 100_000,
5562                         fee_base_msat: 0,
5563                         fee_proportional_millionths: 0,
5564                         excess_data: Vec::new()
5565                 });
5566
5567                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
5568                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5569                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5570                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5571                         short_channel_id: 5,
5572                         timestamp: 2,
5573                         flags: 0,
5574                         cltv_expiry_delta: 0,
5575                         htlc_minimum_msat: 0,
5576                         htlc_maximum_msat: 200_000,
5577                         fee_base_msat: 0,
5578                         fee_proportional_millionths: 0,
5579                         excess_data: Vec::new()
5580                 });
5581
5582                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5583                 // Add 100 sats to the capacities of {12, 13}, because these channels
5584                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5585                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5586                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5587                         short_channel_id: 12,
5588                         timestamp: 2,
5589                         flags: 0,
5590                         cltv_expiry_delta: 0,
5591                         htlc_minimum_msat: 0,
5592                         htlc_maximum_msat: 200_000,
5593                         fee_base_msat: 0,
5594                         fee_proportional_millionths: 0,
5595                         excess_data: Vec::new()
5596                 });
5597                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5598                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5599                         short_channel_id: 13,
5600                         timestamp: 2,
5601                         flags: 0,
5602                         cltv_expiry_delta: 0,
5603                         htlc_minimum_msat: 0,
5604                         htlc_maximum_msat: 200_000,
5605                         fee_base_msat: 0,
5606                         fee_proportional_millionths: 0,
5607                         excess_data: Vec::new()
5608                 });
5609
5610                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5611                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5612                         short_channel_id: 6,
5613                         timestamp: 2,
5614                         flags: 0,
5615                         cltv_expiry_delta: 0,
5616                         htlc_minimum_msat: 0,
5617                         htlc_maximum_msat: 100_000,
5618                         fee_base_msat: 1_000,
5619                         fee_proportional_millionths: 0,
5620                         excess_data: Vec::new()
5621                 });
5622                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5623                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5624                         short_channel_id: 11,
5625                         timestamp: 2,
5626                         flags: 0,
5627                         cltv_expiry_delta: 0,
5628                         htlc_minimum_msat: 0,
5629                         htlc_maximum_msat: 100_000,
5630                         fee_base_msat: 0,
5631                         fee_proportional_millionths: 0,
5632                         excess_data: Vec::new()
5633                 });
5634
5635                 // Path via {node7, node2} is channels {12, 13, 5}.
5636                 // We already limited them to 200 sats (they are used twice for 100 sats).
5637                 // Nothing to do here.
5638
5639                 {
5640                         // Now, attempt to route 180 sats.
5641                         // Our algorithm should provide us with these 2 paths.
5642                         let route_params = RouteParameters::from_payment_params_and_value(
5643                                 payment_params, 180_000);
5644                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5645                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5646                         assert_eq!(route.paths.len(), 2);
5647
5648                         let mut total_value_transferred_msat = 0;
5649                         let mut total_paid_msat = 0;
5650                         for path in &route.paths {
5651                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5652                                 total_value_transferred_msat += path.final_value_msat();
5653                                 for hop in &path.hops {
5654                                         total_paid_msat += hop.fee_msat;
5655                                 }
5656                         }
5657                         // If we paid fee, this would be higher.
5658                         assert_eq!(total_value_transferred_msat, 180_000);
5659                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5660                         assert_eq!(total_fees_paid, 0);
5661                 }
5662         }
5663
5664         #[test]
5665         fn fees_on_mpp_route_test() {
5666                 // This test makes sure that MPP algorithm properly takes into account
5667                 // fees charged on the channels, by making the fees impactful:
5668                 // if the fee is not properly accounted for, the behavior is different.
5669                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5670                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5671                 let scorer = ln_test_utils::TestScorer::new();
5672                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5673                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5674                 let config = UserConfig::default();
5675                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5676                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5677                         .unwrap();
5678
5679                 // We need a route consisting of 2 paths:
5680                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
5681                 // We will route 200 sats, Each path will have 100 sats capacity.
5682
5683                 // This test is not particularly stable: e.g.,
5684                 // there's a way to route via {node0, node2, node4}.
5685                 // It works while pathfinding is deterministic, but can be broken otherwise.
5686                 // It's fine to ignore this concern for now.
5687
5688                 // Disable other potential paths.
5689                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5690                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5691                         short_channel_id: 2,
5692                         timestamp: 2,
5693                         flags: 2,
5694                         cltv_expiry_delta: 0,
5695                         htlc_minimum_msat: 0,
5696                         htlc_maximum_msat: 100_000,
5697                         fee_base_msat: 0,
5698                         fee_proportional_millionths: 0,
5699                         excess_data: Vec::new()
5700                 });
5701
5702                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5703                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5704                         short_channel_id: 7,
5705                         timestamp: 2,
5706                         flags: 2,
5707                         cltv_expiry_delta: 0,
5708                         htlc_minimum_msat: 0,
5709                         htlc_maximum_msat: 100_000,
5710                         fee_base_msat: 0,
5711                         fee_proportional_millionths: 0,
5712                         excess_data: Vec::new()
5713                 });
5714
5715                 // Path via {node0, node2} is channels {1, 3, 5}.
5716                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5717                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5718                         short_channel_id: 1,
5719                         timestamp: 2,
5720                         flags: 0,
5721                         cltv_expiry_delta: 0,
5722                         htlc_minimum_msat: 0,
5723                         htlc_maximum_msat: 100_000,
5724                         fee_base_msat: 0,
5725                         fee_proportional_millionths: 0,
5726                         excess_data: Vec::new()
5727                 });
5728                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5729                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5730                         short_channel_id: 3,
5731                         timestamp: 2,
5732                         flags: 0,
5733                         cltv_expiry_delta: 0,
5734                         htlc_minimum_msat: 0,
5735                         htlc_maximum_msat: 100_000,
5736                         fee_base_msat: 0,
5737                         fee_proportional_millionths: 0,
5738                         excess_data: Vec::new()
5739                 });
5740
5741                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5742                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5743                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5744                         short_channel_id: 5,
5745                         timestamp: 2,
5746                         flags: 0,
5747                         cltv_expiry_delta: 0,
5748                         htlc_minimum_msat: 0,
5749                         htlc_maximum_msat: 100_000,
5750                         fee_base_msat: 0,
5751                         fee_proportional_millionths: 0,
5752                         excess_data: Vec::new()
5753                 });
5754
5755                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5756                 // All channels should be 100 sats capacity. But for the fee experiment,
5757                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
5758                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
5759                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
5760                 // so no matter how large are other channels,
5761                 // the whole path will be limited by 100 sats with just these 2 conditions:
5762                 // - channel 12 capacity is 250 sats
5763                 // - fee for channel 6 is 150 sats
5764                 // Let's test this by enforcing these 2 conditions and removing other limits.
5765                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5766                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5767                         short_channel_id: 12,
5768                         timestamp: 2,
5769                         flags: 0,
5770                         cltv_expiry_delta: 0,
5771                         htlc_minimum_msat: 0,
5772                         htlc_maximum_msat: 250_000,
5773                         fee_base_msat: 0,
5774                         fee_proportional_millionths: 0,
5775                         excess_data: Vec::new()
5776                 });
5777                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5778                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5779                         short_channel_id: 13,
5780                         timestamp: 2,
5781                         flags: 0,
5782                         cltv_expiry_delta: 0,
5783                         htlc_minimum_msat: 0,
5784                         htlc_maximum_msat: MAX_VALUE_MSAT,
5785                         fee_base_msat: 0,
5786                         fee_proportional_millionths: 0,
5787                         excess_data: Vec::new()
5788                 });
5789
5790                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5791                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5792                         short_channel_id: 6,
5793                         timestamp: 2,
5794                         flags: 0,
5795                         cltv_expiry_delta: 0,
5796                         htlc_minimum_msat: 0,
5797                         htlc_maximum_msat: MAX_VALUE_MSAT,
5798                         fee_base_msat: 150_000,
5799                         fee_proportional_millionths: 0,
5800                         excess_data: Vec::new()
5801                 });
5802                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5803                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5804                         short_channel_id: 11,
5805                         timestamp: 2,
5806                         flags: 0,
5807                         cltv_expiry_delta: 0,
5808                         htlc_minimum_msat: 0,
5809                         htlc_maximum_msat: MAX_VALUE_MSAT,
5810                         fee_base_msat: 0,
5811                         fee_proportional_millionths: 0,
5812                         excess_data: Vec::new()
5813                 });
5814
5815                 {
5816                         // Attempt to route more than available results in a failure.
5817                         let route_params = RouteParameters::from_payment_params_and_value(
5818                                 payment_params.clone(), 210_000);
5819                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5820                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5821                                         &scorer, &Default::default(), &random_seed_bytes) {
5822                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5823                         } else { panic!(); }
5824                 }
5825
5826                 {
5827                         // Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
5828                         let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5829                                 max_total_routing_fee_msat: Some(149_999) };
5830                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5831                                 &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5832                                 &scorer, &Default::default(), &random_seed_bytes) {
5833                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
5834                         } else { panic!(); }
5835                 }
5836
5837                 {
5838                         // Now, attempt to route 200 sats (exact amount we can route).
5839                         let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
5840                                 max_total_routing_fee_msat: Some(150_000) };
5841                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5842                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5843                         assert_eq!(route.paths.len(), 2);
5844
5845                         let mut total_amount_paid_msat = 0;
5846                         for path in &route.paths {
5847                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5848                                 total_amount_paid_msat += path.final_value_msat();
5849                         }
5850                         assert_eq!(total_amount_paid_msat, 200_000);
5851                         assert_eq!(route.get_total_fees(), 150_000);
5852                 }
5853         }
5854
5855         #[test]
5856         fn mpp_with_last_hops() {
5857                 // Previously, if we tried to send an MPP payment to a destination which was only reachable
5858                 // via a single last-hop route hint, we'd fail to route if we first collected routes
5859                 // totaling close but not quite enough to fund the full payment.
5860                 //
5861                 // This was because we considered last-hop hints to have exactly the sought payment amount
5862                 // instead of the amount we were trying to collect, needlessly limiting our path searching
5863                 // at the very first hop.
5864                 //
5865                 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
5866                 // criterion to cause us to refuse all routes at the last hop hint which would be considered
5867                 // to only have the remaining to-collect amount in available liquidity.
5868                 //
5869                 // This bug appeared in production in some specific channel configurations.
5870                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5871                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5872                 let scorer = ln_test_utils::TestScorer::new();
5873                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5874                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5875                 let config = UserConfig::default();
5876                 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
5877                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
5878                         .with_route_hints(vec![RouteHint(vec![RouteHintHop {
5879                                 src_node_id: nodes[2],
5880                                 short_channel_id: 42,
5881                                 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
5882                                 cltv_expiry_delta: 42,
5883                                 htlc_minimum_msat: None,
5884                                 htlc_maximum_msat: None,
5885                         }])]).unwrap().with_max_channel_saturation_power_of_half(0);
5886
5887                 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
5888                 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
5889                 // would first use the no-fee route and then fail to find a path along the second route as
5890                 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
5891                 // under 5% of our payment amount.
5892                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5893                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5894                         short_channel_id: 1,
5895                         timestamp: 2,
5896                         flags: 0,
5897                         cltv_expiry_delta: (5 << 4) | 5,
5898                         htlc_minimum_msat: 0,
5899                         htlc_maximum_msat: 99_000,
5900                         fee_base_msat: u32::max_value(),
5901                         fee_proportional_millionths: u32::max_value(),
5902                         excess_data: Vec::new()
5903                 });
5904                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5905                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5906                         short_channel_id: 2,
5907                         timestamp: 2,
5908                         flags: 0,
5909                         cltv_expiry_delta: (5 << 4) | 3,
5910                         htlc_minimum_msat: 0,
5911                         htlc_maximum_msat: 99_000,
5912                         fee_base_msat: u32::max_value(),
5913                         fee_proportional_millionths: u32::max_value(),
5914                         excess_data: Vec::new()
5915                 });
5916                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5917                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5918                         short_channel_id: 4,
5919                         timestamp: 2,
5920                         flags: 0,
5921                         cltv_expiry_delta: (4 << 4) | 1,
5922                         htlc_minimum_msat: 0,
5923                         htlc_maximum_msat: MAX_VALUE_MSAT,
5924                         fee_base_msat: 1,
5925                         fee_proportional_millionths: 0,
5926                         excess_data: Vec::new()
5927                 });
5928                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5929                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5930                         short_channel_id: 13,
5931                         timestamp: 2,
5932                         flags: 0|2, // Channel disabled
5933                         cltv_expiry_delta: (13 << 4) | 1,
5934                         htlc_minimum_msat: 0,
5935                         htlc_maximum_msat: MAX_VALUE_MSAT,
5936                         fee_base_msat: 0,
5937                         fee_proportional_millionths: 2000000,
5938                         excess_data: Vec::new()
5939                 });
5940
5941                 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
5942                 // overpay at all.
5943                 let route_params = RouteParameters::from_payment_params_and_value(
5944                         payment_params, 100_000);
5945                 let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5946                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5947                 assert_eq!(route.paths.len(), 2);
5948                 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
5949                 // Paths are manually ordered ordered by SCID, so:
5950                 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
5951                 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
5952                 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
5953                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
5954                 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
5955                 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
5956                 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
5957                 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
5958                 assert_eq!(route.get_total_fees(), 1);
5959                 assert_eq!(route.get_total_amount(), 100_000);
5960         }
5961
5962         #[test]
5963         fn drop_lowest_channel_mpp_route_test() {
5964                 // This test checks that low-capacity channel is dropped when after
5965                 // path finding we realize that we found more capacity than we need.
5966                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5967                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5968                 let scorer = ln_test_utils::TestScorer::new();
5969                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5970                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5971                 let config = UserConfig::default();
5972                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5973                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5974                         .unwrap()
5975                         .with_max_channel_saturation_power_of_half(0);
5976
5977                 // We need a route consisting of 3 paths:
5978                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5979
5980                 // The first and the second paths should be sufficient, but the third should be
5981                 // cheaper, so that we select it but drop later.
5982
5983                 // First, we set limits on these (previously unlimited) channels.
5984                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5985
5986                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5987                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5988                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5989                         short_channel_id: 1,
5990                         timestamp: 2,
5991                         flags: 0,
5992                         cltv_expiry_delta: 0,
5993                         htlc_minimum_msat: 0,
5994                         htlc_maximum_msat: 100_000,
5995                         fee_base_msat: 0,
5996                         fee_proportional_millionths: 0,
5997                         excess_data: Vec::new()
5998                 });
5999                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6000                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6001                         short_channel_id: 3,
6002                         timestamp: 2,
6003                         flags: 0,
6004                         cltv_expiry_delta: 0,
6005                         htlc_minimum_msat: 0,
6006                         htlc_maximum_msat: 50_000,
6007                         fee_base_msat: 100,
6008                         fee_proportional_millionths: 0,
6009                         excess_data: Vec::new()
6010                 });
6011
6012                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6013                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6014                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6015                         short_channel_id: 12,
6016                         timestamp: 2,
6017                         flags: 0,
6018                         cltv_expiry_delta: 0,
6019                         htlc_minimum_msat: 0,
6020                         htlc_maximum_msat: 60_000,
6021                         fee_base_msat: 100,
6022                         fee_proportional_millionths: 0,
6023                         excess_data: Vec::new()
6024                 });
6025                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6026                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6027                         short_channel_id: 13,
6028                         timestamp: 2,
6029                         flags: 0,
6030                         cltv_expiry_delta: 0,
6031                         htlc_minimum_msat: 0,
6032                         htlc_maximum_msat: 60_000,
6033                         fee_base_msat: 0,
6034                         fee_proportional_millionths: 0,
6035                         excess_data: Vec::new()
6036                 });
6037
6038                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6039                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6040                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6041                         short_channel_id: 2,
6042                         timestamp: 2,
6043                         flags: 0,
6044                         cltv_expiry_delta: 0,
6045                         htlc_minimum_msat: 0,
6046                         htlc_maximum_msat: 20_000,
6047                         fee_base_msat: 0,
6048                         fee_proportional_millionths: 0,
6049                         excess_data: Vec::new()
6050                 });
6051                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6052                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6053                         short_channel_id: 4,
6054                         timestamp: 2,
6055                         flags: 0,
6056                         cltv_expiry_delta: 0,
6057                         htlc_minimum_msat: 0,
6058                         htlc_maximum_msat: 20_000,
6059                         fee_base_msat: 0,
6060                         fee_proportional_millionths: 0,
6061                         excess_data: Vec::new()
6062                 });
6063
6064                 {
6065                         // Attempt to route more than available results in a failure.
6066                         let route_params = RouteParameters::from_payment_params_and_value(
6067                                 payment_params.clone(), 150_000);
6068                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6069                                         &our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6070                                         &scorer, &Default::default(), &random_seed_bytes) {
6071                                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
6072                         } else { panic!(); }
6073                 }
6074
6075                 {
6076                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6077                         // Our algorithm should provide us with these 3 paths.
6078                         let route_params = RouteParameters::from_payment_params_and_value(
6079                                 payment_params.clone(), 125_000);
6080                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6081                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6082                         assert_eq!(route.paths.len(), 3);
6083                         let mut total_amount_paid_msat = 0;
6084                         for path in &route.paths {
6085                                 assert_eq!(path.hops.len(), 2);
6086                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6087                                 total_amount_paid_msat += path.final_value_msat();
6088                         }
6089                         assert_eq!(total_amount_paid_msat, 125_000);
6090                 }
6091
6092                 {
6093                         // Attempt to route without the last small cheap channel
6094                         let route_params = RouteParameters::from_payment_params_and_value(
6095                                 payment_params, 90_000);
6096                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6097                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6098                         assert_eq!(route.paths.len(), 2);
6099                         let mut total_amount_paid_msat = 0;
6100                         for path in &route.paths {
6101                                 assert_eq!(path.hops.len(), 2);
6102                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6103                                 total_amount_paid_msat += path.final_value_msat();
6104                         }
6105                         assert_eq!(total_amount_paid_msat, 90_000);
6106                 }
6107         }
6108
6109         #[test]
6110         fn min_criteria_consistency() {
6111                 // Test that we don't use an inconsistent metric between updating and walking nodes during
6112                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6113                 // was updated with a different criterion from the heap sorting, resulting in loops in
6114                 // calculated paths. We test for that specific case here.
6115
6116                 // We construct a network that looks like this:
6117                 //
6118                 //            node2 -1(3)2- node3
6119                 //              2          2
6120                 //               (2)     (4)
6121                 //                  1   1
6122                 //    node1 -1(5)2- node4 -1(1)2- node6
6123                 //    2
6124                 //   (6)
6125                 //        1
6126                 // our_node
6127                 //
6128                 // We create a loop on the side of our real path - our destination is node 6, with a
6129                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6130                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6131                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6132                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6133                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6134                 // "previous hop" being set to node 3, creating a loop in the path.
6135                 let secp_ctx = Secp256k1::new();
6136                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6137                 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6138                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6139                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6140                 let scorer = ln_test_utils::TestScorer::new();
6141                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6142                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6143                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6144
6145                 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6146                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6147                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6148                         short_channel_id: 6,
6149                         timestamp: 1,
6150                         flags: 0,
6151                         cltv_expiry_delta: (6 << 4) | 0,
6152                         htlc_minimum_msat: 0,
6153                         htlc_maximum_msat: MAX_VALUE_MSAT,
6154                         fee_base_msat: 0,
6155                         fee_proportional_millionths: 0,
6156                         excess_data: Vec::new()
6157                 });
6158                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6159
6160                 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6161                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6162                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6163                         short_channel_id: 5,
6164                         timestamp: 1,
6165                         flags: 0,
6166                         cltv_expiry_delta: (5 << 4) | 0,
6167                         htlc_minimum_msat: 0,
6168                         htlc_maximum_msat: MAX_VALUE_MSAT,
6169                         fee_base_msat: 100,
6170                         fee_proportional_millionths: 0,
6171                         excess_data: Vec::new()
6172                 });
6173                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6174
6175                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6176                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6177                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6178                         short_channel_id: 4,
6179                         timestamp: 1,
6180                         flags: 0,
6181                         cltv_expiry_delta: (4 << 4) | 0,
6182                         htlc_minimum_msat: 0,
6183                         htlc_maximum_msat: MAX_VALUE_MSAT,
6184                         fee_base_msat: 0,
6185                         fee_proportional_millionths: 0,
6186                         excess_data: Vec::new()
6187                 });
6188                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6189
6190                 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6191                 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6192                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6193                         short_channel_id: 3,
6194                         timestamp: 1,
6195                         flags: 0,
6196                         cltv_expiry_delta: (3 << 4) | 0,
6197                         htlc_minimum_msat: 0,
6198                         htlc_maximum_msat: MAX_VALUE_MSAT,
6199                         fee_base_msat: 0,
6200                         fee_proportional_millionths: 0,
6201                         excess_data: Vec::new()
6202                 });
6203                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6204
6205                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6206                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6207                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6208                         short_channel_id: 2,
6209                         timestamp: 1,
6210                         flags: 0,
6211                         cltv_expiry_delta: (2 << 4) | 0,
6212                         htlc_minimum_msat: 0,
6213                         htlc_maximum_msat: MAX_VALUE_MSAT,
6214                         fee_base_msat: 0,
6215                         fee_proportional_millionths: 0,
6216                         excess_data: Vec::new()
6217                 });
6218
6219                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6220                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6221                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6222                         short_channel_id: 1,
6223                         timestamp: 1,
6224                         flags: 0,
6225                         cltv_expiry_delta: (1 << 4) | 0,
6226                         htlc_minimum_msat: 100,
6227                         htlc_maximum_msat: MAX_VALUE_MSAT,
6228                         fee_base_msat: 0,
6229                         fee_proportional_millionths: 0,
6230                         excess_data: Vec::new()
6231                 });
6232                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6233
6234                 {
6235                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
6236                         let route_params = RouteParameters::from_payment_params_and_value(
6237                                 payment_params, 10_000);
6238                         let route = get_route(&our_id, &route_params, &network.read_only(), None,
6239                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6240                         assert_eq!(route.paths.len(), 1);
6241                         assert_eq!(route.paths[0].hops.len(), 3);
6242
6243                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6244                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6245                         assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6246                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6247                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6248                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6249
6250                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6251                         assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6252                         assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6253                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6254                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6255                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6256
6257                         assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6258                         assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6259                         assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6260                         assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6261                         assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6262                         assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6263                 }
6264         }
6265
6266
6267         #[test]
6268         fn exact_fee_liquidity_limit() {
6269                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6270                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
6271                 // we calculated fees on a higher value, resulting in us ignoring such paths.
6272                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6273                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6274                 let scorer = ln_test_utils::TestScorer::new();
6275                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6276                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6277                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6278
6279                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6280                 // send.
6281                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6282                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6283                         short_channel_id: 2,
6284                         timestamp: 2,
6285                         flags: 0,
6286                         cltv_expiry_delta: 0,
6287                         htlc_minimum_msat: 0,
6288                         htlc_maximum_msat: 85_000,
6289                         fee_base_msat: 0,
6290                         fee_proportional_millionths: 0,
6291                         excess_data: Vec::new()
6292                 });
6293
6294                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6295                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6296                         short_channel_id: 12,
6297                         timestamp: 2,
6298                         flags: 0,
6299                         cltv_expiry_delta: (4 << 4) | 1,
6300                         htlc_minimum_msat: 0,
6301                         htlc_maximum_msat: 270_000,
6302                         fee_base_msat: 0,
6303                         fee_proportional_millionths: 1000000,
6304                         excess_data: Vec::new()
6305                 });
6306
6307                 {
6308                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6309                         // 200% fee charged channel 13 in the 1-to-2 direction.
6310                         let mut route_params = RouteParameters::from_payment_params_and_value(
6311                                 payment_params, 90_000);
6312                         route_params.max_total_routing_fee_msat = Some(90_000*2);
6313                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6314                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6315                         assert_eq!(route.paths.len(), 1);
6316                         assert_eq!(route.paths[0].hops.len(), 2);
6317
6318                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6319                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6320                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6321                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6322                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6323                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6324
6325                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6326                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6327                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6328                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6329                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6330                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6331                 }
6332         }
6333
6334         #[test]
6335         fn htlc_max_reduction_below_min() {
6336                 // Test that if, while walking the graph, we reduce the value being sent to meet an
6337                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6338                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
6339                 // resulting in us thinking there is no possible path, even if other paths exist.
6340                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6341                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6342                 let scorer = ln_test_utils::TestScorer::new();
6343                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6344                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6345                 let config = UserConfig::default();
6346                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6347                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6348                         .unwrap();
6349
6350                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6351                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6352                 // then try to send 90_000.
6353                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6354                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6355                         short_channel_id: 2,
6356                         timestamp: 2,
6357                         flags: 0,
6358                         cltv_expiry_delta: 0,
6359                         htlc_minimum_msat: 0,
6360                         htlc_maximum_msat: 80_000,
6361                         fee_base_msat: 0,
6362                         fee_proportional_millionths: 0,
6363                         excess_data: Vec::new()
6364                 });
6365                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6366                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6367                         short_channel_id: 4,
6368                         timestamp: 2,
6369                         flags: 0,
6370                         cltv_expiry_delta: (4 << 4) | 1,
6371                         htlc_minimum_msat: 90_000,
6372                         htlc_maximum_msat: MAX_VALUE_MSAT,
6373                         fee_base_msat: 0,
6374                         fee_proportional_millionths: 0,
6375                         excess_data: Vec::new()
6376                 });
6377
6378                 {
6379                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6380                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6381                         // expensive) channels 12-13 path.
6382                         let mut route_params = RouteParameters::from_payment_params_and_value(
6383                                 payment_params, 90_000);
6384                         route_params.max_total_routing_fee_msat = Some(90_000*2);
6385                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6386                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6387                         assert_eq!(route.paths.len(), 1);
6388                         assert_eq!(route.paths[0].hops.len(), 2);
6389
6390                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6391                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6392                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6393                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6394                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6395                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6396
6397                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6398                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6399                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6400                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6401                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6402                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6403                 }
6404         }
6405
6406         #[test]
6407         fn multiple_direct_first_hops() {
6408                 // Previously we'd only ever considered one first hop path per counterparty.
6409                 // However, as we don't restrict users to one channel per peer, we really need to support
6410                 // looking at all first hop paths.
6411                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6412                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6413                 // route over multiple channels with the same first hop.
6414                 let secp_ctx = Secp256k1::new();
6415                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6416                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6417                 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6418                 let scorer = ln_test_utils::TestScorer::new();
6419                 let config = UserConfig::default();
6420                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6421                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6422                         .unwrap();
6423                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6424                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6425
6426                 {
6427                         let route_params = RouteParameters::from_payment_params_and_value(
6428                                 payment_params.clone(), 100_000);
6429                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6430                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6431                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6432                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6433                         assert_eq!(route.paths.len(), 1);
6434                         assert_eq!(route.paths[0].hops.len(), 1);
6435
6436                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6437                         assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6438                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6439                 }
6440                 {
6441                         let route_params = RouteParameters::from_payment_params_and_value(
6442                                 payment_params.clone(), 100_000);
6443                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6444                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6445                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6446                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6447                         assert_eq!(route.paths.len(), 2);
6448                         assert_eq!(route.paths[0].hops.len(), 1);
6449                         assert_eq!(route.paths[1].hops.len(), 1);
6450
6451                         assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6452                                 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6453
6454                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6455                         assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6456
6457                         assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6458                         assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6459                 }
6460
6461                 {
6462                         // If we have a bunch of outbound channels to the same node, where most are not
6463                         // sufficient to pay the full payment, but one is, we should default to just using the
6464                         // one single channel that has sufficient balance, avoiding MPP.
6465                         //
6466                         // If we have several options above the 3xpayment value threshold, we should pick the
6467                         // smallest of them, avoiding further fragmenting our available outbound balance to
6468                         // this node.
6469                         let route_params = RouteParameters::from_payment_params_and_value(
6470                                 payment_params, 100_000);
6471                         let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6472                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6473                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6474                                 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6475                                 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6476                                 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6477                                 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6478                                 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6479                                 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6480                         ]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6481                         assert_eq!(route.paths.len(), 1);
6482                         assert_eq!(route.paths[0].hops.len(), 1);
6483
6484                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6485                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6486                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6487                 }
6488         }
6489
6490         #[test]
6491         fn prefers_shorter_route_with_higher_fees() {
6492                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6493                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6494                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6495
6496                 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6497                 let scorer = ln_test_utils::TestScorer::new();
6498                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6499                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6500                 let route_params = RouteParameters::from_payment_params_and_value(
6501                         payment_params.clone(), 100);
6502                 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6503                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6504                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6505
6506                 assert_eq!(route.get_total_fees(), 100);
6507                 assert_eq!(route.get_total_amount(), 100);
6508                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6509
6510                 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6511                 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6512                 let scorer = FixedPenaltyScorer::with_penalty(100);
6513                 let route_params = RouteParameters::from_payment_params_and_value(
6514                         payment_params, 100);
6515                 let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6516                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6517                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6518
6519                 assert_eq!(route.get_total_fees(), 300);
6520                 assert_eq!(route.get_total_amount(), 100);
6521                 assert_eq!(path, vec![2, 4, 7, 10]);
6522         }
6523
6524         struct BadChannelScorer {
6525                 short_channel_id: u64,
6526         }
6527
6528         #[cfg(c_bindings)]
6529         impl Writeable for BadChannelScorer {
6530                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6531         }
6532         impl ScoreLookUp for BadChannelScorer {
6533                 type ScoreParams = ();
6534                 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6535                         if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value()  } else { 0  }
6536                 }
6537         }
6538
6539         struct BadNodeScorer {
6540                 node_id: NodeId,
6541         }
6542
6543         #[cfg(c_bindings)]
6544         impl Writeable for BadNodeScorer {
6545                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6546         }
6547
6548         impl ScoreLookUp for BadNodeScorer {
6549                 type ScoreParams = ();
6550                 fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6551                         if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6552                 }
6553         }
6554
6555         #[test]
6556         fn avoids_routing_through_bad_channels_and_nodes() {
6557                 let (secp_ctx, network, _, _, logger) = build_graph();
6558                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6559                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6560                 let network_graph = network.read_only();
6561
6562                 // A path to nodes[6] exists when no penalties are applied to any channel.
6563                 let scorer = ln_test_utils::TestScorer::new();
6564                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6565                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6566                 let route_params = RouteParameters::from_payment_params_and_value(
6567                         payment_params, 100);
6568                 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6569                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6570                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6571
6572                 assert_eq!(route.get_total_fees(), 100);
6573                 assert_eq!(route.get_total_amount(), 100);
6574                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
6575
6576                 // A different path to nodes[6] exists if channel 6 cannot be routed over.
6577                 let scorer = BadChannelScorer { short_channel_id: 6 };
6578                 let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6579                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6580                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6581
6582                 assert_eq!(route.get_total_fees(), 300);
6583                 assert_eq!(route.get_total_amount(), 100);
6584                 assert_eq!(path, vec![2, 4, 7, 10]);
6585
6586                 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6587                 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6588                 match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6589                         &scorer, &Default::default(), &random_seed_bytes) {
6590                                 Err(LightningError { err, .. } ) => {
6591                                         assert_eq!(err, "Failed to find a path to the given destination");
6592                                 },
6593                                 Ok(_) => panic!("Expected error"),
6594                 }
6595         }
6596
6597         #[test]
6598         fn total_fees_single_path() {
6599                 let route = Route {
6600                         paths: vec![Path { hops: vec![
6601                                 RouteHop {
6602                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6603                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6604                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6605                                 },
6606                                 RouteHop {
6607                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6608                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6609                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6610                                 },
6611                                 RouteHop {
6612                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6613                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6614                                         short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6615                                 },
6616                         ], blinded_tail: None }],
6617                         route_params: None,
6618                 };
6619
6620                 assert_eq!(route.get_total_fees(), 250);
6621                 assert_eq!(route.get_total_amount(), 225);
6622         }
6623
6624         #[test]
6625         fn total_fees_multi_path() {
6626                 let route = Route {
6627                         paths: vec![Path { hops: vec![
6628                                 RouteHop {
6629                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6630                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6631                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6632                                 },
6633                                 RouteHop {
6634                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6635                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6636                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6637                                 },
6638                         ], blinded_tail: None }, Path { hops: vec![
6639                                 RouteHop {
6640                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6641                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6642                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6643                                 },
6644                                 RouteHop {
6645                                         pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6646                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6647                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6648                                 },
6649                         ], blinded_tail: None }],
6650                         route_params: None,
6651                 };
6652
6653                 assert_eq!(route.get_total_fees(), 200);
6654                 assert_eq!(route.get_total_amount(), 300);
6655         }
6656
6657         #[test]
6658         fn total_empty_route_no_panic() {
6659                 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
6660                 // would both panic if the route was completely empty. We test to ensure they return 0
6661                 // here, even though its somewhat nonsensical as a route.
6662                 let route = Route { paths: Vec::new(), route_params: None };
6663
6664                 assert_eq!(route.get_total_fees(), 0);
6665                 assert_eq!(route.get_total_amount(), 0);
6666         }
6667
6668         #[test]
6669         fn limits_total_cltv_delta() {
6670                 let (secp_ctx, network, _, _, logger) = build_graph();
6671                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6672                 let network_graph = network.read_only();
6673
6674                 let scorer = ln_test_utils::TestScorer::new();
6675
6676                 // Make sure that generally there is at least one route available
6677                 let feasible_max_total_cltv_delta = 1008;
6678                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6679                         .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
6680                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6681                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6682                 let route_params = RouteParameters::from_payment_params_and_value(
6683                         feasible_payment_params, 100);
6684                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6685                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6686                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6687                 assert_ne!(path.len(), 0);
6688
6689                 // But not if we exclude all paths on the basis of their accumulated CLTV delta
6690                 let fail_max_total_cltv_delta = 23;
6691                 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6692                         .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
6693                 let route_params = RouteParameters::from_payment_params_and_value(
6694                         fail_payment_params, 100);
6695                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6696                         &Default::default(), &random_seed_bytes)
6697                 {
6698                         Err(LightningError { err, .. } ) => {
6699                                 assert_eq!(err, "Failed to find a path to the given destination");
6700                         },
6701                         Ok(_) => panic!("Expected error"),
6702                 }
6703         }
6704
6705         #[test]
6706         fn avoids_recently_failed_paths() {
6707                 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
6708                 // randomly inserting channels into it until we can't find a route anymore.
6709                 let (secp_ctx, network, _, _, logger) = build_graph();
6710                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6711                 let network_graph = network.read_only();
6712
6713                 let scorer = ln_test_utils::TestScorer::new();
6714                 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
6715                         .with_max_path_count(1);
6716                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6717                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6718
6719                 // We should be able to find a route initially, and then after we fail a few random
6720                 // channels eventually we won't be able to any longer.
6721                 let route_params = RouteParameters::from_payment_params_and_value(
6722                         payment_params.clone(), 100);
6723                 assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6724                         &scorer, &Default::default(), &random_seed_bytes).is_ok());
6725                 loop {
6726                         let route_params = RouteParameters::from_payment_params_and_value(
6727                                 payment_params.clone(), 100);
6728                         if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
6729                                 Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
6730                         {
6731                                 for chan in route.paths[0].hops.iter() {
6732                                         assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
6733                                 }
6734                                 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
6735                                         % route.paths[0].hops.len();
6736                                 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
6737                         } else { break; }
6738                 }
6739         }
6740
6741         #[test]
6742         fn limits_path_length() {
6743                 let (secp_ctx, network, _, _, logger) = build_line_graph();
6744                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6745                 let network_graph = network.read_only();
6746
6747                 let scorer = ln_test_utils::TestScorer::new();
6748                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6749                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6750
6751                 // First check we can actually create a long route on this graph.
6752                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
6753                 let route_params = RouteParameters::from_payment_params_and_value(
6754                         feasible_payment_params, 100);
6755                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6756                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
6757                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6758                 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
6759
6760                 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
6761                 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
6762                 let route_params = RouteParameters::from_payment_params_and_value(
6763                         fail_payment_params, 100);
6764                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
6765                         &Default::default(), &random_seed_bytes)
6766                 {
6767                         Err(LightningError { err, .. } ) => {
6768                                 assert_eq!(err, "Failed to find a path to the given destination");
6769                         },
6770                         Ok(_) => panic!("Expected error"),
6771                 }
6772         }
6773
6774         #[test]
6775         fn adds_and_limits_cltv_offset() {
6776                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6777                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6778
6779                 let scorer = ln_test_utils::TestScorer::new();
6780
6781                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6782                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6783                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6784                 let route_params = RouteParameters::from_payment_params_and_value(
6785                         payment_params.clone(), 100);
6786                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6787                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6788                 assert_eq!(route.paths.len(), 1);
6789
6790                 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6791
6792                 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
6793                 let mut route_default = route.clone();
6794                 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
6795                 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6796                 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
6797                 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
6798                 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
6799
6800                 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
6801                 let mut route_limited = route.clone();
6802                 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
6803                 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
6804                 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
6805                 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
6806                 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
6807         }
6808
6809         #[test]
6810         fn adds_plausible_cltv_offset() {
6811                 let (secp_ctx, network, _, _, logger) = build_graph();
6812                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6813                 let network_graph = network.read_only();
6814                 let network_nodes = network_graph.nodes();
6815                 let network_channels = network_graph.channels();
6816                 let scorer = ln_test_utils::TestScorer::new();
6817                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6818                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
6819                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6820
6821                 let route_params = RouteParameters::from_payment_params_and_value(
6822                         payment_params.clone(), 100);
6823                 let mut route = get_route(&our_id, &route_params, &network_graph, None,
6824                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6825                 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
6826
6827                 let mut path_plausibility = vec![];
6828
6829                 for p in route.paths {
6830                         // 1. Select random observation point
6831                         let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
6832                         let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
6833
6834                         prng.process_in_place(&mut random_bytes);
6835                         let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
6836                         let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
6837
6838                         // 2. Calculate what CLTV expiry delta we would observe there
6839                         let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
6840
6841                         // 3. Starting from the observation point, find candidate paths
6842                         let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
6843                         candidates.push_back((observation_point, vec![]));
6844
6845                         let mut found_plausible_candidate = false;
6846
6847                         'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
6848                                 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
6849                                         if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
6850                                                 found_plausible_candidate = true;
6851                                                 break 'candidate_loop;
6852                                         }
6853                                 }
6854
6855                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
6856                                         for channel_id in &cur_node.channels {
6857                                                 if let Some(channel_info) = network_channels.get(&channel_id) {
6858                                                         if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
6859                                                                 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
6860                                                                 if cur_path_cltv_deltas.iter().sum::<u32>()
6861                                                                         .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
6862                                                                         let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
6863                                                                         new_path_cltv_deltas.push(next_cltv_expiry_delta);
6864                                                                         candidates.push_back((*next_id, new_path_cltv_deltas));
6865                                                                 }
6866                                                         }
6867                                                 }
6868                                         }
6869                                 }
6870                         }
6871
6872                         path_plausibility.push(found_plausible_candidate);
6873                 }
6874                 assert!(path_plausibility.iter().all(|x| *x));
6875         }
6876
6877         #[test]
6878         fn builds_correct_path_from_hops() {
6879                 let (secp_ctx, network, _, _, logger) = build_graph();
6880                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6881                 let network_graph = network.read_only();
6882
6883                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6884                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6885
6886                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
6887                 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
6888                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
6889                 let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
6890                         Arc::clone(&logger), &random_seed_bytes).unwrap();
6891                 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
6892                 assert_eq!(hops.len(), route.paths[0].hops.len());
6893                 for (idx, hop_pubkey) in hops.iter().enumerate() {
6894                         assert!(*hop_pubkey == route_hop_pubkeys[idx]);
6895                 }
6896         }
6897
6898         #[test]
6899         fn avoids_saturating_channels() {
6900                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6901                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6902                 let decay_params = ProbabilisticScoringDecayParameters::default();
6903                 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
6904
6905                 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
6906                 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
6907                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6908                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6909                         short_channel_id: 4,
6910                         timestamp: 2,
6911                         flags: 0,
6912                         cltv_expiry_delta: (4 << 4) | 1,
6913                         htlc_minimum_msat: 0,
6914                         htlc_maximum_msat: 250_000_000,
6915                         fee_base_msat: 0,
6916                         fee_proportional_millionths: 0,
6917                         excess_data: Vec::new()
6918                 });
6919                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6920                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6921                         short_channel_id: 13,
6922                         timestamp: 2,
6923                         flags: 0,
6924                         cltv_expiry_delta: (13 << 4) | 1,
6925                         htlc_minimum_msat: 0,
6926                         htlc_maximum_msat: 250_000_000,
6927                         fee_base_msat: 0,
6928                         fee_proportional_millionths: 0,
6929                         excess_data: Vec::new()
6930                 });
6931
6932                 let config = UserConfig::default();
6933                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6934                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6935                         .unwrap();
6936                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6937                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6938                 // 100,000 sats is less than the available liquidity on each channel, set above.
6939                 let route_params = RouteParameters::from_payment_params_and_value(
6940                         payment_params, 100_000_000);
6941                 let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6942                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
6943                 assert_eq!(route.paths.len(), 2);
6944                 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
6945                         (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
6946         }
6947
6948         #[cfg(feature = "std")]
6949         pub(super) fn random_init_seed() -> u64 {
6950                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
6951                 use core::hash::{BuildHasher, Hasher};
6952                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
6953                 println!("Using seed of {}", seed);
6954                 seed
6955         }
6956
6957         #[test]
6958         #[cfg(feature = "std")]
6959         fn generate_routes() {
6960                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6961
6962                 let logger = ln_test_utils::TestLogger::new();
6963                 let graph = match super::bench_utils::read_network_graph(&logger) {
6964                         Ok(f) => f,
6965                         Err(e) => {
6966                                 eprintln!("{}", e);
6967                                 return;
6968                         },
6969                 };
6970
6971                 let params = ProbabilisticScoringFeeParameters::default();
6972                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6973                 let features = super::Bolt11InvoiceFeatures::empty();
6974
6975                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
6976         }
6977
6978         #[test]
6979         #[cfg(feature = "std")]
6980         fn generate_routes_mpp() {
6981                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
6982
6983                 let logger = ln_test_utils::TestLogger::new();
6984                 let graph = match super::bench_utils::read_network_graph(&logger) {
6985                         Ok(f) => f,
6986                         Err(e) => {
6987                                 eprintln!("{}", e);
6988                                 return;
6989                         },
6990                 };
6991
6992                 let params = ProbabilisticScoringFeeParameters::default();
6993                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
6994                 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
6995
6996                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
6997         }
6998
6999         #[test]
7000         #[cfg(feature = "std")]
7001         fn generate_large_mpp_routes() {
7002                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
7003
7004                 let logger = ln_test_utils::TestLogger::new();
7005                 let graph = match super::bench_utils::read_network_graph(&logger) {
7006                         Ok(f) => f,
7007                         Err(e) => {
7008                                 eprintln!("{}", e);
7009                                 return;
7010                         },
7011                 };
7012
7013                 let params = ProbabilisticScoringFeeParameters::default();
7014                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
7015                 let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7016
7017                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 1_000_000, 2);
7018         }
7019
7020         #[test]
7021         fn honors_manual_penalties() {
7022                 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7023                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7024
7025                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7026                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7027
7028                 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7029                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7030
7031                 // First check set manual penalties are returned by the scorer.
7032                 let usage = ChannelUsage {
7033                         amount_msat: 0,
7034                         inflight_htlc_msat: 0,
7035                         effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7036                 };
7037                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7038                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7039                 let network_graph = network_graph.read_only();
7040                 let channels = network_graph.channels();
7041                 let channel = channels.get(&5).unwrap();
7042                 let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7043                 let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7044                         info: info.0,
7045                         short_channel_id: 5,
7046                 });
7047                 assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7048
7049                 // Then check we can get a normal route
7050                 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7051                 let route_params = RouteParameters::from_payment_params_and_value(
7052                         payment_params, 100);
7053                 let route = get_route(&our_id, &route_params, &network_graph, None,
7054                         Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7055                 assert!(route.is_ok());
7056
7057                 // Then check that we can't get a route if we ban an intermediate node.
7058                 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7059                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7060                 assert!(route.is_err());
7061
7062                 // Finally make sure we can route again, when we remove the ban.
7063                 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7064                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7065                 assert!(route.is_ok());
7066         }
7067
7068         #[test]
7069         fn abide_by_route_hint_max_htlc() {
7070                 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7071                 // params in the final route.
7072                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7073                 let netgraph = network_graph.read_only();
7074                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7075                 let scorer = ln_test_utils::TestScorer::new();
7076                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7077                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7078                 let config = UserConfig::default();
7079
7080                 let max_htlc_msat = 50_000;
7081                 let route_hint_1 = RouteHint(vec![RouteHintHop {
7082                         src_node_id: nodes[2],
7083                         short_channel_id: 42,
7084                         fees: RoutingFees {
7085                                 base_msat: 100,
7086                                 proportional_millionths: 0,
7087                         },
7088                         cltv_expiry_delta: 10,
7089                         htlc_minimum_msat: None,
7090                         htlc_maximum_msat: Some(max_htlc_msat),
7091                 }]);
7092                 let dest_node_id = ln_test_utils::pubkey(42);
7093                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7094                         .with_route_hints(vec![route_hint_1.clone()]).unwrap()
7095                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7096                         .unwrap();
7097
7098                 // Make sure we'll error if our route hints don't have enough liquidity according to their
7099                 // htlc_maximum_msat.
7100                 let mut route_params = RouteParameters::from_payment_params_and_value(
7101                         payment_params, max_htlc_msat + 1);
7102                 route_params.max_total_routing_fee_msat = None;
7103                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7104                         &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7105                         &random_seed_bytes)
7106                 {
7107                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
7108                 } else { panic!(); }
7109
7110                 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7111                 let mut route_hint_2 = route_hint_1.clone();
7112                 route_hint_2.0[0].short_channel_id = 43;
7113                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7114                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7115                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7116                         .unwrap();
7117                 let mut route_params = RouteParameters::from_payment_params_and_value(
7118                         payment_params, max_htlc_msat + 1);
7119                 route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7120                 let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7121                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
7122                 assert_eq!(route.paths.len(), 2);
7123                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7124                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7125         }
7126
7127         #[test]
7128         fn direct_channel_to_hints_with_max_htlc() {
7129                 // Check that if we have a first hop channel peer that's connected to multiple provided route
7130                 // hints, that we properly split the payment between the route hints if needed.
7131                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7132                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7133                 let scorer = ln_test_utils::TestScorer::new();
7134                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7135                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7136                 let config = UserConfig::default();
7137
7138                 let our_node_id = ln_test_utils::pubkey(42);
7139                 let intermed_node_id = ln_test_utils::pubkey(43);
7140                 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7141
7142                 let amt_msat = 900_000;
7143                 let max_htlc_msat = 500_000;
7144                 let route_hint_1 = RouteHint(vec![RouteHintHop {
7145                         src_node_id: intermed_node_id,
7146                         short_channel_id: 44,
7147                         fees: RoutingFees {
7148                                 base_msat: 100,
7149                                 proportional_millionths: 0,
7150                         },
7151                         cltv_expiry_delta: 10,
7152                         htlc_minimum_msat: None,
7153                         htlc_maximum_msat: Some(max_htlc_msat),
7154                 }, RouteHintHop {
7155                         src_node_id: intermed_node_id,
7156                         short_channel_id: 45,
7157                         fees: RoutingFees {
7158                                 base_msat: 100,
7159                                 proportional_millionths: 0,
7160                         },
7161                         cltv_expiry_delta: 10,
7162                         htlc_minimum_msat: None,
7163                         // Check that later route hint max htlcs don't override earlier ones
7164                         htlc_maximum_msat: Some(max_htlc_msat - 50),
7165                 }]);
7166                 let mut route_hint_2 = route_hint_1.clone();
7167                 route_hint_2.0[0].short_channel_id = 46;
7168                 route_hint_2.0[1].short_channel_id = 47;
7169                 let dest_node_id = ln_test_utils::pubkey(44);
7170                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7171                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7172                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7173                         .unwrap();
7174
7175                 let route_params = RouteParameters::from_payment_params_and_value(
7176                         payment_params, amt_msat);
7177                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7178                         Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7179                         &Default::default(), &random_seed_bytes).unwrap();
7180                 assert_eq!(route.paths.len(), 2);
7181                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7182                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7183                 assert_eq!(route.get_total_amount(), amt_msat);
7184
7185                 // Re-run but with two first hop channels connected to the same route hint peers that must be
7186                 // split between.
7187                 let first_hops = vec![
7188                         get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7189                         get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7190                 ];
7191                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7192                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7193                         &Default::default(), &random_seed_bytes).unwrap();
7194                 assert_eq!(route.paths.len(), 2);
7195                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7196                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7197                 assert_eq!(route.get_total_amount(), amt_msat);
7198
7199                 // Make sure this works for blinded route hints.
7200                 let blinded_path = BlindedPath {
7201                         introduction_node_id: intermed_node_id,
7202                         blinding_point: ln_test_utils::pubkey(42),
7203                         blinded_hops: vec![
7204                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42), encrypted_payload: vec![] },
7205                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![] },
7206                         ],
7207                 };
7208                 let blinded_payinfo = BlindedPayInfo {
7209                         fee_base_msat: 100,
7210                         fee_proportional_millionths: 0,
7211                         htlc_minimum_msat: 1,
7212                         htlc_maximum_msat: max_htlc_msat,
7213                         cltv_expiry_delta: 10,
7214                         features: BlindedHopFeatures::empty(),
7215                 };
7216                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7217                 let payment_params = PaymentParameters::blinded(vec![
7218                         (blinded_payinfo.clone(), blinded_path.clone()),
7219                         (blinded_payinfo.clone(), blinded_path.clone())])
7220                         .with_bolt12_features(bolt12_features).unwrap();
7221                 let route_params = RouteParameters::from_payment_params_and_value(
7222                         payment_params, amt_msat);
7223                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7224                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7225                         &Default::default(), &random_seed_bytes).unwrap();
7226                 assert_eq!(route.paths.len(), 2);
7227                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7228                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7229                 assert_eq!(route.get_total_amount(), amt_msat);
7230         }
7231
7232         #[test]
7233         fn blinded_route_ser() {
7234                 let blinded_path_1 = BlindedPath {
7235                         introduction_node_id: ln_test_utils::pubkey(42),
7236                         blinding_point: ln_test_utils::pubkey(43),
7237                         blinded_hops: vec![
7238                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7239                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7240                         ],
7241                 };
7242                 let blinded_path_2 = BlindedPath {
7243                         introduction_node_id: ln_test_utils::pubkey(46),
7244                         blinding_point: ln_test_utils::pubkey(47),
7245                         blinded_hops: vec![
7246                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7247                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7248                         ],
7249                 };
7250                 // (De)serialize a Route with 1 blinded path out of two total paths.
7251                 let mut route = Route { paths: vec![Path {
7252                         hops: vec![RouteHop {
7253                                 pubkey: ln_test_utils::pubkey(50),
7254                                 node_features: NodeFeatures::empty(),
7255                                 short_channel_id: 42,
7256                                 channel_features: ChannelFeatures::empty(),
7257                                 fee_msat: 100,
7258                                 cltv_expiry_delta: 0,
7259                                 maybe_announced_channel: true,
7260                         }],
7261                         blinded_tail: Some(BlindedTail {
7262                                 hops: blinded_path_1.blinded_hops,
7263                                 blinding_point: blinded_path_1.blinding_point,
7264                                 excess_final_cltv_expiry_delta: 40,
7265                                 final_value_msat: 100,
7266                         })}, Path {
7267                         hops: vec![RouteHop {
7268                                 pubkey: ln_test_utils::pubkey(51),
7269                                 node_features: NodeFeatures::empty(),
7270                                 short_channel_id: 43,
7271                                 channel_features: ChannelFeatures::empty(),
7272                                 fee_msat: 100,
7273                                 cltv_expiry_delta: 0,
7274                                 maybe_announced_channel: true,
7275                         }], blinded_tail: None }],
7276                         route_params: None,
7277                 };
7278                 let encoded_route = route.encode();
7279                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7280                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7281                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7282
7283                 // (De)serialize a Route with two paths, each containing a blinded tail.
7284                 route.paths[1].blinded_tail = Some(BlindedTail {
7285                         hops: blinded_path_2.blinded_hops,
7286                         blinding_point: blinded_path_2.blinding_point,
7287                         excess_final_cltv_expiry_delta: 41,
7288                         final_value_msat: 101,
7289                 });
7290                 let encoded_route = route.encode();
7291                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7292                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7293                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7294         }
7295
7296         #[test]
7297         fn blinded_path_inflight_processing() {
7298                 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7299                 // account for the blinded tail's final amount_msat.
7300                 let mut inflight_htlcs = InFlightHtlcs::new();
7301                 let blinded_path = BlindedPath {
7302                         introduction_node_id: ln_test_utils::pubkey(43),
7303                         blinding_point: ln_test_utils::pubkey(48),
7304                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7305                 };
7306                 let path = Path {
7307                         hops: vec![RouteHop {
7308                                 pubkey: ln_test_utils::pubkey(42),
7309                                 node_features: NodeFeatures::empty(),
7310                                 short_channel_id: 42,
7311                                 channel_features: ChannelFeatures::empty(),
7312                                 fee_msat: 100,
7313                                 cltv_expiry_delta: 0,
7314                                 maybe_announced_channel: false,
7315                         },
7316                         RouteHop {
7317                                 pubkey: blinded_path.introduction_node_id,
7318                                 node_features: NodeFeatures::empty(),
7319                                 short_channel_id: 43,
7320                                 channel_features: ChannelFeatures::empty(),
7321                                 fee_msat: 1,
7322                                 cltv_expiry_delta: 0,
7323                                 maybe_announced_channel: false,
7324                         }],
7325                         blinded_tail: Some(BlindedTail {
7326                                 hops: blinded_path.blinded_hops,
7327                                 blinding_point: blinded_path.blinding_point,
7328                                 excess_final_cltv_expiry_delta: 0,
7329                                 final_value_msat: 200,
7330                         }),
7331                 };
7332                 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7333                 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7334                 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7335         }
7336
7337         #[test]
7338         fn blinded_path_cltv_shadow_offset() {
7339                 // Make sure we add a shadow offset when sending to blinded paths.
7340                 let blinded_path = BlindedPath {
7341                         introduction_node_id: ln_test_utils::pubkey(43),
7342                         blinding_point: ln_test_utils::pubkey(44),
7343                         blinded_hops: vec![
7344                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7345                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7346                         ],
7347                 };
7348                 let mut route = Route { paths: vec![Path {
7349                         hops: vec![RouteHop {
7350                                 pubkey: ln_test_utils::pubkey(42),
7351                                 node_features: NodeFeatures::empty(),
7352                                 short_channel_id: 42,
7353                                 channel_features: ChannelFeatures::empty(),
7354                                 fee_msat: 100,
7355                                 cltv_expiry_delta: 0,
7356                                 maybe_announced_channel: false,
7357                         },
7358                         RouteHop {
7359                                 pubkey: blinded_path.introduction_node_id,
7360                                 node_features: NodeFeatures::empty(),
7361                                 short_channel_id: 43,
7362                                 channel_features: ChannelFeatures::empty(),
7363                                 fee_msat: 1,
7364                                 cltv_expiry_delta: 0,
7365                                 maybe_announced_channel: false,
7366                         }
7367                         ],
7368                         blinded_tail: Some(BlindedTail {
7369                                 hops: blinded_path.blinded_hops,
7370                                 blinding_point: blinded_path.blinding_point,
7371                                 excess_final_cltv_expiry_delta: 0,
7372                                 final_value_msat: 200,
7373                         }),
7374                 }], route_params: None};
7375
7376                 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7377                 let (_, network_graph, _, _, _) = build_line_graph();
7378                 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7379                 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7380                 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7381         }
7382
7383         #[test]
7384         fn simple_blinded_route_hints() {
7385                 do_simple_blinded_route_hints(1);
7386                 do_simple_blinded_route_hints(2);
7387                 do_simple_blinded_route_hints(3);
7388         }
7389
7390         fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7391                 // Check that we can generate a route to a blinded path with the expected hops.
7392                 let (secp_ctx, network, _, _, logger) = build_graph();
7393                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7394                 let network_graph = network.read_only();
7395
7396                 let scorer = ln_test_utils::TestScorer::new();
7397                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7398                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7399
7400                 let mut blinded_path = BlindedPath {
7401                         introduction_node_id: nodes[2],
7402                         blinding_point: ln_test_utils::pubkey(42),
7403                         blinded_hops: Vec::with_capacity(num_blinded_hops),
7404                 };
7405                 for i in 0..num_blinded_hops {
7406                         blinded_path.blinded_hops.push(
7407                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7408                         );
7409                 }
7410                 let blinded_payinfo = BlindedPayInfo {
7411                         fee_base_msat: 100,
7412                         fee_proportional_millionths: 500,
7413                         htlc_minimum_msat: 1000,
7414                         htlc_maximum_msat: 100_000_000,
7415                         cltv_expiry_delta: 15,
7416                         features: BlindedHopFeatures::empty(),
7417                 };
7418
7419                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), blinded_path.clone())]);
7420                 let route_params = RouteParameters::from_payment_params_and_value(
7421                         payment_params, 1001);
7422                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7423                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
7424                 assert_eq!(route.paths.len(), 1);
7425                 assert_eq!(route.paths[0].hops.len(), 2);
7426
7427                 let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7428                 assert_eq!(tail.hops, blinded_path.blinded_hops);
7429                 assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7430                 assert_eq!(tail.final_value_msat, 1001);
7431
7432                 let final_hop = route.paths[0].hops.last().unwrap();
7433                 assert_eq!(final_hop.pubkey, blinded_path.introduction_node_id);
7434                 if tail.hops.len() > 1 {
7435                         assert_eq!(final_hop.fee_msat,
7436                                 blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7437                         assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7438                 } else {
7439                         assert_eq!(final_hop.fee_msat, 0);
7440                         assert_eq!(final_hop.cltv_expiry_delta, 0);
7441                 }
7442         }
7443
7444         #[test]
7445         fn blinded_path_routing_errors() {
7446                 // Check that we can generate a route to a blinded path with the expected hops.
7447                 let (secp_ctx, network, _, _, logger) = build_graph();
7448                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7449                 let network_graph = network.read_only();
7450
7451                 let scorer = ln_test_utils::TestScorer::new();
7452                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7453                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7454
7455                 let mut invalid_blinded_path = BlindedPath {
7456                         introduction_node_id: nodes[2],
7457                         blinding_point: ln_test_utils::pubkey(42),
7458                         blinded_hops: vec![
7459                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(43), encrypted_payload: vec![0; 43] },
7460                         ],
7461                 };
7462                 let blinded_payinfo = BlindedPayInfo {
7463                         fee_base_msat: 100,
7464                         fee_proportional_millionths: 500,
7465                         htlc_minimum_msat: 1000,
7466                         htlc_maximum_msat: 100_000_000,
7467                         cltv_expiry_delta: 15,
7468                         features: BlindedHopFeatures::empty(),
7469                 };
7470
7471                 let mut invalid_blinded_path_2 = invalid_blinded_path.clone();
7472                 invalid_blinded_path_2.introduction_node_id = ln_test_utils::pubkey(45);
7473                 let payment_params = PaymentParameters::blinded(vec![
7474                         (blinded_payinfo.clone(), invalid_blinded_path.clone()),
7475                         (blinded_payinfo.clone(), invalid_blinded_path_2)]);
7476                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7477                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7478                         &scorer, &Default::default(), &random_seed_bytes)
7479                 {
7480                         Err(LightningError { err, .. }) => {
7481                                 assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7482                         },
7483                         _ => panic!("Expected error")
7484                 }
7485
7486                 invalid_blinded_path.introduction_node_id = our_id;
7487                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo.clone(), invalid_blinded_path.clone())]);
7488                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7489                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7490                         &Default::default(), &random_seed_bytes)
7491                 {
7492                         Err(LightningError { err, .. }) => {
7493                                 assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7494                         },
7495                         _ => panic!("Expected error")
7496                 }
7497
7498                 invalid_blinded_path.introduction_node_id = ln_test_utils::pubkey(46);
7499                 invalid_blinded_path.blinded_hops.clear();
7500                 let payment_params = PaymentParameters::blinded(vec![(blinded_payinfo, invalid_blinded_path)]);
7501                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7502                 match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7503                         &Default::default(), &random_seed_bytes)
7504                 {
7505                         Err(LightningError { err, .. }) => {
7506                                 assert_eq!(err, "0-hop blinded path provided");
7507                         },
7508                         _ => panic!("Expected error")
7509                 }
7510         }
7511
7512         #[test]
7513         fn matching_intro_node_paths_provided() {
7514                 // Check that if multiple blinded paths with the same intro node are provided in payment
7515                 // parameters, we'll return the correct paths in the resulting MPP route.
7516                 let (secp_ctx, network, _, _, logger) = build_graph();
7517                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7518                 let network_graph = network.read_only();
7519
7520                 let scorer = ln_test_utils::TestScorer::new();
7521                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7522                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7523                 let config = UserConfig::default();
7524
7525                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7526                 let blinded_path_1 = BlindedPath {
7527                         introduction_node_id: nodes[2],
7528                         blinding_point: ln_test_utils::pubkey(42),
7529                         blinded_hops: vec![
7530                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7531                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7532                         ],
7533                 };
7534                 let blinded_payinfo_1 = BlindedPayInfo {
7535                         fee_base_msat: 0,
7536                         fee_proportional_millionths: 0,
7537                         htlc_minimum_msat: 0,
7538                         htlc_maximum_msat: 30_000,
7539                         cltv_expiry_delta: 0,
7540                         features: BlindedHopFeatures::empty(),
7541                 };
7542
7543                 let mut blinded_path_2 = blinded_path_1.clone();
7544                 blinded_path_2.blinding_point = ln_test_utils::pubkey(43);
7545                 let mut blinded_payinfo_2 = blinded_payinfo_1.clone();
7546                 blinded_payinfo_2.htlc_maximum_msat = 70_000;
7547
7548                 let blinded_hints = vec![
7549                         (blinded_payinfo_1.clone(), blinded_path_1.clone()),
7550                         (blinded_payinfo_2.clone(), blinded_path_2.clone()),
7551                 ];
7552                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7553                         .with_bolt12_features(bolt12_features).unwrap();
7554
7555                 let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7556                 route_params.max_total_routing_fee_msat = Some(100_000);
7557                 let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7558                         &scorer, &Default::default(), &random_seed_bytes).unwrap();
7559                 assert_eq!(route.paths.len(), 2);
7560                 let mut total_amount_paid_msat = 0;
7561                 for path in route.paths.into_iter() {
7562                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7563                         if let Some(bt) = &path.blinded_tail {
7564                                 assert_eq!(bt.blinding_point,
7565                                         blinded_hints.iter().find(|(p, _)| p.htlc_maximum_msat == path.final_value_msat())
7566                                                 .map(|(_, bp)| bp.blinding_point).unwrap());
7567                         } else { panic!(); }
7568                         total_amount_paid_msat += path.final_value_msat();
7569                 }
7570                 assert_eq!(total_amount_paid_msat, 100_000);
7571         }
7572
7573         #[test]
7574         fn direct_to_intro_node() {
7575                 // This previously caused a debug panic in the router when asserting
7576                 // `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7577                 // direct channels we failed to account for the fee charged for use of the blinded path.
7578
7579                 // Build a graph:
7580                 // node0 -1(1)2 - node1
7581                 // such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7582                 // doesn't account for the blinded path fee.
7583
7584                 let secp_ctx = Secp256k1::new();
7585                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7586                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7587                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7588                 let scorer = ln_test_utils::TestScorer::new();
7589                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7590                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7591
7592                 let amt_msat = 10_000_000;
7593                 let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7594                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7595                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7596                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7597                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7598                         short_channel_id: 1,
7599                         timestamp: 1,
7600                         flags: 0,
7601                         cltv_expiry_delta: 42,
7602                         htlc_minimum_msat: 1_000,
7603                         htlc_maximum_msat: 10_000_000,
7604                         fee_base_msat: 800,
7605                         fee_proportional_millionths: 0,
7606                         excess_data: Vec::new()
7607                 });
7608                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7609                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7610                         short_channel_id: 1,
7611                         timestamp: 1,
7612                         flags: 1,
7613                         cltv_expiry_delta: 42,
7614                         htlc_minimum_msat: 1_000,
7615                         htlc_maximum_msat: 10_000_000,
7616                         fee_base_msat: 800,
7617                         fee_proportional_millionths: 0,
7618                         excess_data: Vec::new()
7619                 });
7620                 let first_hops = vec![
7621                         get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7622
7623                 let blinded_path = BlindedPath {
7624                         introduction_node_id: nodes[1],
7625                         blinding_point: ln_test_utils::pubkey(42),
7626                         blinded_hops: vec![
7627                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7628                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7629                         ],
7630                 };
7631                 let blinded_payinfo = BlindedPayInfo {
7632                         fee_base_msat: 1000,
7633                         fee_proportional_millionths: 0,
7634                         htlc_minimum_msat: 1000,
7635                         htlc_maximum_msat: MAX_VALUE_MSAT,
7636                         cltv_expiry_delta: 0,
7637                         features: BlindedHopFeatures::empty(),
7638                 };
7639                 let blinded_hints = vec![(blinded_payinfo.clone(), blinded_path)];
7640
7641                 let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7642
7643                 let netgraph = network_graph.read_only();
7644                 let route_params = RouteParameters::from_payment_params_and_value(
7645                         payment_params.clone(), amt_msat);
7646                 if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7647                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7648                         &Default::default(), &random_seed_bytes) {
7649                                 assert_eq!(err, "Failed to find a path to the given destination");
7650                 } else { panic!("Expected error") }
7651
7652                 // Sending an exact amount accounting for the blinded path fee works.
7653                 let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7654                 let route_params = RouteParameters::from_payment_params_and_value(
7655                         payment_params, amt_minus_blinded_path_fee);
7656                 let route = get_route(&nodes[0], &route_params, &netgraph,
7657                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7658                         &Default::default(), &random_seed_bytes).unwrap();
7659                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7660                 assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7661         }
7662
7663         #[test]
7664         fn direct_to_matching_intro_nodes() {
7665                 // This previously caused us to enter `unreachable` code in the following situation:
7666                 // 1. We add a route candidate for intro_node contributing a high amount
7667                 // 2. We add a first_hop<>intro_node route candidate for the same high amount
7668                 // 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7669                 //    amount, and update our route candidate for intro_node for the lower amount
7670                 // 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7671                 //    lower contribution amount, but fail (this was previously caused by failure to account for
7672                 //    blinded path fees when adding first_hop<>intro_node candidates)
7673                 // 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7674                 //    candidate still thinks its path is contributing the original higher amount. This caused us
7675                 //    to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7676                 //    larger amount
7677                 let secp_ctx = Secp256k1::new();
7678                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7679                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7680                 let scorer = ln_test_utils::TestScorer::new();
7681                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7682                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7683                 let config = UserConfig::default();
7684
7685                 // Values are taken from the fuzz input that uncovered this panic.
7686                 let amt_msat = 21_7020_5185_1403_2640;
7687                 let (_, _, _, nodes) = get_nodes(&secp_ctx);
7688                 let first_hops = vec![
7689                         get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
7690                                 18446744073709551615)];
7691
7692                 let blinded_path = BlindedPath {
7693                         introduction_node_id: nodes[1],
7694                         blinding_point: ln_test_utils::pubkey(42),
7695                         blinded_hops: vec![
7696                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7697                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7698                         ],
7699                 };
7700                 let blinded_payinfo = BlindedPayInfo {
7701                         fee_base_msat: 5046_2720,
7702                         fee_proportional_millionths: 0,
7703                         htlc_minimum_msat: 4503_5996_2737_0496,
7704                         htlc_maximum_msat: 45_0359_9627_3704_9600,
7705                         cltv_expiry_delta: 0,
7706                         features: BlindedHopFeatures::empty(),
7707                 };
7708                 let mut blinded_hints = vec![
7709                         (blinded_payinfo.clone(), blinded_path.clone()),
7710                         (blinded_payinfo.clone(), blinded_path.clone()),
7711                 ];
7712                 blinded_hints[1].0.fee_base_msat = 419_4304;
7713                 blinded_hints[1].0.fee_proportional_millionths = 257;
7714                 blinded_hints[1].0.htlc_minimum_msat = 280_8908_6115_8400;
7715                 blinded_hints[1].0.htlc_maximum_msat = 2_8089_0861_1584_0000;
7716                 blinded_hints[1].0.cltv_expiry_delta = 0;
7717
7718                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7719                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7720                         .with_bolt12_features(bolt12_features).unwrap();
7721
7722                 let netgraph = network_graph.read_only();
7723                 let route_params = RouteParameters::from_payment_params_and_value(
7724                         payment_params, amt_msat);
7725                 let route = get_route(&nodes[0], &route_params, &netgraph,
7726                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7727                         &Default::default(), &random_seed_bytes).unwrap();
7728                 assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7729                 assert_eq!(route.get_total_amount(), amt_msat);
7730         }
7731
7732         #[test]
7733         fn we_are_intro_node_candidate_hops() {
7734                 // This previously led to a panic in the router because we'd generate a Path with only a
7735                 // BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
7736                 // where the origin node is the intro node. We now fully disallow considering candidate hops
7737                 // where the origin node is the intro node.
7738                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7739                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7740                 let scorer = ln_test_utils::TestScorer::new();
7741                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7742                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7743                 let config = UserConfig::default();
7744
7745                 // Values are taken from the fuzz input that uncovered this panic.
7746                 let amt_msat = 21_7020_5185_1423_0019;
7747
7748                 let blinded_path = BlindedPath {
7749                         introduction_node_id: our_id,
7750                         blinding_point: ln_test_utils::pubkey(42),
7751                         blinded_hops: vec![
7752                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7753                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7754                         ],
7755                 };
7756                 let blinded_payinfo = BlindedPayInfo {
7757                         fee_base_msat: 5052_9027,
7758                         fee_proportional_millionths: 0,
7759                         htlc_minimum_msat: 21_7020_5185_1423_0019,
7760                         htlc_maximum_msat: 1844_6744_0737_0955_1615,
7761                         cltv_expiry_delta: 0,
7762                         features: BlindedHopFeatures::empty(),
7763                 };
7764                 let mut blinded_hints = vec![
7765                         (blinded_payinfo.clone(), blinded_path.clone()),
7766                         (blinded_payinfo.clone(), blinded_path.clone()),
7767                 ];
7768                 blinded_hints[1].1.introduction_node_id = nodes[6];
7769
7770                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7771                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7772                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7773
7774                 let netgraph = network_graph.read_only();
7775                 let route_params = RouteParameters::from_payment_params_and_value(
7776                         payment_params, amt_msat);
7777                 if let Err(LightningError { err, .. }) = get_route(
7778                         &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7779                 ) {
7780                         assert_eq!(err, "Failed to find a path to the given destination");
7781                 } else { panic!() }
7782         }
7783
7784         #[test]
7785         fn we_are_intro_node_bp_in_final_path_fee_calc() {
7786                 // This previously led to a debug panic in the router because we'd find an invalid Path with
7787                 // 0 unblinded hops and a blinded tail, leading to the generation of a final
7788                 // PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
7789                 // the payment, when it was intended to only include the final value of the payment.
7790                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
7791                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7792                 let scorer = ln_test_utils::TestScorer::new();
7793                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7794                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7795                 let config = UserConfig::default();
7796
7797                 // Values are taken from the fuzz input that uncovered this panic.
7798                 let amt_msat = 21_7020_5185_1423_0019;
7799
7800                 let blinded_path = BlindedPath {
7801                         introduction_node_id: our_id,
7802                         blinding_point: ln_test_utils::pubkey(42),
7803                         blinded_hops: vec![
7804                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7805                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7806                         ],
7807                 };
7808                 let blinded_payinfo = BlindedPayInfo {
7809                         fee_base_msat: 10_4425_1395,
7810                         fee_proportional_millionths: 0,
7811                         htlc_minimum_msat: 21_7301_9934_9094_0931,
7812                         htlc_maximum_msat: 1844_6744_0737_0955_1615,
7813                         cltv_expiry_delta: 0,
7814                         features: BlindedHopFeatures::empty(),
7815                 };
7816                 let mut blinded_hints = vec![
7817                         (blinded_payinfo.clone(), blinded_path.clone()),
7818                         (blinded_payinfo.clone(), blinded_path.clone()),
7819                         (blinded_payinfo.clone(), blinded_path.clone()),
7820                 ];
7821                 blinded_hints[1].0.fee_base_msat = 5052_9027;
7822                 blinded_hints[1].0.htlc_minimum_msat = 21_7020_5185_1423_0019;
7823                 blinded_hints[1].0.htlc_maximum_msat = 1844_6744_0737_0955_1615;
7824
7825                 blinded_hints[2].1.introduction_node_id = nodes[6];
7826
7827                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7828                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7829                         .with_bolt12_features(bolt12_features.clone()).unwrap();
7830
7831                 let netgraph = network_graph.read_only();
7832                 let route_params = RouteParameters::from_payment_params_and_value(
7833                         payment_params, amt_msat);
7834                 if let Err(LightningError { err, .. }) = get_route(
7835                         &our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7836                 ) {
7837                         assert_eq!(err, "Failed to find a path to the given destination");
7838                 } else { panic!() }
7839         }
7840
7841         #[test]
7842         fn min_htlc_overpay_violates_max_htlc() {
7843                 do_min_htlc_overpay_violates_max_htlc(true);
7844                 do_min_htlc_overpay_violates_max_htlc(false);
7845         }
7846         fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
7847                 // Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
7848                 // hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
7849                 // to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
7850                 // that the used liquidity for a hop was less than its available liquidity limit.
7851                 let secp_ctx = Secp256k1::new();
7852                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7853                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7854                 let scorer = ln_test_utils::TestScorer::new();
7855                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7856                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7857                 let config = UserConfig::default();
7858
7859                 // Values are taken from the fuzz input that uncovered this panic.
7860                 let amt_msat = 7_4009_8048;
7861                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7862                 let first_hop_outbound_capacity = 2_7345_2000;
7863                 let first_hops = vec![get_channel_details(
7864                         Some(200), nodes[0], channelmanager::provided_init_features(&config),
7865                         first_hop_outbound_capacity
7866                 )];
7867
7868                 let base_fee = 1_6778_3453;
7869                 let htlc_min = 2_5165_8240;
7870                 let payment_params = if blinded_payee {
7871                         let blinded_path = BlindedPath {
7872                                 introduction_node_id: nodes[0],
7873                                 blinding_point: ln_test_utils::pubkey(42),
7874                                 blinded_hops: vec![
7875                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7876                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7877                                 ],
7878                         };
7879                         let blinded_payinfo = BlindedPayInfo {
7880                                 fee_base_msat: base_fee,
7881                                 fee_proportional_millionths: 0,
7882                                 htlc_minimum_msat: htlc_min,
7883                                 htlc_maximum_msat: htlc_min * 1000,
7884                                 cltv_expiry_delta: 0,
7885                                 features: BlindedHopFeatures::empty(),
7886                         };
7887                         let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7888                         PaymentParameters::blinded(vec![(blinded_payinfo, blinded_path)])
7889                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
7890                 } else {
7891                         let route_hint = RouteHint(vec![RouteHintHop {
7892                                 src_node_id: nodes[0],
7893                                 short_channel_id: 42,
7894                                 fees: RoutingFees {
7895                                         base_msat: base_fee,
7896                                         proportional_millionths: 0,
7897                                 },
7898                                 cltv_expiry_delta: 10,
7899                                 htlc_minimum_msat: Some(htlc_min),
7900                                 htlc_maximum_msat: None,
7901                         }]);
7902
7903                         PaymentParameters::from_node_id(nodes[1], 42)
7904                                 .with_route_hints(vec![route_hint]).unwrap()
7905                                 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7906                 };
7907
7908                 let netgraph = network_graph.read_only();
7909                 let route_params = RouteParameters::from_payment_params_and_value(
7910                         payment_params, amt_msat);
7911                 if let Err(LightningError { err, .. }) = get_route(
7912                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7913                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
7914                 ) {
7915                         assert_eq!(err, "Failed to find a path to the given destination");
7916                 } else { panic!() }
7917         }
7918
7919         #[test]
7920         fn previously_used_liquidity_violates_max_htlc() {
7921                 do_previously_used_liquidity_violates_max_htlc(true);
7922                 do_previously_used_liquidity_violates_max_htlc(false);
7923
7924         }
7925         fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
7926                 // Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
7927                 // contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
7928                 // candidate. In this case, the candidate does not have enough due to a previous path taking up
7929                 // some of its liquidity. Previously we would construct an invalid path and hit a debug panic
7930                 // asserting that the used liquidity for a hop was less than its available liquidity limit.
7931                 let secp_ctx = Secp256k1::new();
7932                 let logger = Arc::new(ln_test_utils::TestLogger::new());
7933                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7934                 let scorer = ln_test_utils::TestScorer::new();
7935                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
7936                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
7937                 let config = UserConfig::default();
7938
7939                 // Values are taken from the fuzz input that uncovered this panic.
7940                 let amt_msat = 52_4288;
7941                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7942                 let first_hops = vec![get_channel_details(
7943                         Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
7944                 ), get_channel_details(
7945                         Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
7946                 )];
7947
7948                 let base_fees = [0, 425_9840, 0, 0];
7949                 let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
7950                 let payment_params = if blinded_payee {
7951                         let blinded_path = BlindedPath {
7952                                 introduction_node_id: nodes[0],
7953                                 blinding_point: ln_test_utils::pubkey(42),
7954                                 blinded_hops: vec![
7955                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7956                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7957                                 ],
7958                         };
7959                         let mut blinded_hints = Vec::new();
7960                         for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
7961                                 blinded_hints.push((BlindedPayInfo {
7962                                         fee_base_msat: *base_fee,
7963                                         fee_proportional_millionths: 0,
7964                                         htlc_minimum_msat: *htlc_min,
7965                                         htlc_maximum_msat: htlc_min * 100,
7966                                         cltv_expiry_delta: 10,
7967                                         features: BlindedHopFeatures::empty(),
7968                                 }, blinded_path.clone()));
7969                         }
7970                         let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7971                         PaymentParameters::blinded(blinded_hints.clone())
7972                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
7973                 } else {
7974                         let mut route_hints = Vec::new();
7975                         for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
7976                                 route_hints.push(RouteHint(vec![RouteHintHop {
7977                                         src_node_id: nodes[0],
7978                                         short_channel_id: 42 + idx as u64,
7979                                         fees: RoutingFees {
7980                                                 base_msat: *base_fee,
7981                                                 proportional_millionths: 0,
7982                                         },
7983                                         cltv_expiry_delta: 10,
7984                                         htlc_minimum_msat: Some(*htlc_min),
7985                                         htlc_maximum_msat: Some(htlc_min * 100),
7986                                 }]));
7987                         }
7988                         PaymentParameters::from_node_id(nodes[1], 42)
7989                                 .with_route_hints(route_hints).unwrap()
7990                                 .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
7991                 };
7992
7993                 let netgraph = network_graph.read_only();
7994                 let route_params = RouteParameters::from_payment_params_and_value(
7995                         payment_params, amt_msat);
7996
7997                 let route = get_route(
7998                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
7999                         Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8000                 ).unwrap();
8001                 assert_eq!(route.paths.len(), 1);
8002                 assert_eq!(route.get_total_amount(), amt_msat);
8003         }
8004
8005         #[test]
8006         fn candidate_path_min() {
8007                 // Test that if a candidate first_hop<>network_node channel does not have enough contribution
8008                 // amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8009                 // Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8010                 // would add a connecting first_hop node that did not have enough contribution amount, leading
8011                 // to a debug panic upon invalid path construction.
8012                 let secp_ctx = Secp256k1::new();
8013                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8014                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8015                 let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8016                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8017                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8018                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8019                 let config = UserConfig::default();
8020
8021                 // Values are taken from the fuzz input that uncovered this panic.
8022                 let amt_msat = 7_4009_8048;
8023                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8024                 let first_hops = vec![get_channel_details(
8025                         Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8026                 )];
8027
8028                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8029                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8030                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8031                         short_channel_id: 6,
8032                         timestamp: 1,
8033                         flags: 0,
8034                         cltv_expiry_delta: (6 << 4) | 0,
8035                         htlc_minimum_msat: 0,
8036                         htlc_maximum_msat: MAX_VALUE_MSAT,
8037                         fee_base_msat: 0,
8038                         fee_proportional_millionths: 0,
8039                         excess_data: Vec::new()
8040                 });
8041                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8042
8043                 let htlc_min = 2_5165_8240;
8044                 let blinded_hints = vec![
8045                         (BlindedPayInfo {
8046                                 fee_base_msat: 1_6778_3453,
8047                                 fee_proportional_millionths: 0,
8048                                 htlc_minimum_msat: htlc_min,
8049                                 htlc_maximum_msat: htlc_min * 100,
8050                                 cltv_expiry_delta: 10,
8051                                 features: BlindedHopFeatures::empty(),
8052                         }, BlindedPath {
8053                                 introduction_node_id: nodes[0],
8054                                 blinding_point: ln_test_utils::pubkey(42),
8055                                 blinded_hops: vec![
8056                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8057                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8058                                 ],
8059                         })
8060                 ];
8061                 let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8062                 let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8063                         .with_bolt12_features(bolt12_features.clone()).unwrap();
8064                 let route_params = RouteParameters::from_payment_params_and_value(
8065                         payment_params, amt_msat);
8066                 let netgraph = network_graph.read_only();
8067
8068                 if let Err(LightningError { err, .. }) = get_route(
8069                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8070                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8071                         &random_seed_bytes
8072                 ) {
8073                         assert_eq!(err, "Failed to find a path to the given destination");
8074                 } else { panic!() }
8075         }
8076
8077         #[test]
8078         fn path_contribution_includes_min_htlc_overpay() {
8079                 // Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8080                 // meet a last hop's min_htlc in the total collected paths value. We now include this value and
8081                 // also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8082                 // selection, both tested here.
8083                 let secp_ctx = Secp256k1::new();
8084                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8085                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8086                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8087                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8088                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8089                 let config = UserConfig::default();
8090
8091                 // Values are taken from the fuzz input that uncovered this panic.
8092                 let amt_msat = 562_0000;
8093                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8094                 let first_hops = vec![
8095                         get_channel_details(
8096                                 Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8097                         ),
8098                 ];
8099
8100                 let htlc_mins = [49_0000, 1125_0000];
8101                 let payment_params = {
8102                         let blinded_path = BlindedPath {
8103                                 introduction_node_id: nodes[0],
8104                                 blinding_point: ln_test_utils::pubkey(42),
8105                                 blinded_hops: vec![
8106                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
8107                                         BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
8108                                 ],
8109                         };
8110                         let mut blinded_hints = Vec::new();
8111                         for htlc_min in htlc_mins.iter() {
8112                                 blinded_hints.push((BlindedPayInfo {
8113                                         fee_base_msat: 0,
8114                                         fee_proportional_millionths: 0,
8115                                         htlc_minimum_msat: *htlc_min,
8116                                         htlc_maximum_msat: *htlc_min * 100,
8117                                         cltv_expiry_delta: 10,
8118                                         features: BlindedHopFeatures::empty(),
8119                                 }, blinded_path.clone()));
8120                         }
8121                         let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8122                         PaymentParameters::blinded(blinded_hints.clone())
8123                                 .with_bolt12_features(bolt12_features.clone()).unwrap()
8124                 };
8125
8126                 let netgraph = network_graph.read_only();
8127                 let route_params = RouteParameters::from_payment_params_and_value(
8128                         payment_params, amt_msat);
8129                 let route = get_route(
8130                         &our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8131                         Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8132                         &random_seed_bytes
8133                 ).unwrap();
8134                 assert_eq!(route.paths.len(), 1);
8135                 assert_eq!(route.get_total_amount(), amt_msat);
8136         }
8137
8138         #[test]
8139         fn first_hop_preferred_over_hint() {
8140                 // Check that if we have a first hop to a peer we'd always prefer that over a route hint
8141                 // they gave us, but we'd still consider all subsequent hints if they are more attractive.
8142                 let secp_ctx = Secp256k1::new();
8143                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8144                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8145                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8146                 let scorer = ln_test_utils::TestScorer::new();
8147                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8148                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8149                 let config = UserConfig::default();
8150
8151                 let amt_msat = 1_000_000;
8152                 let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8153
8154                 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8155                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8156                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8157                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8158                         short_channel_id: 1,
8159                         timestamp: 1,
8160                         flags: 0,
8161                         cltv_expiry_delta: 42,
8162                         htlc_minimum_msat: 1_000,
8163                         htlc_maximum_msat: 10_000_000,
8164                         fee_base_msat: 800,
8165                         fee_proportional_millionths: 0,
8166                         excess_data: Vec::new()
8167                 });
8168                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8169                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8170                         short_channel_id: 1,
8171                         timestamp: 1,
8172                         flags: 1,
8173                         cltv_expiry_delta: 42,
8174                         htlc_minimum_msat: 1_000,
8175                         htlc_maximum_msat: 10_000_000,
8176                         fee_base_msat: 800,
8177                         fee_proportional_millionths: 0,
8178                         excess_data: Vec::new()
8179                 });
8180
8181                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8182                         ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8183                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8184                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8185                         short_channel_id: 2,
8186                         timestamp: 2,
8187                         flags: 0,
8188                         cltv_expiry_delta: 42,
8189                         htlc_minimum_msat: 1_000,
8190                         htlc_maximum_msat: 10_000_000,
8191                         fee_base_msat: 800,
8192                         fee_proportional_millionths: 0,
8193                         excess_data: Vec::new()
8194                 });
8195                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8196                         chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8197                         short_channel_id: 2,
8198                         timestamp: 2,
8199                         flags: 1,
8200                         cltv_expiry_delta: 42,
8201                         htlc_minimum_msat: 1_000,
8202                         htlc_maximum_msat: 10_000_000,
8203                         fee_base_msat: 800,
8204                         fee_proportional_millionths: 0,
8205                         excess_data: Vec::new()
8206                 });
8207
8208                 let dest_node_id = nodes[2];
8209
8210                 let route_hint = RouteHint(vec![RouteHintHop {
8211                         src_node_id: our_node_id,
8212                         short_channel_id: 44,
8213                         fees: RoutingFees {
8214                                 base_msat: 234,
8215                                 proportional_millionths: 0,
8216                         },
8217                         cltv_expiry_delta: 10,
8218                         htlc_minimum_msat: None,
8219                         htlc_maximum_msat: Some(5_000_000),
8220                 },
8221                 RouteHintHop {
8222                         src_node_id: nodes[0],
8223                         short_channel_id: 45,
8224                         fees: RoutingFees {
8225                                 base_msat: 123,
8226                                 proportional_millionths: 0,
8227                         },
8228                         cltv_expiry_delta: 10,
8229                         htlc_minimum_msat: None,
8230                         htlc_maximum_msat: None,
8231                 }]);
8232
8233                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8234                         .with_route_hints(vec![route_hint]).unwrap()
8235                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8236                 let route_params = RouteParameters::from_payment_params_and_value(
8237                         payment_params, amt_msat);
8238
8239                 // First create an insufficient first hop for channel with SCID 1 and check we'd use the
8240                 // route hint.
8241                 let first_hop = get_channel_details(Some(1), nodes[0],
8242                         channelmanager::provided_init_features(&config), 999_999);
8243                 let first_hops = vec![first_hop];
8244
8245                 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8246                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8247                         &Default::default(), &random_seed_bytes).unwrap();
8248                 assert_eq!(route.paths.len(), 1);
8249                 assert_eq!(route.get_total_amount(), amt_msat);
8250                 assert_eq!(route.paths[0].hops.len(), 2);
8251                 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8252                 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8253                 assert_eq!(route.get_total_fees(), 123);
8254
8255                 // Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8256                 // for a first hop channel.
8257                 let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8258                 first_hop.outbound_scid_alias = Some(44);
8259                 let first_hops = vec![first_hop];
8260
8261                 let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8262                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8263                         &Default::default(), &random_seed_bytes);
8264                 assert!(route_res.is_err());
8265
8266                 // Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8267                 // use the cheaper second hop of the route hint.
8268                 let mut first_hop = get_channel_details(Some(1), nodes[0],
8269                         channelmanager::provided_init_features(&config), 10_000_000);
8270                 first_hop.outbound_scid_alias = Some(44);
8271                 let first_hops = vec![first_hop];
8272
8273                 let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8274                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8275                         &Default::default(), &random_seed_bytes).unwrap();
8276                 assert_eq!(route.paths.len(), 1);
8277                 assert_eq!(route.get_total_amount(), amt_msat);
8278                 assert_eq!(route.paths[0].hops.len(), 2);
8279                 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8280                 assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8281                 assert_eq!(route.get_total_fees(), 123);
8282         }
8283
8284         #[test]
8285         fn allow_us_being_first_hint() {
8286                 // Check that we consider a route hint even if we are the src of the first hop.
8287                 let secp_ctx = Secp256k1::new();
8288                 let logger = Arc::new(ln_test_utils::TestLogger::new());
8289                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8290                 let scorer = ln_test_utils::TestScorer::new();
8291                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
8292                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8293                 let config = UserConfig::default();
8294
8295                 let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8296
8297                 let amt_msat = 1_000_000;
8298                 let dest_node_id = nodes[1];
8299
8300                 let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8301                 let first_hops = vec![first_hop];
8302
8303                 let route_hint = RouteHint(vec![RouteHintHop {
8304                         src_node_id: our_node_id,
8305                         short_channel_id: 44,
8306                         fees: RoutingFees {
8307                                 base_msat: 123,
8308                                 proportional_millionths: 0,
8309                         },
8310                         cltv_expiry_delta: 10,
8311                         htlc_minimum_msat: None,
8312                         htlc_maximum_msat: None,
8313                 }]);
8314
8315                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8316                         .with_route_hints(vec![route_hint]).unwrap()
8317                         .with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8318
8319                 let route_params = RouteParameters::from_payment_params_and_value(
8320                         payment_params, amt_msat);
8321
8322
8323                 let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8324                         Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8325                         &Default::default(), &random_seed_bytes).unwrap();
8326
8327                 assert_eq!(route.paths.len(), 1);
8328                 assert_eq!(route.get_total_amount(), amt_msat);
8329                 assert_eq!(route.get_total_fees(), 0);
8330                 assert_eq!(route.paths[0].hops.len(), 1);
8331
8332                 assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8333         }
8334 }
8335
8336 #[cfg(all(any(test, ldk_bench), feature = "std"))]
8337 pub(crate) mod bench_utils {
8338         use super::*;
8339         use std::fs::File;
8340         use std::time::Duration;
8341
8342         use bitcoin::hashes::Hash;
8343         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
8344
8345         use crate::chain::transaction::OutPoint;
8346         use crate::routing::scoring::ScoreUpdate;
8347         use crate::sign::{EntropySource, KeysManager};
8348         use crate::ln::ChannelId;
8349         use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
8350         use crate::ln::features::Bolt11InvoiceFeatures;
8351         use crate::routing::gossip::NetworkGraph;
8352         use crate::util::config::UserConfig;
8353         use crate::util::ser::ReadableArgs;
8354         use crate::util::test_utils::TestLogger;
8355
8356         /// Tries to open a network graph file, or panics with a URL to fetch it.
8357         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
8358                 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
8359                         .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
8360                         .or_else(|_| { // Fall back to guessing based on the binary location
8361                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8362                                 let mut path = std::env::current_exe().unwrap();
8363                                 path.pop(); // lightning-...
8364                                 path.pop(); // deps
8365                                 path.pop(); // debug
8366                                 path.pop(); // target
8367                                 path.push("lightning");
8368                                 path.push("net_graph-2023-01-18.bin");
8369                                 File::open(path)
8370                         })
8371                         .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8372                                 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8373                                 let mut path = std::env::current_exe().unwrap();
8374                                 path.pop(); // bench...
8375                                 path.pop(); // deps
8376                                 path.pop(); // debug
8377                                 path.pop(); // target
8378                                 path.pop(); // bench
8379                                 path.push("lightning");
8380                                 path.push("net_graph-2023-01-18.bin");
8381                                 File::open(path)
8382                         })
8383                 .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");
8384                 #[cfg(require_route_graph_test)]
8385                 return Ok(res.unwrap());
8386                 #[cfg(not(require_route_graph_test))]
8387                 return res;
8388         }
8389
8390         pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
8391                 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
8392         }
8393
8394         pub(crate) fn payer_pubkey() -> PublicKey {
8395                 let secp_ctx = Secp256k1::new();
8396                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8397         }
8398
8399         #[inline]
8400         pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8401                 ChannelDetails {
8402                         channel_id: ChannelId::new_zero(),
8403                         counterparty: ChannelCounterparty {
8404                                 features: channelmanager::provided_init_features(&UserConfig::default()),
8405                                 node_id,
8406                                 unspendable_punishment_reserve: 0,
8407                                 forwarding_info: None,
8408                                 outbound_htlc_minimum_msat: None,
8409                                 outbound_htlc_maximum_msat: None,
8410                         },
8411                         funding_txo: Some(OutPoint {
8412                                 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8413                         }),
8414                         channel_type: None,
8415                         short_channel_id: Some(1),
8416                         inbound_scid_alias: None,
8417                         outbound_scid_alias: None,
8418                         channel_value_satoshis: 10_000_000_000,
8419                         user_channel_id: 0,
8420                         balance_msat: 10_000_000_000,
8421                         outbound_capacity_msat: 10_000_000_000,
8422                         next_outbound_htlc_minimum_msat: 0,
8423                         next_outbound_htlc_limit_msat: 10_000_000_000,
8424                         inbound_capacity_msat: 0,
8425                         unspendable_punishment_reserve: None,
8426                         confirmations_required: None,
8427                         confirmations: None,
8428                         force_close_spend_delay: None,
8429                         is_outbound: true,
8430                         is_channel_ready: true,
8431                         is_usable: true,
8432                         is_public: true,
8433                         inbound_htlc_minimum_msat: None,
8434                         inbound_htlc_maximum_msat: None,
8435                         config: None,
8436                         feerate_sat_per_1000_weight: None,
8437                         channel_shutdown_state: Some(channelmanager::ChannelShutdownState::NotShuttingDown),
8438                 }
8439         }
8440
8441         pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
8442                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
8443                 starting_amount: u64, route_count: usize,
8444         ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
8445                 let payer = payer_pubkey();
8446                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8447                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8448
8449                 let nodes = graph.read_only().nodes().clone();
8450                 let mut route_endpoints = Vec::new();
8451                 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
8452                 // with some routes we picked being un-routable.
8453                 for _ in 0..route_count * 3 / 2 {
8454                         loop {
8455                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8456                                 let src = PublicKey::from_slice(nodes.unordered_keys()
8457                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8458                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8459                                 let dst = PublicKey::from_slice(nodes.unordered_keys()
8460                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
8461                                 let params = PaymentParameters::from_node_id(dst, 42)
8462                                         .with_bolt11_features(features.clone()).unwrap();
8463                                 let first_hop = first_hop(src);
8464                                 let amt_msat = starting_amount + seed % 1_000_000;
8465                                 let route_params = RouteParameters::from_payment_params_and_value(
8466                                         params.clone(), amt_msat);
8467                                 let path_exists =
8468                                         get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
8469                                                 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
8470                                 if path_exists {
8471                                         // ...and seed the scorer with success and failure data...
8472                                         seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8473                                         let mut score_amt = seed % 1_000_000_000;
8474                                         loop {
8475                                                 // Generate fail/success paths for a wider range of potential amounts with
8476                                                 // MPP enabled to give us a chance to apply penalties for more potential
8477                                                 // routes.
8478                                                 let mpp_features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
8479                                                 let params = PaymentParameters::from_node_id(dst, 42)
8480                                                         .with_bolt11_features(mpp_features).unwrap();
8481                                                 let route_params = RouteParameters::from_payment_params_and_value(
8482                                                         params.clone(), score_amt);
8483                                                 let route_res = get_route(&payer, &route_params, &graph.read_only(),
8484                                                         Some(&[&first_hop]), &TestLogger::new(), scorer, score_params,
8485                                                         &random_seed_bytes);
8486                                                 if let Ok(route) = route_res {
8487                                                         for path in route.paths {
8488                                                                 if seed & 0x80 == 0 {
8489                                                                         scorer.payment_path_successful(&path, Duration::ZERO);
8490                                                                 } else {
8491                                                                         let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
8492                                                                         scorer.payment_path_failed(&path, short_channel_id, Duration::ZERO);
8493                                                                 }
8494                                                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
8495                                                         }
8496                                                         break;
8497                                                 }
8498                                                 // If we couldn't find a path with a higher amount, reduce and try again.
8499                                                 score_amt /= 100;
8500                                         }
8501
8502                                         route_endpoints.push((first_hop, params, amt_msat));
8503                                         break;
8504                                 }
8505                         }
8506                 }
8507
8508                 // Because we've changed channel scores, it's possible we'll take different routes to the
8509                 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
8510                 // requires a too-high CLTV delta.
8511                 route_endpoints.retain(|(first_hop, params, amt_msat)| {
8512                         let route_params = RouteParameters::from_payment_params_and_value(
8513                                 params.clone(), *amt_msat);
8514                         get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8515                                 &TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok()
8516                 });
8517                 route_endpoints.truncate(route_count);
8518                 assert_eq!(route_endpoints.len(), route_count);
8519                 route_endpoints
8520         }
8521 }
8522
8523 #[cfg(ldk_bench)]
8524 pub mod benches {
8525         use super::*;
8526         use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
8527         use crate::sign::{EntropySource, KeysManager};
8528         use crate::ln::channelmanager;
8529         use crate::ln::features::Bolt11InvoiceFeatures;
8530         use crate::routing::gossip::NetworkGraph;
8531         use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
8532         use crate::util::config::UserConfig;
8533         use crate::util::logger::{Logger, Record};
8534         use crate::util::test_utils::TestLogger;
8535
8536         use criterion::Criterion;
8537
8538         struct DummyLogger {}
8539         impl Logger for DummyLogger {
8540                 fn log(&self, _record: Record) {}
8541         }
8542
8543         pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8544                 let logger = TestLogger::new();
8545                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8546                 let scorer = FixedPenaltyScorer::with_penalty(0);
8547                 generate_routes(bench, &network_graph, scorer, &Default::default(),
8548                         Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
8549         }
8550
8551         pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
8552                 let logger = TestLogger::new();
8553                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8554                 let scorer = FixedPenaltyScorer::with_penalty(0);
8555                 generate_routes(bench, &network_graph, scorer, &Default::default(),
8556                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8557                         "generate_mpp_routes_with_zero_penalty_scorer");
8558         }
8559
8560         pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8561                 let logger = TestLogger::new();
8562                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8563                 let params = ProbabilisticScoringFeeParameters::default();
8564                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8565                 generate_routes(bench, &network_graph, scorer, &params, Bolt11InvoiceFeatures::empty(), 0,
8566                         "generate_routes_with_probabilistic_scorer");
8567         }
8568
8569         pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8570                 let logger = TestLogger::new();
8571                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8572                 let params = ProbabilisticScoringFeeParameters::default();
8573                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8574                 generate_routes(bench, &network_graph, scorer, &params,
8575                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8576                         "generate_mpp_routes_with_probabilistic_scorer");
8577         }
8578
8579         pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
8580                 let logger = TestLogger::new();
8581                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8582                 let params = ProbabilisticScoringFeeParameters::default();
8583                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8584                 generate_routes(bench, &network_graph, scorer, &params,
8585                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8586                         "generate_large_mpp_routes_with_probabilistic_scorer");
8587         }
8588
8589         pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8590                 let logger = TestLogger::new();
8591                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8592                 let mut params = ProbabilisticScoringFeeParameters::default();
8593                 params.linear_success_probability = false;
8594                 let scorer = ProbabilisticScorer::new(
8595                         ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8596                 generate_routes(bench, &network_graph, scorer, &params,
8597                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8598                         "generate_routes_with_nonlinear_probabilistic_scorer");
8599         }
8600
8601         pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8602                 let logger = TestLogger::new();
8603                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8604                 let mut params = ProbabilisticScoringFeeParameters::default();
8605                 params.linear_success_probability = false;
8606                 let scorer = ProbabilisticScorer::new(
8607                         ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8608                 generate_routes(bench, &network_graph, scorer, &params,
8609                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
8610                         "generate_mpp_routes_with_nonlinear_probabilistic_scorer");
8611         }
8612
8613         pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
8614                 let logger = TestLogger::new();
8615                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
8616                 let mut params = ProbabilisticScoringFeeParameters::default();
8617                 params.linear_success_probability = false;
8618                 let scorer = ProbabilisticScorer::new(
8619                         ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
8620                 generate_routes(bench, &network_graph, scorer, &params,
8621                         channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
8622                         "generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
8623         }
8624
8625         fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
8626                 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
8627                 score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
8628                 bench_name: &'static str,
8629         ) {
8630                 let payer = bench_utils::payer_pubkey();
8631                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
8632                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
8633
8634                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
8635                 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
8636
8637                 // ...then benchmark finding paths between the nodes we learned.
8638                 let mut idx = 0;
8639                 bench.bench_function(bench_name, |b| b.iter(|| {
8640                         let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
8641                         let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
8642                         assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
8643                                 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());
8644                         idx += 1;
8645                 }));
8646         }
8647 }