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