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