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