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