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