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