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