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