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