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