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