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