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