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