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