lightning/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
12use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
13
14use crate::blinded_path::{BlindedHop, Direction, IntroductionNode};
15use crate::blinded_path::payment::{BlindedPaymentPath, ForwardTlvs, PaymentConstraints, PaymentForwardNode, PaymentRelay, ReceiveTlvs};
16use crate::types::payment::{PaymentHash, PaymentPreimage};
17use crate::ln::channel_state::ChannelDetails;
18use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA, RecipientOnionFields};
19use crate::types::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
20use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21use crate::ln::onion_utils;
22#[cfg(async_payments)]
23use crate::offers::static_invoice::StaticInvoice;
24use crate::offers::invoice::Bolt12Invoice;
25use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId};
26use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
27use crate::sign::EntropySource;
28use crate::sync::Mutex;
29use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
30use crate::util::logger::{Level, Logger};
31use crate::crypto::chacha20::ChaCha20;
32
33use crate::io;
34use crate::prelude::*;
35use alloc::collections::BinaryHeap;
36use core::{cmp, fmt};
37use core::ops::Deref;
38
39use lightning_types::routing::RoutingFees;
40
41pub use lightning_types::routing::{RouteHint, RouteHintHop};
42
43/// A [`Router`] implemented using [`find_route`].
44///
45/// # Privacy
46///
47/// Creating [`BlindedPaymentPath`]s may affect privacy since, if a suitable path cannot be found,
48/// it will create a one-hop path using the recipient as the introduction node if it is a announced
49/// node. Otherwise, there is no way to find a path to the introduction node in order to send a
50/// payment, and thus an `Err` is returned.
51pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
52	L::Target: Logger,
53	S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
54	ES::Target: EntropySource,
55{
56	network_graph: G,
57	logger: L,
58	entropy_source: ES,
59	scorer: S,
60	score_params: SP,
61}
62
63impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
64	L::Target: Logger,
65	S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
66	ES::Target: EntropySource,
67{
68	/// Creates a new router.
69	pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
70		Self { network_graph, logger, entropy_source, scorer, score_params }
71	}
72}
73
74impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
75	L::Target: Logger,
76	S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
77	ES::Target: EntropySource,
78{
79	fn find_route(
80		&self,
81		payer: &PublicKey,
82		params: &RouteParameters,
83		first_hops: Option<&[&ChannelDetails]>,
84		inflight_htlcs: InFlightHtlcs
85	) -> Result<Route, LightningError> {
86		let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
87		find_route(
88			payer, params, &self.network_graph, first_hops, &*self.logger,
89			&ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
90			&self.score_params,
91			&random_seed_bytes
92		)
93	}
94
95	fn create_blinded_payment_paths<
96		T: secp256k1::Signing + secp256k1::Verification
97	> (
98		&self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
99		amount_msats: u64, secp_ctx: &Secp256k1<T>
100	) -> Result<Vec<BlindedPaymentPath>, ()> {
101		// Limit the number of blinded paths that are computed.
102		const MAX_PAYMENT_PATHS: usize = 3;
103
104		// Ensure peers have at least three channels so that it is more difficult to infer the
105		// recipient's node_id.
106		const MIN_PEER_CHANNELS: usize = 3;
107
108		let has_one_peer = first_hops
109			.first()
110			.map(|details| details.counterparty.node_id)
111			.map(|node_id| first_hops
112				.iter()
113				.skip(1)
114				.all(|details| details.counterparty.node_id == node_id)
115			)
116			.unwrap_or(false);
117
118		let network_graph = self.network_graph.deref().read_only();
119		let is_recipient_announced =
120			network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
121
122		let paths = first_hops.into_iter()
123			.filter(|details| details.counterparty.features.supports_route_blinding())
124			.filter(|details| amount_msats <= details.inbound_capacity_msat)
125			.filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
126			.filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
127			// Limit to peers with announced channels unless the recipient is unannounced.
128			.filter(|details| network_graph
129					.node(&NodeId::from_pubkey(&details.counterparty.node_id))
130					.map(|node| !is_recipient_announced || node.channels.len() >= MIN_PEER_CHANNELS)
131					// Allow payments directly with the only peer when unannounced.
132					.unwrap_or(!is_recipient_announced && has_one_peer)
133			)
134			.filter_map(|details| {
135				let short_channel_id = match details.get_inbound_payment_scid() {
136					Some(short_channel_id) => short_channel_id,
137					None => return None,
138				};
139				let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
140					Some(forwarding_info) => match forwarding_info.try_into() {
141						Ok(payment_relay) => payment_relay,
142						Err(()) => return None,
143					},
144					None => return None,
145				};
146
147				let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
148				let payment_constraints = PaymentConstraints {
149					max_cltv_expiry: tlvs.tlvs().payment_constraints.max_cltv_expiry + cltv_expiry_delta,
150					htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
151				};
152				Some(PaymentForwardNode {
153					tlvs: ForwardTlvs {
154						short_channel_id,
155						payment_relay,
156						payment_constraints,
157						next_blinding_override: None,
158						features: BlindedHopFeatures::empty(),
159					},
160					node_id: details.counterparty.node_id,
161					htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
162				})
163			})
164			.map(|forward_node| {
165				BlindedPaymentPath::new(
166					&[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
167					&*self.entropy_source, secp_ctx
168				)
169			})
170			.take(MAX_PAYMENT_PATHS)
171			.collect::<Result<Vec<_>, _>>();
172
173		match paths {
174			Ok(paths) if !paths.is_empty() => Ok(paths),
175			_ => {
176				if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
177					BlindedPaymentPath::new(
178						&[], recipient, tlvs, u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source,
179						secp_ctx
180					).map(|path| vec![path])
181				} else {
182					Err(())
183				}
184			},
185		}
186	}
187}
188
189/// A `Router` that returns a fixed route one time, erroring otherwise. Useful for
190/// `ChannelManager::send_payment_with_route` to support sending to specific routes without
191/// requiring a custom `Router` implementation.
192pub(crate) struct FixedRouter {
193	// Use an `Option` to avoid needing to clone the route when `find_route` is called.
194	route: Mutex<Option<Route>>,
195}
196
197impl FixedRouter {
198	pub(crate) fn new(route: Route) -> Self {
199		Self { route: Mutex::new(Some(route)) }
200	}
201}
202
203impl Router for FixedRouter {
204	fn find_route(
205		&self, _payer: &PublicKey, _route_params: &RouteParameters,
206		_first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
207	) -> Result<Route, LightningError> {
208		self.route.lock().unwrap().take().ok_or_else(|| {
209			LightningError {
210				err: "Can't use this router to return multiple routes".to_owned(),
211				action: ErrorAction::IgnoreError,
212			}
213		})
214	}
215
216	fn create_blinded_payment_paths<
217		T: secp256k1::Signing + secp256k1::Verification
218	> (
219		&self, _recipient: PublicKey, _first_hops: Vec<ChannelDetails>, _tlvs: ReceiveTlvs,
220		_amount_msats: u64, _secp_ctx: &Secp256k1<T>
221	) -> Result<Vec<BlindedPaymentPath>, ()> {
222		// Should be unreachable as this router is only intended to provide a one-time payment route.
223		debug_assert!(false);
224		Err(())
225	}
226}
227
228/// A trait defining behavior for routing a payment.
229pub trait Router {
230	/// Finds a [`Route`] for a payment between the given `payer` and a payee.
231	///
232	/// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
233	/// and [`RouteParameters::final_value_msat`], respectively.
234	fn find_route(
235		&self, payer: &PublicKey, route_params: &RouteParameters,
236		first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
237	) -> Result<Route, LightningError>;
238
239	/// Finds a [`Route`] for a payment between the given `payer` and a payee.
240	///
241	/// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
242	/// and [`RouteParameters::final_value_msat`], respectively.
243	///
244	/// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
245	/// payment.
246	fn find_route_with_id(
247		&self, payer: &PublicKey, route_params: &RouteParameters,
248		first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
249		_payment_hash: PaymentHash, _payment_id: PaymentId
250	) -> Result<Route, LightningError> {
251		self.find_route(payer, route_params, first_hops, inflight_htlcs)
252	}
253
254	/// Creates [`BlindedPaymentPath`]s for payment to the `recipient` node. The channels in `first_hops`
255	/// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
256	/// given in `tlvs`.
257	fn create_blinded_payment_paths<
258		T: secp256k1::Signing + secp256k1::Verification
259	> (
260		&self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
261		amount_msats: u64, secp_ctx: &Secp256k1<T>
262	) -> Result<Vec<BlindedPaymentPath>, ()>;
263}
264
265/// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
266///
267/// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
268/// [`find_route`].
269///
270/// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
271pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
272	scorer: S,
273	// Maps a channel's short channel id and its direction to the liquidity used up.
274	inflight_htlcs: &'a InFlightHtlcs,
275}
276impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
277	/// Initialize a new `ScorerAccountingForInFlightHtlcs`.
278	pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
279		ScorerAccountingForInFlightHtlcs {
280			scorer,
281			inflight_htlcs
282		}
283	}
284}
285
286impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
287	type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
288	fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
289		let target = match candidate.target() {
290			Some(target) => target,
291			None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
292		};
293		let short_channel_id = match candidate.short_channel_id() {
294			Some(short_channel_id) => short_channel_id,
295			None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
296		};
297		let source = candidate.source();
298		if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
299			&source, &target, short_channel_id
300		) {
301			let usage = ChannelUsage {
302				inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
303				..usage
304			};
305
306			self.scorer.channel_penalty_msat(candidate, usage, score_params)
307		} else {
308			self.scorer.channel_penalty_msat(candidate, usage, score_params)
309		}
310	}
311}
312
313/// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
314/// in-use channel liquidity.
315#[derive(Clone)]
316pub struct InFlightHtlcs(
317	// A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
318	// is traveling in. The direction boolean is determined by checking if the HTLC source's public
319	// key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
320	// details.
321	HashMap<(u64, bool), u64>
322);
323
324impl InFlightHtlcs {
325	/// Constructs an empty `InFlightHtlcs`.
326	pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
327
328	/// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
329	pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
330		if path.hops.is_empty() { return };
331
332		let mut cumulative_msat = 0;
333		if let Some(tail) = &path.blinded_tail {
334			cumulative_msat += tail.final_value_msat;
335		}
336
337		// total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
338		// that is held up. However, the `hops` array, which is a path returned by `find_route` in
339		// the router excludes the payer node. In the following lines, the payer's information is
340		// hardcoded with an inflight value of 0 so that we can correctly represent the first hop
341		// in our sliding window of two.
342		let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
343			.map(|hop| hop.pubkey)
344			.chain(core::iter::once(payer_node_id));
345
346		// Taking the reversed vector from above, we zip it with just the reversed hops list to
347		// work "backwards" of the given path, since the last hop's `fee_msat` actually represents
348		// the total amount sent.
349		for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
350			cumulative_msat += next_hop.fee_msat;
351			self.0
352				.entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
353				.and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
354				.or_insert(cumulative_msat);
355		}
356	}
357
358	/// Adds a known HTLC given the public key of the HTLC source, target, and short channel
359	/// id.
360	pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
361		self.0
362			.entry((channel_scid, source < target))
363			.and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
364			.or_insert(used_msat);
365	}
366
367	/// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
368	/// id.
369	pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
370		self.0.get(&(channel_scid, source < target)).map(|v| *v)
371	}
372}
373
374impl Writeable for InFlightHtlcs {
375	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
376}
377
378impl Readable for InFlightHtlcs {
379	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
380		let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
381		Ok(Self(infight_map))
382	}
383}
384
385/// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
386/// that leads to it.
387#[derive(Clone, Debug, Hash, PartialEq, Eq)]
388pub struct RouteHop {
389	/// The node_id of the node at this hop.
390	pub pubkey: PublicKey,
391	/// The node_announcement features of the node at this hop. For the last hop, these may be
392	/// amended to match the features present in the invoice this node generated.
393	pub node_features: NodeFeatures,
394	/// The channel that should be used from the previous hop to reach this node.
395	pub short_channel_id: u64,
396	/// The channel_announcement features of the channel that should be used from the previous hop
397	/// to reach this node.
398	pub channel_features: ChannelFeatures,
399	/// The fee taken on this hop (for paying for the use of the *next* channel in the path).
400	/// If this is the last hop in [`Path::hops`]:
401	/// * if we're sending to a [`BlindedPaymentPath`], this is the fee paid for use of the entire
402	///   blinded path
403	/// * otherwise, this is the full value of this [`Path`]'s part of the payment
404	pub fee_msat: u64,
405	/// The CLTV delta added for this hop.
406	/// If this is the last hop in [`Path::hops`]:
407	/// * if we're sending to a [`BlindedPaymentPath`], this is the CLTV delta for the entire blinded
408	///   path
409	/// * otherwise, this is the CLTV delta expected at the destination
410	pub cltv_expiry_delta: u32,
411	/// Indicates whether this hop is possibly announced in the public network graph.
412	///
413	/// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
414	/// either know for sure it's announced in the public graph, or if any public channels exist
415	/// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
416	/// the channel to be unannounced.
417	///
418	/// Will be `true` for objects serialized with LDK version 0.0.116 and before.
419	pub maybe_announced_channel: bool,
420}
421
422impl_writeable_tlv_based!(RouteHop, {
423	(0, pubkey, required),
424	(1, maybe_announced_channel, (default_value, true)),
425	(2, node_features, required),
426	(4, short_channel_id, required),
427	(6, channel_features, required),
428	(8, fee_msat, required),
429	(10, cltv_expiry_delta, required),
430});
431
432/// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
433/// their [`Bolt12Invoice`].
434///
435/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
436#[derive(Clone, Debug, Hash, PartialEq, Eq)]
437pub struct BlindedTail {
438	/// The hops of the [`BlindedPaymentPath`] provided by the recipient.
439	pub hops: Vec<BlindedHop>,
440	/// The blinding point of the [`BlindedPaymentPath`] provided by the recipient.
441	pub blinding_point: PublicKey,
442	/// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
443	/// inferring the destination. May be 0.
444	pub excess_final_cltv_expiry_delta: u32,
445	/// The total amount paid on this [`Path`], excluding the fees.
446	pub final_value_msat: u64,
447}
448
449impl_writeable_tlv_based!(BlindedTail, {
450	(0, hops, required_vec),
451	(2, blinding_point, required),
452	(4, excess_final_cltv_expiry_delta, required),
453	(6, final_value_msat, required),
454});
455
456/// A path in a [`Route`] to the payment recipient. Must always be at least length one.
457/// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
458#[derive(Clone, Debug, Hash, PartialEq, Eq)]
459pub struct Path {
460	/// The list of unblinded hops in this [`Path`]. Must be at least length one.
461	pub hops: Vec<RouteHop>,
462	/// The blinded path at which this path terminates, if we're sending to one, and its metadata.
463	pub blinded_tail: Option<BlindedTail>,
464}
465
466impl Path {
467	/// Gets the fees for a given path, excluding any excess paid to the recipient.
468	pub fn fee_msat(&self) -> u64 {
469		match &self.blinded_tail {
470			Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
471			None => {
472				// Do not count last hop of each path since that's the full value of the payment
473				self.hops.split_last().map_or(0,
474					|(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
475			}
476		}
477	}
478
479	/// Gets the total amount paid on this [`Path`], excluding the fees.
480	pub fn final_value_msat(&self) -> u64 {
481		match &self.blinded_tail {
482			Some(blinded_tail) => blinded_tail.final_value_msat,
483			None => self.hops.last().map_or(0, |hop| hop.fee_msat)
484		}
485	}
486
487	/// Gets the final hop's CLTV expiry delta.
488	pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
489		match &self.blinded_tail {
490			Some(_) => None,
491			None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
492		}
493	}
494}
495
496/// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
497/// it can take multiple paths. Each path is composed of one or more hops through the network.
498#[derive(Clone, Debug, Hash, PartialEq, Eq)]
499pub struct Route {
500	/// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
501	/// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
502	/// the same.
503	pub paths: Vec<Path>,
504	/// The `route_params` parameter passed to [`find_route`].
505	///
506	/// This is used by `ChannelManager` to track information which may be required for retries.
507	///
508	/// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
509	pub route_params: Option<RouteParameters>,
510}
511
512impl Route {
513	/// Returns the total amount of fees paid on this [`Route`].
514	///
515	/// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
516	/// the recipient, which can happen in excess of the amount passed to [`find_route`] via
517	/// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
518	///
519	/// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
520	pub fn get_total_fees(&self) -> u64 {
521		let overpaid_value_msat = self.route_params.as_ref()
522			.map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
523		overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
524	}
525
526	/// Returns the total amount paid on this [`Route`], excluding the fees.
527	///
528	/// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
529	/// we had to reach the [`htlc_minimum_msat`] limits.
530	///
531	/// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
532	pub fn get_total_amount(&self) -> u64 {
533		self.paths.iter().map(|path| path.final_value_msat()).sum()
534	}
535}
536
537impl fmt::Display for Route {
538	fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
539		log_route!(self).fmt(f)
540	}
541}
542
543const SERIALIZATION_VERSION: u8 = 1;
544const MIN_SERIALIZATION_VERSION: u8 = 1;
545
546impl Writeable for Route {
547	fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
548		write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
549		(self.paths.len() as u64).write(writer)?;
550		let mut blinded_tails = Vec::new();
551		for (idx, path) in self.paths.iter().enumerate() {
552			(path.hops.len() as u8).write(writer)?;
553			for hop in path.hops.iter() {
554				hop.write(writer)?;
555			}
556			if let Some(blinded_tail) = &path.blinded_tail {
557				if blinded_tails.is_empty() {
558					blinded_tails = Vec::with_capacity(path.hops.len());
559					for _ in 0..idx {
560						blinded_tails.push(None);
561					}
562				}
563				blinded_tails.push(Some(blinded_tail));
564			} else if !blinded_tails.is_empty() { blinded_tails.push(None); }
565		}
566		write_tlv_fields!(writer, {
567			// For compatibility with LDK versions prior to 0.0.117, we take the individual
568			// RouteParameters' fields and reconstruct them on read.
569			(1, self.route_params.as_ref().map(|p| &p.payment_params), option),
570			(2, blinded_tails, optional_vec),
571			(3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
572			(5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
573		});
574		Ok(())
575	}
576}
577
578impl Readable for Route {
579	fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
580		let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
581		let path_count: u64 = Readable::read(reader)?;
582		if path_count == 0 { return Err(DecodeError::InvalidValue); }
583		let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
584		let mut min_final_cltv_expiry_delta = u32::max_value();
585		for _ in 0..path_count {
586			let hop_count: u8 = Readable::read(reader)?;
587			let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
588			for _ in 0..hop_count {
589				hops.push(Readable::read(reader)?);
590			}
591			if hops.is_empty() { return Err(DecodeError::InvalidValue); }
592			min_final_cltv_expiry_delta =
593				cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
594			paths.push(Path { hops, blinded_tail: None });
595		}
596		_init_and_read_len_prefixed_tlv_fields!(reader, {
597			(1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
598			(2, blinded_tails, optional_vec),
599			(3, final_value_msat, option),
600			(5, max_total_routing_fee_msat, option)
601		});
602		let blinded_tails = blinded_tails.unwrap_or(Vec::new());
603		if blinded_tails.len() != 0 {
604			if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
605			for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
606				path.blinded_tail = blinded_tail_opt;
607			}
608		}
609
610		// If we previously wrote the corresponding fields, reconstruct RouteParameters.
611		let route_params = match (payment_params, final_value_msat) {
612			(Some(payment_params), Some(final_value_msat)) => {
613				Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
614			}
615			_ => None,
616		};
617
618		Ok(Route { paths, route_params })
619	}
620}
621
622/// Parameters needed to find a [`Route`].
623///
624/// Passed to [`find_route`] and [`build_route_from_hops`].
625#[derive(Clone, Debug, Hash, PartialEq, Eq)]
626pub struct RouteParameters {
627	/// The parameters of the failed payment path.
628	pub payment_params: PaymentParameters,
629
630	/// The amount in msats sent on the failed payment path.
631	pub final_value_msat: u64,
632
633	/// The maximum total fees, in millisatoshi, that may accrue during route finding.
634	///
635	/// This limit also applies to the total fees that may arise while retrying failed payment
636	/// paths.
637	///
638	/// Note that values below a few sats may result in some paths being spuriously ignored.
639	pub max_total_routing_fee_msat: Option<u64>,
640}
641
642impl RouteParameters {
643	/// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
644	///
645	/// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
646	pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
647		Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
648	}
649
650	/// Sets the maximum number of hops that can be included in a payment path, based on the provided
651	/// [`RecipientOnionFields`] and blinded paths.
652	pub fn set_max_path_length(
653		&mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32
654	) -> Result<(), ()> {
655		let keysend_preimage_opt = is_keysend.then(|| PaymentPreimage([42; 32]));
656		// TODO: no way to account for the invoice request here yet
657		onion_utils::set_max_path_length(
658			self, recipient_onion, keysend_preimage_opt, None, best_block_height
659		)
660	}
661}
662
663impl Writeable for RouteParameters {
664	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
665		write_tlv_fields!(writer, {
666			(0, self.payment_params, required),
667			(1, self.max_total_routing_fee_msat, option),
668			(2, self.final_value_msat, required),
669			// LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
670			// `RouteParameters` directly. For compatibility, we write it here.
671			(4, self.payment_params.payee.final_cltv_expiry_delta(), option),
672		});
673		Ok(())
674	}
675}
676
677impl Readable for RouteParameters {
678	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
679		_init_and_read_len_prefixed_tlv_fields!(reader, {
680			(0, payment_params, (required: ReadableArgs, 0)),
681			(1, max_total_routing_fee_msat, option),
682			(2, final_value_msat, required),
683			(4, final_cltv_delta, option),
684		});
685		let mut payment_params: PaymentParameters = payment_params.0.unwrap();
686		if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
687			if final_cltv_expiry_delta == &0 {
688				*final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
689			}
690		}
691		Ok(Self {
692			payment_params,
693			final_value_msat: final_value_msat.0.unwrap(),
694			max_total_routing_fee_msat,
695		})
696	}
697}
698
699/// Maximum total CTLV difference we allow for a full payment path.
700pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
701
702/// Maximum number of paths we allow an (MPP) payment to have.
703// The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
704// limits, but for now more than 10 paths likely carries too much one-path failure.
705pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
706
707const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
708
709// The median hop CLTV expiry delta currently seen in the network.
710const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
711
712/// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
713/// payment metadata, custom TLVs, or blinded paths are included in the payment.
714// During routing, we only consider paths shorter than our maximum length estimate.
715// In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
716// field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
717// estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
718//
719// We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
720// 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
721// (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
722// (payment_secret and total_msat) = 93 bytes for the final hop.
723// Since the length of the potentially included `payment_metadata` is unknown to us, we round
724// down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
725pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
726
727/// Information used to route a payment.
728#[derive(Clone, Debug, Hash, PartialEq, Eq)]
729pub struct PaymentParameters {
730	/// Information about the payee, such as their features and route hints for their channels.
731	pub payee: Payee,
732
733	/// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
734	pub expiry_time: Option<u64>,
735
736	/// The maximum total CLTV delta we accept for the route.
737	/// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
738	pub max_total_cltv_expiry_delta: u32,
739
740	/// The maximum number of paths that may be used by (MPP) payments.
741	/// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
742	pub max_path_count: u8,
743
744	/// The maximum number of [`Path::hops`] in any returned path.
745	/// Defaults to [`MAX_PATH_LENGTH_ESTIMATE`].
746	pub max_path_length: u8,
747
748	/// Selects the maximum share of a channel's total capacity which will be sent over a channel,
749	/// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
750	/// a lower value prefers to send larger MPP parts, potentially saturating channels and
751	/// increasing failure probability for those paths.
752	///
753	/// Note that this restriction will be relaxed during pathfinding after paths which meet this
754	/// restriction have been found. While paths which meet this criteria will be searched for, it
755	/// is ultimately up to the scorer to select them over other paths.
756	///
757	/// A value of 0 will allow payments up to and including a channel's total announced usable
758	/// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
759	///
760	/// Default value: 2
761	pub max_channel_saturation_power_of_half: u8,
762
763	/// A list of SCIDs which this payment was previously attempted over and which caused the
764	/// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
765	/// these SCIDs.
766	pub previously_failed_channels: Vec<u64>,
767
768	/// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
769	/// payment was previously attempted over and which caused the payment to fail. Future attempts
770	/// for the same payment shouldn't be relayed through any of these blinded paths.
771	pub previously_failed_blinded_path_idxs: Vec<u64>,
772}
773
774impl Writeable for PaymentParameters {
775	fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
776		let mut clear_hints = &vec![];
777		let mut blinded_hints = None;
778		match &self.payee {
779			Payee::Clear { route_hints, .. } => clear_hints = route_hints,
780			Payee::Blinded { route_hints, .. } => {
781				let hints_iter = route_hints.iter().map(|path| (&path.payinfo, path.inner_blinded_path()));
782				blinded_hints = Some(crate::util::ser::IterableOwned(hints_iter));
783			}
784		}
785		write_tlv_fields!(writer, {
786			(0, self.payee.node_id(), option),
787			(1, self.max_total_cltv_expiry_delta, required),
788			(2, self.payee.features(), option),
789			(3, self.max_path_count, required),
790			(4, *clear_hints, required_vec),
791			(5, self.max_channel_saturation_power_of_half, required),
792			(6, self.expiry_time, option),
793			(7, self.previously_failed_channels, required_vec),
794			(8, blinded_hints, option),
795			(9, self.payee.final_cltv_expiry_delta(), option),
796			(11, self.previously_failed_blinded_path_idxs, required_vec),
797			(13, self.max_path_length, required),
798		});
799		Ok(())
800	}
801}
802
803impl ReadableArgs<u32> for PaymentParameters {
804	fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
805		_init_and_read_len_prefixed_tlv_fields!(reader, {
806			(0, payee_pubkey, option),
807			(1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
808			(2, features, (option: ReadableArgs, payee_pubkey.is_some())),
809			(3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
810			(4, clear_route_hints, required_vec),
811			(5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
812			(6, expiry_time, option),
813			(7, previously_failed_channels, optional_vec),
814			(8, blinded_route_hints, optional_vec),
815			(9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
816			(11, previously_failed_blinded_path_idxs, optional_vec),
817			(13, max_path_length, (default_value, MAX_PATH_LENGTH_ESTIMATE)),
818		});
819		let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
820		let payee = if blinded_route_hints.len() != 0 {
821			if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
822			Payee::Blinded {
823				route_hints: blinded_route_hints
824					.into_iter()
825					.map(|(payinfo, path)| BlindedPaymentPath::from_parts(path, payinfo))
826					.collect(),
827				features: features.and_then(|f: Features| f.bolt12()),
828			}
829		} else {
830			Payee::Clear {
831				route_hints: clear_route_hints,
832				node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
833				features: features.and_then(|f| f.bolt11()),
834				final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
835			}
836		};
837		Ok(Self {
838			max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
839			max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
840			payee,
841			max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
842			expiry_time,
843			previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
844			previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
845			max_path_length: _init_tlv_based_struct_field!(max_path_length, (default_value, unused)),
846		})
847	}
848}
849
850
851impl PaymentParameters {
852	/// Creates a payee with the node id of the given `pubkey`.
853	///
854	/// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
855	/// provided.
856	pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
857		Self {
858			payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
859			expiry_time: None,
860			max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
861			max_path_count: DEFAULT_MAX_PATH_COUNT,
862			max_path_length: MAX_PATH_LENGTH_ESTIMATE,
863			max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
864			previously_failed_channels: Vec::new(),
865			previously_failed_blinded_path_idxs: Vec::new(),
866		}
867	}
868
869	/// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
870	///
871	/// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
872	/// provided.
873	///
874	/// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
875	/// whether your router will be allowed to find a multi-part route for this payment. If you
876	/// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
877	/// [`RecipientOnionFields::secret_only`].
878	///
879	/// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
880	pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
881		Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
882			.with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
883			.expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
884	}
885
886	/// Creates parameters for paying to a blinded payee from the provided invoice. Sets
887	/// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
888	/// [`PaymentParameters::expiry_time`].
889	pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
890		Self::blinded(invoice.payment_paths().to_vec())
891			.with_bolt12_features(invoice.invoice_features().clone()).unwrap()
892			.with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
893	}
894
895	/// Creates parameters for paying to a blinded payee from the provided invoice. Sets
896	/// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
897	/// [`PaymentParameters::expiry_time`].
898	#[cfg(async_payments)]
899	pub fn from_static_invoice(invoice: &StaticInvoice) -> Self {
900		Self::blinded(invoice.payment_paths().to_vec())
901			.with_bolt12_features(invoice.invoice_features().clone()).unwrap()
902			.with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
903	}
904
905	/// Creates parameters for paying to a blinded payee from the provided blinded route hints.
906	pub fn blinded(blinded_route_hints: Vec<BlindedPaymentPath>) -> Self {
907		Self {
908			payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
909			expiry_time: None,
910			max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
911			max_path_count: DEFAULT_MAX_PATH_COUNT,
912			max_path_length: MAX_PATH_LENGTH_ESTIMATE,
913			max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
914			previously_failed_channels: Vec::new(),
915			previously_failed_blinded_path_idxs: Vec::new(),
916		}
917	}
918
919	/// Includes the payee's features. Errors if the parameters were not initialized with
920	/// [`PaymentParameters::from_bolt12_invoice`].
921	///
922	/// This is not exported to bindings users since bindings don't support move semantics
923	pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
924		match self.payee {
925			Payee::Clear { .. } => Err(()),
926			Payee::Blinded { route_hints, .. } =>
927				Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
928		}
929	}
930
931	/// Includes the payee's features. Errors if the parameters were initialized with
932	/// [`PaymentParameters::from_bolt12_invoice`].
933	///
934	/// This is not exported to bindings users since bindings don't support move semantics
935	pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
936		match self.payee {
937			Payee::Blinded { .. } => Err(()),
938			Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
939				Ok(Self {
940					payee: Payee::Clear {
941						route_hints, node_id, features: Some(features), final_cltv_expiry_delta
942					}, ..self
943				})
944		}
945	}
946
947	/// Includes hints for routing to the payee. Errors if the parameters were initialized with
948	/// [`PaymentParameters::from_bolt12_invoice`].
949	///
950	/// This is not exported to bindings users since bindings don't support move semantics
951	pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
952		match self.payee {
953			Payee::Blinded { .. } => Err(()),
954			Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
955				Ok(Self {
956					payee: Payee::Clear {
957						route_hints, node_id, features, final_cltv_expiry_delta,
958					}, ..self
959				})
960		}
961	}
962
963	/// Includes a payment expiration in seconds relative to the UNIX epoch.
964	///
965	/// This is not exported to bindings users since bindings don't support move semantics
966	pub fn with_expiry_time(self, expiry_time: u64) -> Self {
967		Self { expiry_time: Some(expiry_time), ..self }
968	}
969
970	/// Includes a limit for the total CLTV expiry delta which is considered during routing
971	///
972	/// This is not exported to bindings users since bindings don't support move semantics
973	pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
974		Self { max_total_cltv_expiry_delta, ..self }
975	}
976
977	/// Includes a limit for the maximum number of payment paths that may be used.
978	///
979	/// This is not exported to bindings users since bindings don't support move semantics
980	pub fn with_max_path_count(self, max_path_count: u8) -> Self {
981		Self { max_path_count, ..self }
982	}
983
984	/// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
985	/// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
986	///
987	/// This is not exported to bindings users since bindings don't support move semantics
988	pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
989		Self { max_channel_saturation_power_of_half, ..self }
990	}
991
992	pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
993		let mut found_blinded_tail = false;
994		for (idx, path) in self.payee.blinded_route_hints().iter().enumerate() {
995			if &failed_blinded_tail.hops == path.blinded_hops() &&
996				failed_blinded_tail.blinding_point == path.blinding_point()
997			{
998				self.previously_failed_blinded_path_idxs.push(idx as u64);
999				found_blinded_tail = true;
1000			}
1001		}
1002		debug_assert!(found_blinded_tail);
1003	}
1004}
1005
1006/// The recipient of a payment, differing based on whether they've hidden their identity with route
1007/// blinding.
1008#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1009pub enum Payee {
1010	/// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
1011	/// will be included in the final [`Route`].
1012	Blinded {
1013		/// Aggregated routing info and blinded paths, for routing to the payee without knowing their
1014		/// node id.
1015		route_hints: Vec<BlindedPaymentPath>,
1016		/// Features supported by the payee.
1017		///
1018		/// May be set from the payee's invoice. May be `None` if the invoice does not contain any
1019		/// features.
1020		features: Option<Bolt12InvoiceFeatures>,
1021	},
1022	/// The recipient included these route hints in their BOLT11 invoice.
1023	Clear {
1024		/// The node id of the payee.
1025		node_id: PublicKey,
1026		/// Hints for routing to the payee, containing channels connecting the payee to public nodes.
1027		route_hints: Vec<RouteHint>,
1028		/// Features supported by the payee.
1029		///
1030		/// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
1031		/// does not contain any features.
1032		///
1033		/// [`for_keysend`]: PaymentParameters::for_keysend
1034		features: Option<Bolt11InvoiceFeatures>,
1035		/// The minimum CLTV delta at the end of the route. This value must not be zero.
1036		final_cltv_expiry_delta: u32,
1037	},
1038}
1039
1040impl Payee {
1041	fn node_id(&self) -> Option<PublicKey> {
1042		match self {
1043			Self::Clear { node_id, .. } => Some(*node_id),
1044			_ => None,
1045		}
1046	}
1047	fn node_features(&self) -> Option<NodeFeatures> {
1048		match self {
1049			Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
1050			Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
1051		}
1052	}
1053	fn supports_basic_mpp(&self) -> bool {
1054		match self {
1055			Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1056			Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
1057		}
1058	}
1059	fn features(&self) -> Option<FeaturesRef> {
1060		match self {
1061			Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
1062			Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
1063		}
1064	}
1065	fn final_cltv_expiry_delta(&self) -> Option<u32> {
1066		match self {
1067			Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
1068			_ => None,
1069		}
1070	}
1071	pub(crate) fn blinded_route_hints(&self) -> &[BlindedPaymentPath] {
1072		match self {
1073			Self::Blinded { route_hints, .. } => &route_hints[..],
1074			Self::Clear { .. } => &[]
1075		}
1076	}
1077
1078	pub(crate) fn blinded_route_hints_mut(&mut self) -> &mut [BlindedPaymentPath] {
1079		match self {
1080			Self::Blinded { route_hints, .. } => &mut route_hints[..],
1081			Self::Clear { .. } => &mut []
1082		}
1083	}
1084
1085	fn unblinded_route_hints(&self) -> &[RouteHint] {
1086		match self {
1087			Self::Blinded { .. } => &[],
1088			Self::Clear { route_hints, .. } => &route_hints[..]
1089		}
1090	}
1091}
1092
1093enum FeaturesRef<'a> {
1094	Bolt11(&'a Bolt11InvoiceFeatures),
1095	Bolt12(&'a Bolt12InvoiceFeatures),
1096}
1097enum Features {
1098	Bolt11(Bolt11InvoiceFeatures),
1099	Bolt12(Bolt12InvoiceFeatures),
1100}
1101
1102impl Features {
1103	fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
1104		match self {
1105			Self::Bolt12(f) => Some(f),
1106			_ => None,
1107		}
1108	}
1109	fn bolt11(self) -> Option<Bolt11InvoiceFeatures> {
1110		match self {
1111			Self::Bolt11(f) => Some(f),
1112			_ => None,
1113		}
1114	}
1115}
1116
1117impl<'a> Writeable for FeaturesRef<'a> {
1118	fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1119		match self {
1120			Self::Bolt11(f) => Ok(f.write(w)?),
1121			Self::Bolt12(f) => Ok(f.write(w)?),
1122		}
1123	}
1124}
1125
1126impl ReadableArgs<bool> for Features {
1127	fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
1128		if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
1129		Ok(Self::Bolt12(Readable::read(reader)?))
1130	}
1131}
1132
1133impl Writeable for RouteHint {
1134	fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1135		(self.0.len() as u64).write(writer)?;
1136		for hop in self.0.iter() {
1137			hop.write(writer)?;
1138		}
1139		Ok(())
1140	}
1141}
1142
1143impl Readable for RouteHint {
1144	fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
1145		let hop_count: u64 = Readable::read(reader)?;
1146		let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
1147		for _ in 0..hop_count {
1148			hops.push(Readable::read(reader)?);
1149		}
1150		Ok(Self(hops))
1151	}
1152}
1153
1154impl_writeable_tlv_based!(RouteHintHop, {
1155	(0, src_node_id, required),
1156	(1, htlc_minimum_msat, option),
1157	(2, short_channel_id, required),
1158	(3, htlc_maximum_msat, option),
1159	(4, fees, required),
1160	(6, cltv_expiry_delta, required),
1161});
1162
1163#[derive(Eq, PartialEq)]
1164#[repr(align(32))] // Force the size to 32 bytes
1165struct RouteGraphNode {
1166	node_counter: u32,
1167	score: u128,
1168	// The maximum value a yet-to-be-constructed payment path might flow through this node.
1169	// This value is upper-bounded by us by:
1170	// - how much is needed for a path being constructed
1171	// - how much value can channels following this node (up to the destination) can contribute,
1172	//   considering their capacity and fees
1173	value_contribution_msat: u64,
1174	total_cltv_delta: u16,
1175	/// The number of hops walked up to this node.
1176	path_length_to_node: u8,
1177}
1178
1179impl cmp::Ord for RouteGraphNode {
1180	fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
1181		other.score.cmp(&self.score)
1182			.then_with(|| self.value_contribution_msat.cmp(&other.value_contribution_msat))
1183			.then_with(|| other.path_length_to_node.cmp(&self.path_length_to_node))
1184			.then_with(|| other.node_counter.cmp(&self.node_counter))
1185	}
1186}
1187
1188impl cmp::PartialOrd for RouteGraphNode {
1189	fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
1190		Some(self.cmp(other))
1191	}
1192}
1193
1194// While RouteGraphNode can be laid out with fewer bytes, performance appears to be improved
1195// substantially when it is laid out at exactly 32 bytes.
1196const _GRAPH_NODE_32: () = assert!(core::mem::size_of::<RouteGraphNode>() == 32);
1197
1198/// A [`CandidateRouteHop::FirstHop`] entry.
1199#[derive(Clone, Debug)]
1200pub struct FirstHopCandidate<'a> {
1201	/// Channel details of the first hop
1202	///
1203	/// [`ChannelDetails::get_outbound_payment_scid`] MUST be `Some` (indicating the channel
1204	/// has been funded and is able to pay), and accessor methods may panic otherwise.
1205	///
1206	/// [`find_route`] validates this prior to constructing a [`CandidateRouteHop`].
1207	///
1208	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1209	pub details: &'a ChannelDetails,
1210	/// The node id of the payer, which is also the source side of this candidate route hop.
1211	///
1212	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1213	pub payer_node_id: &'a NodeId,
1214	/// A unique ID which describes the payer.
1215	///
1216	/// It will not conflict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1217	/// payer is a public node.
1218	///
1219	/// [`NodeInfo::node_counter`]: super::gossip::NodeInfo::node_counter
1220	pub(crate) payer_node_counter: u32,
1221	/// A unique ID which describes the first hop counterparty.
1222	///
1223	/// It will not conflict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1224	/// counterparty is a public node.
1225	///
1226	/// [`NodeInfo::node_counter`]: super::gossip::NodeInfo::node_counter
1227	pub(crate) target_node_counter: u32,
1228}
1229
1230/// A [`CandidateRouteHop::PublicHop`] entry.
1231#[derive(Clone, Debug)]
1232pub struct PublicHopCandidate<'a> {
1233	/// Information about the channel, including potentially its capacity and
1234	/// direction-specific information.
1235	///
1236	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1237	pub info: DirectedChannelInfo<'a>,
1238	/// The short channel ID of the channel, i.e. the identifier by which we refer to this
1239	/// channel.
1240	pub short_channel_id: u64,
1241}
1242
1243/// A [`CandidateRouteHop::PrivateHop`] entry.
1244#[derive(Clone, Debug)]
1245pub struct PrivateHopCandidate<'a> {
1246	/// Information about the private hop communicated via BOLT 11.
1247	///
1248	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1249	pub hint: &'a RouteHintHop,
1250	/// Node id of the next hop in BOLT 11 route hint.
1251	///
1252	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1253	pub target_node_id: &'a NodeId,
1254	/// A unique ID which describes the source node of the hop (further from the payment target).
1255	///
1256	/// It will not conflict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1257	/// node is a public node.
1258	///
1259	/// [`NodeInfo::node_counter`]: super::gossip::NodeInfo::node_counter
1260	pub(crate) source_node_counter: u32,
1261	/// A unique ID which describes the destination node of the hop (towards the payment target).
1262	///
1263	/// It will not conflict with any [`NodeInfo::node_counter`]s, but may be equal to one if the
1264	/// node is a public node.
1265	///
1266	/// [`NodeInfo::node_counter`]: super::gossip::NodeInfo::node_counter
1267	pub(crate) target_node_counter: u32,
1268}
1269
1270/// A [`CandidateRouteHop::Blinded`] entry.
1271#[derive(Clone, Debug)]
1272pub struct BlindedPathCandidate<'a> {
1273	/// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1274	/// hops.
1275	///
1276	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1277	pub source_node_id: &'a NodeId,
1278	/// Information about the blinded path including the fee, HTLC amount limits, and
1279	/// cryptographic material required to build an HTLC through the given path.
1280	///
1281	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1282	pub hint: &'a BlindedPaymentPath,
1283	/// Index of the hint in the original list of blinded hints.
1284	///
1285	/// This is used to cheaply uniquely identify this blinded path, even though we don't have
1286	/// a short channel ID for this hop.
1287	hint_idx: usize,
1288	/// A unique ID which describes the introduction point of the blinded path.
1289	///
1290	/// It will not conflict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1291	/// one from the public network graph (assuming the introduction point is a public node).
1292	///
1293	/// [`NodeInfo::node_counter`]: super::gossip::NodeInfo::node_counter
1294	source_node_counter: u32,
1295}
1296
1297/// A [`CandidateRouteHop::OneHopBlinded`] entry.
1298#[derive(Clone, Debug)]
1299pub struct OneHopBlindedPathCandidate<'a> {
1300	/// The node id of the introduction node, resolved from either the [`NetworkGraph`] or first
1301	/// hops.
1302	///
1303	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1304	pub source_node_id: &'a NodeId,
1305	/// Information about the blinded path including the fee, HTLC amount limits, and
1306	/// cryptographic material required to build an HTLC terminating with the given path.
1307	///
1308	/// Note that the [`BlindedPayInfo`] is ignored here.
1309	///
1310	/// This is not exported to bindings users as lifetimes are not expressible in most languages.
1311	///
1312	/// [`BlindedPayInfo`]: crate::blinded_path::payment::BlindedPayInfo
1313	pub hint: &'a BlindedPaymentPath,
1314	/// Index of the hint in the original list of blinded hints.
1315	///
1316	/// This is used to cheaply uniquely identify this blinded path, even though we don't have
1317	/// a short channel ID for this hop.
1318	hint_idx: usize,
1319	/// A unique ID which describes the introduction point of the blinded path.
1320	///
1321	/// It will not conflict with any [`NodeInfo::node_counter`]s, but will generally be equal to
1322	/// one from the public network graph (assuming the introduction point is a public node).
1323	///
1324	/// [`NodeInfo::node_counter`]: super::gossip::NodeInfo::node_counter
1325	source_node_counter: u32,
1326}
1327
1328/// A wrapper around the various hop representations.
1329///
1330/// Can be used to examine the properties of a hop,
1331/// potentially to decide whether to include it in a route.
1332#[derive(Clone, Debug)]
1333pub enum CandidateRouteHop<'a> {
1334	/// A hop from the payer, where the outbound liquidity is known.
1335	FirstHop(FirstHopCandidate<'a>),
1336	/// A hop found in the [`ReadOnlyNetworkGraph`].
1337	PublicHop(PublicHopCandidate<'a>),
1338	/// A private hop communicated by the payee, generally via a BOLT 11 invoice.
1339	///
1340	/// Because BOLT 11 route hints can take multiple hops to get to the destination, this may not
1341	/// terminate at the payee.
1342	PrivateHop(PrivateHopCandidate<'a>),
1343	/// A blinded path which starts with an introduction point and ultimately terminates with the
1344	/// payee.
1345	///
1346	/// Because we don't know the payee's identity, [`CandidateRouteHop::target`] will return
1347	/// `None` in this state.
1348	///
1349	/// Because blinded paths are "all or nothing", and we cannot use just one part of a blinded
1350	/// path, the full path is treated as a single [`CandidateRouteHop`].
1351	Blinded(BlindedPathCandidate<'a>),
1352	/// Similar to [`Self::Blinded`], but the path here only has one hop.
1353	///
1354	/// While we treat this similarly to [`CandidateRouteHop::Blinded`] in many respects (e.g.
1355	/// returning `None` from [`CandidateRouteHop::target`]), in this case we do actually know the
1356	/// payee's identity - it's the introduction point!
1357	///
1358	/// [`BlindedPayInfo`] provided for 1-hop blinded paths is ignored because it is meant to apply
1359	/// to the hops *between* the introduction node and the destination.
1360	///
1361	/// This primarily exists to track that we need to included a blinded path at the end of our
1362	/// [`Route`], even though it doesn't actually add an additional hop in the payment.
1363	///
1364	/// [`BlindedPayInfo`]: crate::blinded_path::payment::BlindedPayInfo
1365	OneHopBlinded(OneHopBlindedPathCandidate<'a>),
1366}
1367
1368impl<'a> CandidateRouteHop<'a> {
1369	/// Returns the short channel ID for this hop, if one is known.
1370	///
1371	/// This SCID could be an alias or a globally unique SCID, and thus is only expected to
1372	/// uniquely identify this channel in conjunction with the [`CandidateRouteHop::source`].
1373	///
1374	/// Returns `Some` as long as the candidate is a [`CandidateRouteHop::PublicHop`], a
1375	/// [`CandidateRouteHop::PrivateHop`] from a BOLT 11 route hint, or a
1376	/// [`CandidateRouteHop::FirstHop`] with a known [`ChannelDetails::get_outbound_payment_scid`]
1377	/// (which is always true for channels which are funded and ready for use).
1378	///
1379	/// In other words, this should always return `Some` as long as the candidate hop is not a
1380	/// [`CandidateRouteHop::Blinded`] or a [`CandidateRouteHop::OneHopBlinded`].
1381	///
1382	/// Note that this is deliberately not public as it is somewhat of a footgun because it doesn't
1383	/// define a global namespace.
1384	#[inline]
1385	fn short_channel_id(&self) -> Option<u64> {
1386		match self {
1387			CandidateRouteHop::FirstHop(hop) => hop.details.get_outbound_payment_scid(),
1388			CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1389			CandidateRouteHop::PrivateHop(hop) => Some(hop.hint.short_channel_id),
1390			CandidateRouteHop::Blinded(_) => None,
1391			CandidateRouteHop::OneHopBlinded(_) => None,
1392		}
1393	}
1394
1395	/// Returns the globally unique short channel ID for this hop, if one is known.
1396	///
1397	/// This only returns `Some` if the channel is public (either our own, or one we've learned
1398	/// from the public network graph), and thus the short channel ID we have for this channel is
1399	/// globally unique and identifies this channel in a global namespace.
1400	#[inline]
1401	pub fn globally_unique_short_channel_id(&self) -> Option<u64> {
1402		match self {
1403			CandidateRouteHop::FirstHop(hop) => if hop.details.is_announced { hop.details.short_channel_id } else { None },
1404			CandidateRouteHop::PublicHop(hop) => Some(hop.short_channel_id),
1405			CandidateRouteHop::PrivateHop(_) => None,
1406			CandidateRouteHop::Blinded(_) => None,
1407			CandidateRouteHop::OneHopBlinded(_) => None,
1408		}
1409	}
1410
1411	// NOTE: This may alloc memory so avoid calling it in a hot code path.
1412	fn features(&self) -> ChannelFeatures {
1413		match self {
1414			CandidateRouteHop::FirstHop(hop) => hop.details.counterparty.features.to_context(),
1415			CandidateRouteHop::PublicHop(hop) => hop.info.channel().features.clone(),
1416			CandidateRouteHop::PrivateHop(_) => ChannelFeatures::empty(),
1417			CandidateRouteHop::Blinded(_) => ChannelFeatures::empty(),
1418			CandidateRouteHop::OneHopBlinded(_) => ChannelFeatures::empty(),
1419		}
1420	}
1421
1422	/// Returns the required difference in HTLC CLTV expiry between the [`Self::source`] and the
1423	/// next-hop for an HTLC taking this hop.
1424	///
1425	/// This is the time that the node(s) in this hop have to claim the HTLC on-chain if the
1426	/// next-hop goes on chain with a payment preimage.
1427	#[inline]
1428	pub fn cltv_expiry_delta(&self) -> u32 {
1429		match self {
1430			CandidateRouteHop::FirstHop(_) => 0,
1431			CandidateRouteHop::PublicHop(hop) => hop.info.direction().cltv_expiry_delta as u32,
1432			CandidateRouteHop::PrivateHop(hop) => hop.hint.cltv_expiry_delta as u32,
1433			CandidateRouteHop::Blinded(hop) => hop.hint.payinfo.cltv_expiry_delta as u32,
1434			CandidateRouteHop::OneHopBlinded(_) => 0,
1435		}
1436	}
1437
1438	/// Returns the minimum amount that can be sent over this hop, in millisatoshis.
1439	#[inline]
1440	pub fn htlc_minimum_msat(&self) -> u64 {
1441		match self {
1442			CandidateRouteHop::FirstHop(hop) => hop.details.next_outbound_htlc_minimum_msat,
1443			CandidateRouteHop::PublicHop(hop) => hop.info.direction().htlc_minimum_msat,
1444			CandidateRouteHop::PrivateHop(hop) => hop.hint.htlc_minimum_msat.unwrap_or(0),
1445			CandidateRouteHop::Blinded(hop) => hop.hint.payinfo.htlc_minimum_msat,
1446			CandidateRouteHop::OneHopBlinded { .. } => 0,
1447		}
1448	}
1449
1450	#[inline(always)]
1451	fn src_node_counter(&self) -> u32 {
1452		match self {
1453			CandidateRouteHop::FirstHop(hop) => hop.payer_node_counter,
1454			CandidateRouteHop::PublicHop(hop) => hop.info.source_counter(),
1455			CandidateRouteHop::PrivateHop(hop) => hop.source_node_counter,
1456			CandidateRouteHop::Blinded(hop) => hop.source_node_counter,
1457			CandidateRouteHop::OneHopBlinded(hop) => hop.source_node_counter,
1458		}
1459	}
1460
1461	#[inline]
1462	fn target_node_counter(&self) -> Option<u32> {
1463		match self {
1464			CandidateRouteHop::FirstHop(hop) => Some(hop.target_node_counter),
1465			CandidateRouteHop::PublicHop(hop) => Some(hop.info.target_counter()),
1466			CandidateRouteHop::PrivateHop(hop) => Some(hop.target_node_counter),
1467			CandidateRouteHop::Blinded(_) => None,
1468			CandidateRouteHop::OneHopBlinded(_) => None,
1469		}
1470	}
1471
1472	/// Returns the fees that must be paid to route an HTLC over this channel.
1473	#[inline]
1474	pub fn fees(&self) -> RoutingFees {
1475		match self {
1476			CandidateRouteHop::FirstHop(_) => RoutingFees {
1477				base_msat: 0, proportional_millionths: 0,
1478			},
1479			CandidateRouteHop::PublicHop(hop) => hop.info.direction().fees,
1480			CandidateRouteHop::PrivateHop(hop) => hop.hint.fees,
1481			CandidateRouteHop::Blinded(hop) => {
1482				RoutingFees {
1483					base_msat: hop.hint.payinfo.fee_base_msat,
1484					proportional_millionths: hop.hint.payinfo.fee_proportional_millionths
1485				}
1486			},
1487			CandidateRouteHop::OneHopBlinded(_) =>
1488				RoutingFees { base_msat: 0, proportional_millionths: 0 },
1489		}
1490	}
1491
1492	/// Fetch the effective capacity of this hop.
1493	///
1494	/// Note that this may be somewhat expensive, so calls to this should be limited and results
1495	/// cached!
1496	fn effective_capacity(&self) -> EffectiveCapacity {
1497		match self {
1498			CandidateRouteHop::FirstHop(hop) => EffectiveCapacity::ExactLiquidity {
1499				liquidity_msat: hop.details.next_outbound_htlc_limit_msat,
1500			},
1501			CandidateRouteHop::PublicHop(hop) => hop.info.effective_capacity(),
1502			CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }, .. }) =>
1503				EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1504			CandidateRouteHop::PrivateHop(PrivateHopCandidate { hint: RouteHintHop { htlc_maximum_msat: None, .. }, .. }) =>
1505				EffectiveCapacity::Infinite,
1506			CandidateRouteHop::Blinded(hop) =>
1507				EffectiveCapacity::HintMaxHTLC { amount_msat: hop.hint.payinfo.htlc_maximum_msat },
1508			CandidateRouteHop::OneHopBlinded(_) => EffectiveCapacity::Infinite,
1509		}
1510	}
1511
1512	/// Returns an ID describing the given hop.
1513	///
1514	/// See the docs on [`CandidateHopId`] for when this is, or is not, unique.
1515	#[inline]
1516	fn id(&self) -> CandidateHopId {
1517		match self {
1518			CandidateRouteHop::Blinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1519			CandidateRouteHop::OneHopBlinded(hop) => CandidateHopId::Blinded(hop.hint_idx),
1520			_ => CandidateHopId::Clear((self.short_channel_id().unwrap(), self.source() < self.target().unwrap())),
1521		}
1522	}
1523	fn blinded_path(&self) -> Option<&'a BlindedPaymentPath> {
1524		match self {
1525			CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
1526				Some(&hint)
1527			},
1528			_ => None,
1529		}
1530	}
1531	fn blinded_hint_idx(&self) -> Option<usize> {
1532		match self {
1533			Self::Blinded(BlindedPathCandidate { hint_idx, .. }) |
1534			Self::OneHopBlinded(OneHopBlindedPathCandidate { hint_idx, .. }) => {
1535				Some(*hint_idx)
1536			},
1537			_ => None,
1538		}
1539	}
1540	/// Returns the source node id of current hop.
1541	///
1542	/// Source node id refers to the node forwarding the HTLC through this hop.
1543	///
1544	/// For [`Self::FirstHop`] we return payer's node id.
1545	#[inline]
1546	pub fn source(&self) -> NodeId {
1547		match self {
1548			CandidateRouteHop::FirstHop(hop) => *hop.payer_node_id,
1549			CandidateRouteHop::PublicHop(hop) => *hop.info.source(),
1550			CandidateRouteHop::PrivateHop(hop) => hop.hint.src_node_id.into(),
1551			CandidateRouteHop::Blinded(hop) => *hop.source_node_id,
1552			CandidateRouteHop::OneHopBlinded(hop) => *hop.source_node_id,
1553		}
1554	}
1555	/// Returns the target node id of this hop, if known.
1556	///
1557	/// Target node id refers to the node receiving the HTLC after this hop.
1558	///
1559	/// For [`Self::Blinded`] we return `None` because the ultimate destination after the blinded
1560	/// path is unknown.
1561	///
1562	/// For [`Self::OneHopBlinded`] we return `None` because the target is the same as the source,
1563	/// and such a return value would be somewhat nonsensical.
1564	#[inline]
1565	pub fn target(&self) -> Option<NodeId> {
1566		match self {
1567			CandidateRouteHop::FirstHop(hop) => Some(hop.details.counterparty.node_id.into()),
1568			CandidateRouteHop::PublicHop(hop) => Some(*hop.info.target()),
1569			CandidateRouteHop::PrivateHop(hop) => Some(*hop.target_node_id),
1570			CandidateRouteHop::Blinded(_) => None,
1571			CandidateRouteHop::OneHopBlinded(_) => None,
1572		}
1573	}
1574}
1575
1576/// A unique(ish) identifier for a specific [`CandidateRouteHop`].
1577///
1578/// For blinded paths, this ID is unique only within a given [`find_route`] call.
1579///
1580/// For other hops, because SCIDs between private channels and public channels can conflict, this
1581/// isn't guaranteed to be unique at all.
1582///
1583/// For our uses, this is generally fine, but it is not public as it is otherwise a rather
1584/// difficult-to-use API.
1585#[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1586enum CandidateHopId {
1587	/// Contains (scid, src_node_id < target_node_id)
1588	Clear((u64, bool)),
1589	/// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1590	Blinded(usize),
1591}
1592
1593/// To avoid doing [`PublicKey`] -> [`PathBuildingHop`] hashtable lookups, we assign each
1594/// [`PublicKey`]/node a `usize` index and simply keep a `Vec` of values.
1595///
1596/// While this is easy for gossip-originating nodes (the [`DirectedChannelInfo`] exposes "counters"
1597/// for us for this purpose) we have to have our own indexes for nodes originating from invoice
1598/// hints, local channels, or blinded path fake nodes.
1599///
1600/// This wrapper handles all this for us, allowing look-up of counters from the various contexts.
1601///
1602/// It is first built by passing all [`NodeId`]s that we'll ever care about (which are not in our
1603/// [`NetworkGraph`], e.g. those from first- and last-hop hints and blinded path introduction
1604/// points) either though [`NodeCountersBuilder::select_node_counter_for_pubkey`] or
1605/// [`NodeCountersBuilder::select_node_counter_for_id`], then calling [`NodeCountersBuilder::build`]
1606/// and using the resulting [`NodeCounters`] to look up any counters.
1607///
1608/// [`NodeCounters::private_node_counter_from_pubkey`], specifically, will return `Some` iff
1609/// [`NodeCountersBuilder::select_node_counter_for_pubkey`] was called on the same key (not
1610/// [`NodeCountersBuilder::select_node_counter_for_id`]). It will also return a cached copy of the
1611/// [`PublicKey`] -> [`NodeId`] conversion.
1612struct NodeCounters<'a> {
1613	network_graph: &'a ReadOnlyNetworkGraph<'a>,
1614	private_node_id_to_node_counter: HashMap<NodeId, u32>,
1615	private_hop_key_cache: HashMap<PublicKey, (NodeId, u32)>,
1616}
1617
1618struct NodeCountersBuilder<'a>(NodeCounters<'a>);
1619
1620impl<'a> NodeCountersBuilder<'a> {
1621	fn new(network_graph: &'a ReadOnlyNetworkGraph) -> Self {
1622		Self(NodeCounters {
1623			network_graph,
1624			private_node_id_to_node_counter: new_hash_map(),
1625			private_hop_key_cache: new_hash_map(),
1626		})
1627	}
1628
1629	fn select_node_counter_for_pubkey(&mut self, pubkey: PublicKey) -> u32 {
1630		let id = NodeId::from_pubkey(&pubkey);
1631		let counter = self.select_node_counter_for_id(id);
1632		self.0.private_hop_key_cache.insert(pubkey, (id, counter));
1633		counter
1634	}
1635
1636	fn select_node_counter_for_id(&mut self, node_id: NodeId) -> u32 {
1637		// For any node_id, we first have to check if its in the existing network graph, and then
1638		// ensure that we always look up in our internal map first.
1639		self.0.network_graph.nodes().get(&node_id)
1640			.map(|node| node.node_counter)
1641			.unwrap_or_else(|| {
1642				let next_node_counter = self.0.network_graph.max_node_counter() + 1 +
1643					self.0.private_node_id_to_node_counter.len() as u32;
1644				*self.0.private_node_id_to_node_counter.entry(node_id).or_insert(next_node_counter)
1645			})
1646	}
1647
1648	fn build(self) -> NodeCounters<'a> { self.0 }
1649}
1650
1651impl<'a> NodeCounters<'a> {
1652	fn max_counter(&self) -> u32 {
1653		self.network_graph.max_node_counter() +
1654			self.private_node_id_to_node_counter.len() as u32
1655	}
1656
1657	fn private_node_counter_from_pubkey(&self, pubkey: &PublicKey) -> Option<&(NodeId, u32)> {
1658		self.private_hop_key_cache.get(pubkey)
1659	}
1660
1661	fn node_counter_from_id(&self, node_id: &NodeId) -> Option<(&NodeId, u32)> {
1662		self.private_node_id_to_node_counter.get_key_value(node_id).map(|(a, b)| (a, *b))
1663			.or_else(|| {
1664				self.network_graph.nodes().get_key_value(node_id)
1665					.map(|(node_id, node)| (node_id, node.node_counter))
1666			})
1667	}
1668}
1669
1670/// Calculates the introduction point for each blinded path in the given [`PaymentParameters`], if
1671/// they can be found.
1672fn calculate_blinded_path_intro_points<'a, L: Deref>(
1673	payment_params: &PaymentParameters, node_counters: &'a NodeCounters,
1674	network_graph: &ReadOnlyNetworkGraph, logger: &L, our_node_id: NodeId,
1675	first_hop_targets: &HashMap<NodeId, (Vec<&ChannelDetails>, u32)>,
1676) -> Result<Vec<Option<(&'a NodeId, u32)>>, LightningError>
1677where L::Target: Logger {
1678	let introduction_node_id_cache = payment_params.payee.blinded_route_hints().iter()
1679		.map(|path| {
1680			match path.introduction_node() {
1681				IntroductionNode::NodeId(pubkey) => {
1682					// Note that this will only return `Some` if the `pubkey` is somehow known to
1683					// us (i.e. a channel counterparty or in the network graph).
1684					node_counters.node_counter_from_id(&NodeId::from_pubkey(&pubkey))
1685				},
1686				IntroductionNode::DirectedShortChannelId(direction, scid) => {
1687					path.public_introduction_node_id(network_graph)
1688						.map(|node_id_ref| *node_id_ref)
1689						.or_else(|| {
1690							first_hop_targets.iter().find(|(_, (channels, _))|
1691								channels
1692									.iter()
1693									.any(|details| Some(*scid) == details.get_outbound_payment_scid())
1694							).map(|(cp, _)| direction.select_node_id(our_node_id, *cp))
1695						})
1696						.and_then(|node_id| node_counters.node_counter_from_id(&node_id))
1697				},
1698			}
1699		})
1700		.collect::<Vec<_>>();
1701	match &payment_params.payee {
1702		Payee::Clear { route_hints, node_id, .. } => {
1703			for route in route_hints.iter() {
1704				for hop in &route.0 {
1705					if hop.src_node_id == *node_id {
1706						return Err(LightningError {
1707							err: "Route hint cannot have the payee as the source.".to_owned(),
1708							action: ErrorAction::IgnoreError
1709						});
1710					}
1711				}
1712			}
1713		},
1714		Payee::Blinded { route_hints, .. } => {
1715			if introduction_node_id_cache.iter().all(|info_opt| info_opt.map(|(a, _)| a) == Some(&our_node_id)) {
1716				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});
1717			}
1718			for (blinded_path, info_opt) in route_hints.iter().zip(introduction_node_id_cache.iter()) {
1719				if blinded_path.blinded_hops().len() == 0 {
1720					return Err(LightningError{err: "0-hop blinded path provided".to_owned(), action: ErrorAction::IgnoreError});
1721				}
1722				let introduction_node_id = match info_opt {
1723					None => continue,
1724					Some(info) => info.0,
1725				};
1726				if *introduction_node_id == our_node_id {
1727					log_info!(logger, "Got blinded path with ourselves as the introduction node, ignoring");
1728				} else if blinded_path.blinded_hops().len() == 1 &&
1729					route_hints
1730						.iter().zip(introduction_node_id_cache.iter())
1731						.filter(|(p, _)| p.blinded_hops().len() == 1)
1732						.any(|(_, iter_info_opt)| iter_info_opt.is_some() && iter_info_opt != info_opt)
1733				{
1734					return Err(LightningError{err: "1-hop blinded paths must all have matching introduction node ids".to_string(), action: ErrorAction::IgnoreError});
1735				}
1736			}
1737		}
1738	}
1739
1740	Ok(introduction_node_id_cache)
1741}
1742
1743#[inline]
1744fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1745	let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1746	match capacity {
1747		EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1748		EffectiveCapacity::Infinite => u64::max_value(),
1749		EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1750		EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1751			amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1752		// Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1753		// expected to have been generated from up-to-date capacity information.
1754		EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1755		EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1756			cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1757	}
1758}
1759
1760fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1761-> bool where I1::Item: PartialEq<I2::Item> {
1762	loop {
1763		let a = iter_a.next();
1764		let b = iter_b.next();
1765		if a.is_none() && b.is_none() { return true; }
1766		if a.is_none() || b.is_none() { return false; }
1767		if a.unwrap().ne(&b.unwrap()) { return false; }
1768	}
1769}
1770
1771/// It's useful to keep track of the hops associated with the fees required to use them,
1772/// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1773/// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1774/// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1775#[derive(Clone)]
1776#[repr(align(128))]
1777struct PathBuildingHop<'a> {
1778	candidate: CandidateRouteHop<'a>,
1779	/// If we've already processed a node as the best node, we shouldn't process it again. Normally
1780	/// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1781	/// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1782	/// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1783	/// avoid processing them again.
1784	was_processed: bool,
1785	/// If we've already processed a channel backwards from a target node, we shouldn't update our
1786	/// selected best path from that node to the destination. This should never happen, but with
1787	/// multiple codepaths processing channels we've had issues here in the past, so in debug-mode
1788	/// we track it and assert on it when processing a node.
1789	#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1790	best_path_from_hop_selected: bool,
1791	/// When processing a node as the next best-score candidate, we want to quickly check if it is
1792	/// a direct counterparty of ours, using our local channel information immediately if we can.
1793	///
1794	/// In order to do so efficiently, we cache whether a node is a direct counterparty here at the
1795	/// start of a route-finding pass. Unlike all other fields in this struct, this field is never
1796	/// updated after being initialized - it is set at the start of a route-finding pass and only
1797	/// read thereafter.
1798	is_first_hop_target: bool,
1799	/// Identical to the above, but for handling unblinded last-hops rather than first-hops.
1800	is_last_hop_target: bool,
1801	/// Used to compare channels when choosing the for routing.
1802	/// Includes paying for the use of a hop and the following hops, as well as
1803	/// an estimated cost of reaching this hop.
1804	/// Might get stale when fees are recomputed. Primarily for internal use.
1805	total_fee_msat: u64,
1806	/// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1807	/// walk and may be invalid thereafter.
1808	path_htlc_minimum_msat: u64,
1809	/// All penalties incurred from this channel on the way to the destination, as calculated using
1810	/// channel scoring.
1811	path_penalty_msat: u64,
1812
1813	fee_msat: u64,
1814
1815	/// All the fees paid *after* this channel on the way to the destination
1816	next_hops_fee_msat: u64,
1817	/// Fee paid for the use of the current channel (see candidate.fees()).
1818	/// The value will be actually deducted from the counterparty balance on the previous link.
1819	hop_use_fee_msat: u64,
1820
1821	/// The quantity of funds we're willing to route over this channel
1822	value_contribution_msat: u64,
1823}
1824
1825const _NODE_MAP_SIZE_TWO_CACHE_LINES: usize = 128 - core::mem::size_of::<Option<PathBuildingHop>>();
1826const _NODE_MAP_SIZE_EXACTLY_TWO_CACHE_LINES: usize = core::mem::size_of::<Option<PathBuildingHop>>() - 128;
1827
1828impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1829	fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1830		let mut debug_struct = f.debug_struct("PathBuildingHop");
1831		debug_struct
1832			.field("source_node_id", &self.candidate.source())
1833			.field("target_node_id", &self.candidate.target())
1834			.field("short_channel_id", &self.candidate.short_channel_id())
1835			.field("is_first_hop_target", &self.is_first_hop_target)
1836			.field("is_last_hop_target", &self.is_last_hop_target)
1837			.field("total_fee_msat", &self.total_fee_msat)
1838			.field("next_hops_fee_msat", &self.next_hops_fee_msat)
1839			.field("hop_use_fee_msat", &self.hop_use_fee_msat)
1840			.field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat.saturating_sub(self.next_hops_fee_msat).saturating_sub(self.hop_use_fee_msat)))
1841			.field("path_penalty_msat", &self.path_penalty_msat)
1842			.field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1843			.field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta())
1844			.field("value_contribution_msat", &self.value_contribution_msat);
1845		debug_struct.finish()
1846	}
1847}
1848
1849// Instantiated with a list of hops with correct data in them collected during path finding,
1850// an instance of this struct should be further modified only via given methods.
1851#[derive(Clone)]
1852struct PaymentPath<'a> {
1853	hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1854}
1855
1856impl<'a> PaymentPath<'a> {
1857	// TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1858	fn get_value_msat(&self) -> u64 {
1859		self.hops.last().unwrap().0.fee_msat
1860	}
1861
1862	fn get_path_penalty_msat(&self) -> u64 {
1863		self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1864	}
1865
1866	fn get_total_fee_paid_msat(&self) -> u64 {
1867		if self.hops.len() < 1 {
1868			return 0;
1869		}
1870		let mut result = 0;
1871		// Can't use next_hops_fee_msat because it gets outdated.
1872		for (i, (hop, _)) in self.hops.iter().enumerate() {
1873			if i != self.hops.len() - 1 {
1874				result += hop.fee_msat;
1875			}
1876		}
1877		return result;
1878	}
1879
1880	/// Gets the cost (fees plus scorer penalty in msats) of the path divided by the value we
1881	/// can/will send over the path. This is also the heap score during our Dijkstra's walk.
1882	fn get_cost_per_msat(&self) -> u128 {
1883		let fee_cost = self.get_cost_msat();
1884		let value_msat = self.get_value_msat();
1885		debug_assert!(value_msat > 0, "Paths should always send more than 0 msat");
1886		if fee_cost == u64::MAX || value_msat == 0 {
1887			u64::MAX.into()
1888		} else {
1889			// In order to avoid integer division precision loss, we simply shift the costs up to
1890			// the top half of a u128 and divide by the value (which is, at max, just under a u64).
1891			((fee_cost as u128) << 64) / value_msat as u128
1892		}
1893	}
1894
1895	/// Gets the fees plus scorer penalty in msats of the path.
1896	fn get_cost_msat(&self) -> u64 {
1897		self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1898	}
1899
1900	// If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1901	// to change fees may result in an inconsistency.
1902	//
1903	// Sometimes we call this function right after constructing a path which is inconsistent in
1904	// that it the value being transferred has decreased while we were doing path finding, leading
1905	// to the fees being paid not lining up with the actual limits.
1906	//
1907	// This function may also be used to increase the value being transferred in the case that
1908	// overestimating later hops' fees caused us to underutilize earlier hops' capacity.
1909	//
1910	// Note that this function is not aware of the available_liquidity limit of any hops.
1911	//
1912	// Returns the amount that this path contributes to the total payment value, which may be greater
1913	// than `value_msat` if we had to overpay to meet the final node's `htlc_minimum_msat`.
1914	fn update_value_and_recompute_fees(&mut self, value_msat: u64) -> u64 {
1915		let mut extra_contribution_msat = 0;
1916		let mut total_fee_paid_msat = 0 as u64;
1917		for i in (0..self.hops.len()).rev() {
1918			let last_hop = i == self.hops.len() - 1;
1919
1920			// For non-last-hop, this value will represent the fees paid on the current hop. It
1921			// will consist of the fees for the use of the next hop, and extra fees to match
1922			// htlc_minimum_msat of the current channel. Last hop is handled separately.
1923			let mut cur_hop_fees_msat = 0;
1924			if !last_hop {
1925				cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1926			}
1927
1928			let cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1929			cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1930			cur_hop.path_penalty_msat += extra_contribution_msat;
1931			// Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1932			// We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1933			// set it too high just to maliciously take more fees by exploiting this
1934			// match htlc_minimum_msat logic.
1935			let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1936			if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1937				// Note that there is a risk that *previous hops* (those closer to us, as we go
1938				// payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1939				//
1940				// This might make us end up with a broken route, although this should be super-rare
1941				// in practice, both because of how healthy channels look like, and how we pick
1942				// channels in add_entry.
1943				// Also, this can't be exploited more heavily than *announce a free path and fail
1944				// all payments*.
1945				cur_hop_transferred_amount_msat += extra_fees_msat;
1946
1947				// We remember and return the extra fees on the final hop to allow accounting for
1948				// them in the path's value contribution.
1949				if last_hop {
1950					extra_contribution_msat = extra_fees_msat;
1951				} else {
1952					total_fee_paid_msat += extra_fees_msat;
1953					cur_hop_fees_msat += extra_fees_msat;
1954				}
1955			}
1956
1957			if last_hop {
1958				// Final hop is a special case: it usually has just value_msat (by design), but also
1959				// it still could overpay for the htlc_minimum_msat.
1960				cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1961			} else {
1962				// Propagate updated fees for the use of the channels to one hop back, where they
1963				// will be actually paid (fee_msat). The last hop is handled above separately.
1964				cur_hop.fee_msat = cur_hop_fees_msat;
1965			}
1966
1967			// Fee for the use of the current hop which will be deducted on the previous hop.
1968			// Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1969			// this channel is free for us.
1970			if i != 0 {
1971				if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1972					cur_hop.hop_use_fee_msat = new_fee;
1973					total_fee_paid_msat += new_fee;
1974				} else {
1975					// It should not be possible because this function is only called either to reduce the
1976					// value or with a larger amount that was already checked for overflow in
1977					// `compute_max_final_value_contribution`. In the former case, compute_fee was already
1978					// called with the same fees for larger amount and there was no overflow.
1979					unreachable!();
1980				}
1981			}
1982		}
1983		value_msat + extra_contribution_msat
1984	}
1985
1986	// Returns the maximum contribution that this path can make to the final value of the payment. May
1987	// be slightly lower than the actual max due to rounding errors when aggregating fees along the
1988	// path.
1989	fn compute_max_final_value_contribution(
1990		&self, used_liquidities: &HashMap<CandidateHopId, u64>, channel_saturation_pow_half: u8
1991	) -> u64 {
1992		let mut max_path_contribution = u64::MAX;
1993		for (idx, (hop, _)) in self.hops.iter().enumerate() {
1994			let hop_effective_capacity_msat = hop.candidate.effective_capacity();
1995			let hop_max_msat = max_htlc_from_capacity(
1996				hop_effective_capacity_msat, channel_saturation_pow_half
1997			).saturating_sub(*used_liquidities.get(&hop.candidate.id()).unwrap_or(&0_u64));
1998
1999			let next_hops_feerates_iter = self.hops
2000				.iter()
2001				.skip(idx + 1)
2002				.map(|(hop, _)| hop.candidate.fees());
2003
2004			// Aggregate the fees of the hops that come after this one, and use those fees to compute the
2005			// maximum amount that this hop can contribute to the final value received by the payee.
2006			let (next_hops_aggregated_base, next_hops_aggregated_prop) =
2007				crate::blinded_path::payment::compute_aggregated_base_prop_fee(next_hops_feerates_iter).unwrap();
2008
2009			// floor(((hop_max_msat - agg_base) * 1_000_000) / (1_000_000 + agg_prop))
2010			let hop_max_final_value_contribution = (hop_max_msat as u128)
2011				.checked_sub(next_hops_aggregated_base as u128)
2012				.and_then(|f| f.checked_mul(1_000_000))
2013				.and_then(|f| f.checked_add(next_hops_aggregated_prop as u128))
2014				.map(|f| f / ((next_hops_aggregated_prop as u128).saturating_add(1_000_000)));
2015
2016			if let Some(hop_contribution) = hop_max_final_value_contribution {
2017				let hop_contribution: u64 = hop_contribution.try_into().unwrap_or(u64::MAX);
2018				max_path_contribution = core::cmp::min(hop_contribution, max_path_contribution);
2019			} else { debug_assert!(false); }
2020		}
2021
2022		max_path_contribution
2023	}
2024}
2025
2026#[inline(always)]
2027/// Calculate the fees required to route the given amount over a channel with the given fees.
2028fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
2029	amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
2030		.and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
2031}
2032
2033#[inline(always)]
2034/// Calculate the fees required to route the given amount over a channel with the given fees,
2035/// saturating to [`u64::max_value`].
2036fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
2037	amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
2038		.map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
2039		.saturating_add(channel_fees.base_msat as u64)
2040}
2041
2042/// The default `features` we assume for a node in a route, when no `features` are known about that
2043/// specific node.
2044///
2045/// Default features are:
2046/// * variable_length_onion_optional
2047fn default_node_features() -> NodeFeatures {
2048	let mut features = NodeFeatures::empty();
2049	features.set_variable_length_onion_optional();
2050	features
2051}
2052
2053struct LoggedPayeePubkey(Option<PublicKey>);
2054impl fmt::Display for LoggedPayeePubkey {
2055	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2056		match self.0 {
2057			Some(pk) => {
2058				"payee node id ".fmt(f)?;
2059				pk.fmt(f)
2060			},
2061			None => {
2062				"blinded payee".fmt(f)
2063			},
2064		}
2065	}
2066}
2067
2068struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
2069impl<'a> fmt::Display for LoggedCandidateHop<'a> {
2070	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2071		match self.0 {
2072			CandidateRouteHop::Blinded(BlindedPathCandidate { hint, .. }) | CandidateRouteHop::OneHopBlinded(OneHopBlindedPathCandidate { hint, .. }) => {
2073				"blinded route hint with introduction node ".fmt(f)?;
2074				match hint.introduction_node() {
2075					IntroductionNode::NodeId(pubkey) => write!(f, "id {}", pubkey)?,
2076					IntroductionNode::DirectedShortChannelId(direction, scid) => {
2077						match direction {
2078							Direction::NodeOne => {
2079								write!(f, "one on channel with SCID {}", scid)?;
2080							},
2081							Direction::NodeTwo => {
2082								write!(f, "two on channel with SCID {}", scid)?;
2083							},
2084						}
2085					}
2086				}
2087				" and blinding point ".fmt(f)?;
2088				hint.blinding_point().fmt(f)
2089			},
2090			CandidateRouteHop::FirstHop(_) => {
2091				"first hop with SCID ".fmt(f)?;
2092				self.0.short_channel_id().unwrap().fmt(f)
2093			},
2094			CandidateRouteHop::PrivateHop(_) => {
2095				"route hint with SCID ".fmt(f)?;
2096				self.0.short_channel_id().unwrap().fmt(f)
2097			},
2098			_ => {
2099				"SCID ".fmt(f)?;
2100				self.0.short_channel_id().unwrap().fmt(f)
2101			},
2102		}
2103	}
2104}
2105
2106#[inline]
2107fn sort_first_hop_channels(
2108	channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
2109	recommended_value_msat: u64, our_node_pubkey: &PublicKey
2110) {
2111	// Sort the first_hops channels to the same node(s) in priority order of which channel we'd
2112	// most like to use.
2113	//
2114	// First, if channels are below `recommended_value_msat`, sort them in descending order,
2115	// preferring larger channels to avoid splitting the payment into more MPP parts than is
2116	// required.
2117	//
2118	// Second, because simply always sorting in descending order would always use our largest
2119	// available outbound capacity, needlessly fragmenting our available channel capacities,
2120	// sort channels above `recommended_value_msat` in ascending order, preferring channels
2121	// which have enough, but not too much, capacity for the payment.
2122	//
2123	// Available outbound balances factor in liquidity already reserved for previously found paths.
2124	channels.sort_unstable_by(|chan_a, chan_b| {
2125		let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
2126			.saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
2127			our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
2128		let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
2129			.saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
2130			our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
2131		if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
2132			// Sort in descending order
2133			chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
2134		} else {
2135			// Sort in ascending order
2136			chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
2137		}
2138	});
2139}
2140
2141/// Finds a route from us (payer) to the given target node (payee).
2142///
2143/// If the payee provided features in their invoice, they should be provided via the `payee` field
2144/// in the given [`RouteParameters::payment_params`].
2145/// Without this, MPP will only be used if the payee's features are available in the network graph.
2146///
2147/// Private routing paths between a public node and the target may be included in the `payee` field
2148/// of [`RouteParameters::payment_params`].
2149///
2150/// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
2151/// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
2152/// from `network_graph` will be ignored, and only those in `first_hops` will be used.
2153///
2154/// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
2155/// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
2156/// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
2157///
2158/// # Panics
2159///
2160/// Panics if first_hops contains channels without `short_channel_id`s;
2161/// [`ChannelManager::list_usable_channels`] will never include such channels.
2162///
2163/// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
2164/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
2165/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
2166pub fn find_route<L: Deref, GL: Deref, S: ScoreLookUp>(
2167	our_node_pubkey: &PublicKey, route_params: &RouteParameters,
2168	network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
2169	scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
2170) -> Result<Route, LightningError>
2171where L::Target: Logger, GL::Target: Logger {
2172	let graph_lock = network_graph.read_only();
2173	let mut route = get_route(our_node_pubkey, &route_params, &graph_lock, first_hops, logger,
2174		scorer, score_params, random_seed_bytes)?;
2175	add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2176	Ok(route)
2177}
2178
2179pub(crate) fn get_route<L: Deref, S: ScoreLookUp>(
2180	our_node_pubkey: &PublicKey, route_params: &RouteParameters, network_graph: &ReadOnlyNetworkGraph,
2181	first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S, score_params: &S::ScoreParams,
2182	_random_seed_bytes: &[u8; 32]
2183) -> Result<Route, LightningError>
2184where L::Target: Logger {
2185
2186	let payment_params = &route_params.payment_params;
2187	let max_path_length = core::cmp::min(payment_params.max_path_length, MAX_PATH_LENGTH_ESTIMATE);
2188	let final_value_msat = route_params.final_value_msat;
2189	// If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
2190	// unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
2191	// so use a dummy id for this in the blinded case.
2192	let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
2193	const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
2194	let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
2195	let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
2196	let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
2197
2198	if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
2199		return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
2200	}
2201	if our_node_id == maybe_dummy_payee_node_id {
2202		return Err(LightningError{err: "Invalid origin node id provided, use a different one".to_owned(), action: ErrorAction::IgnoreError});
2203	}
2204
2205	if final_value_msat > MAX_VALUE_MSAT {
2206		return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
2207	}
2208
2209	if final_value_msat == 0 {
2210		return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
2211	}
2212
2213	let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
2214	if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
2215		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});
2216	}
2217
2218	// The general routing idea is the following:
2219	// 1. Fill first/last hops communicated by the caller.
2220	// 2. Attempt to construct a path from payer to payee for transferring
2221	//    any ~sufficient (described later) value.
2222	//    If succeed, remember which channels were used and how much liquidity they have available,
2223	//    so that future paths don't rely on the same liquidity.
2224	// 3. Proceed to the next step if:
2225	//    - we hit the recommended target value;
2226	//    - OR if we could not construct a new path. Any next attempt will fail too.
2227	//    Otherwise, repeat step 2.
2228	// 4. See if we managed to collect paths which aggregately are able to transfer target value
2229	//    (not recommended value).
2230	// 5. If yes, proceed. If not, fail routing.
2231	// 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
2232	//    transferred up to the transfer target value.
2233	// 7. Reduce the value of the last path until we are sending only the target value.
2234	// 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
2235	//    them so that we're not sending two HTLCs along the same path.
2236
2237	// As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
2238	// distance from the payee
2239	//
2240	// We are not a faithful Dijkstra's implementation because we can change values which impact
2241	// earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
2242	// liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
2243	// the value we are currently attempting to send over a path, we simply reduce the value being
2244	// sent along the path for any hops after that channel. This may imply that later fees (which
2245	// we've already tabulated) are lower because a smaller value is passing through the channels
2246	// (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
2247	// channels which were selected earlier (and which may still be used for other paths without a
2248	// lower liquidity limit), so we simply accept that some liquidity-limited paths may be
2249	// de-preferenced.
2250	//
2251	// One potentially problematic case for this algorithm would be if there are many
2252	// liquidity-limited paths which are liquidity-limited near the destination (ie early in our
2253	// graph walking), we may never find a path which is not liquidity-limited and has lower
2254	// proportional fee (and only lower absolute fee when considering the ultimate value sent).
2255	// Because we only consider paths with at least 5% of the total value being sent, the damage
2256	// from such a case should be limited, however this could be further reduced in the future by
2257	// calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
2258	// limits for the purposes of fee calculation.
2259	//
2260	// Alternatively, we could store more detailed path information in the heap (targets, below)
2261	// and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
2262	// up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
2263	// and practically (as we would need to store dynamically-allocated path information in heap
2264	// objects, increasing malloc traffic and indirect memory access significantly). Further, the
2265	// results of such an algorithm would likely be biased towards lower-value paths.
2266	//
2267	// Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
2268	// outside of our current search value, running a path search more times to gather candidate
2269	// paths at different values. While this may be acceptable, further path searches may increase
2270	// runtime for little gain. Specifically, the current algorithm rather efficiently explores the
2271	// graph for candidate paths, calculating the maximum value which can realistically be sent at
2272	// the same time, remaining generic across different payment values.
2273
2274	let network_channels = network_graph.channels();
2275	let network_nodes = network_graph.nodes();
2276
2277	if payment_params.max_path_count == 0 {
2278		return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
2279	}
2280
2281	// Allow MPP only if we have a features set from somewhere that indicates the payee supports
2282	// it. If the payee supports it they're supposed to include it in the invoice, so that should
2283	// work reliably.
2284	let allow_mpp = if payment_params.max_path_count == 1 {
2285		false
2286	} else if payment_params.payee.supports_basic_mpp() {
2287		true
2288	} else if let Some(payee) = payee_node_id_opt {
2289		network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
2290			|info| info.features().supports_basic_mpp()))
2291	} else { false };
2292
2293	let max_total_routing_fee_msat = route_params.max_total_routing_fee_msat.unwrap_or(u64::max_value());
2294
2295	let first_hop_count = first_hops.map(|hops| hops.len()).unwrap_or(0);
2296	log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph of {} nodes and {} channels with a fee limit of {} msat",
2297		our_node_pubkey, LoggedPayeePubkey(payment_params.payee.node_id()),
2298		if allow_mpp { "with" } else { "without" },
2299		first_hop_count, if first_hops.is_some() { "" } else { "not " },
2300		network_graph.nodes().len(), network_graph.channels().len(),
2301		max_total_routing_fee_msat);
2302
2303	if first_hop_count < 10 {
2304		if let Some(hops) = first_hops {
2305			for hop in hops {
2306				log_trace!(
2307					logger,
2308					" First hop through {}/{} can send between {}msat and {}msat (inclusive).",
2309					hop.counterparty.node_id,
2310					hop.get_outbound_payment_scid().unwrap_or(0),
2311					hop.next_outbound_htlc_minimum_msat,
2312					hop.next_outbound_htlc_limit_msat
2313				);
2314			}
2315		}
2316	}
2317
2318	let mut node_counter_builder = NodeCountersBuilder::new(&network_graph);
2319
2320	let payer_node_counter = node_counter_builder.select_node_counter_for_pubkey(*our_node_pubkey);
2321	let payee_node_counter = node_counter_builder.select_node_counter_for_pubkey(maybe_dummy_payee_pk);
2322
2323	for route in payment_params.payee.unblinded_route_hints().iter() {
2324		for hop in route.0.iter() {
2325			node_counter_builder.select_node_counter_for_pubkey(hop.src_node_id);
2326		}
2327	}
2328
2329	// Step (1). Prepare first and last hop targets.
2330	//
2331	// For unblinded first- and last-hop channels, cache them in maps so that we can detect them as
2332	// we walk the graph and incorporate them into our candidate set.
2333	// For blinded last-hop paths, look up their introduction point and cache the node counters
2334	// identifying them.
2335	let mut first_hop_targets: HashMap<_, (Vec<&ChannelDetails>, u32)> =
2336		hash_map_with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
2337	if let Some(hops) = first_hops {
2338		for chan in hops {
2339			if chan.get_outbound_payment_scid().is_none() {
2340				panic!("first_hops should be filled in with usable channels, not pending ones");
2341			}
2342			if chan.counterparty.node_id == *our_node_pubkey {
2343				return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
2344			}
2345			let counterparty_id = NodeId::from_pubkey(&chan.counterparty.node_id);
2346			first_hop_targets
2347				.entry(counterparty_id)
2348				.or_insert_with(|| {
2349					// Make sure there's a counter assigned for the counterparty
2350					let node_counter = node_counter_builder.select_node_counter_for_id(counterparty_id);
2351					(Vec::new(), node_counter)
2352				})
2353				.0.push(chan);
2354		}
2355		if first_hop_targets.is_empty() {
2356			return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
2357		}
2358	}
2359
2360	let node_counters = node_counter_builder.build();
2361
2362	let introduction_node_id_cache = calculate_blinded_path_intro_points(
2363		&payment_params, &node_counters, network_graph, &logger, our_node_id, &first_hop_targets,
2364	)?;
2365
2366	let mut last_hop_candidates =
2367		hash_map_with_capacity(payment_params.payee.unblinded_route_hints().len());
2368	for route in payment_params.payee.unblinded_route_hints().iter()
2369		.filter(|route| !route.0.is_empty())
2370	{
2371		let hop_iter = route.0.iter().rev();
2372		let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
2373			route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
2374
2375		for (hop, prev_hop_id) in hop_iter.zip(prev_hop_iter) {
2376			let (target, private_target_node_counter) =
2377				node_counters.private_node_counter_from_pubkey(&prev_hop_id)
2378					.ok_or_else(|| {
2379						debug_assert!(false);
2380						LightningError { err: "We should always have private target node counters available".to_owned(), action: ErrorAction::IgnoreError }
2381					})?;
2382			let (_src_id, private_source_node_counter) =
2383				node_counters.private_node_counter_from_pubkey(&hop.src_node_id)
2384					.ok_or_else(|| {
2385						debug_assert!(false);
2386						LightningError { err: "We should always have private source node counters available".to_owned(), action: ErrorAction::IgnoreError }
2387					})?;
2388
2389			if let Some((first_channels, _)) = first_hop_targets.get(target) {
2390				let matches_an_scid = |d: &&ChannelDetails|
2391					d.outbound_scid_alias == Some(hop.short_channel_id) || d.short_channel_id == Some(hop.short_channel_id);
2392				if first_channels.iter().any(matches_an_scid) {
2393					log_trace!(logger, "Ignoring route hint with SCID {} (and any previous) due to it being a direct channel of ours.",
2394						hop.short_channel_id);
2395					break;
2396				}
2397			}
2398
2399			let candidate = network_channels
2400				.get(&hop.short_channel_id)
2401				.and_then(|channel| channel.as_directed_to(target))
2402				.map(|(info, _)| CandidateRouteHop::PublicHop(PublicHopCandidate {
2403					info,
2404					short_channel_id: hop.short_channel_id,
2405				}))
2406				.unwrap_or_else(|| CandidateRouteHop::PrivateHop(PrivateHopCandidate {
2407					hint: hop, target_node_id: target,
2408					source_node_counter: *private_source_node_counter,
2409					target_node_counter: *private_target_node_counter,
2410				}));
2411
2412			last_hop_candidates.entry(private_target_node_counter).or_insert_with(Vec::new).push(candidate);
2413		}
2414	}
2415
2416	// The main heap containing all candidate next-hops sorted by their score (max(fee,
2417	// htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
2418	// adding duplicate entries when we find a better path to a given node.
2419	let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
2420
2421	// Map from node_id to information about the best current path to that node, including feerate
2422	// information.
2423	let dist_len = node_counters.max_counter() + 1;
2424	let mut dist: Vec<Option<PathBuildingHop>> = vec![None; dist_len as usize];
2425
2426	// During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
2427	// indicating that we may wish to try again with a higher value, potentially paying to meet an
2428	// htlc_minimum with extra fees while still finding a cheaper path.
2429	let mut hit_minimum_limit;
2430
2431	// When arranging a route, we select multiple paths so that we can make a multi-path payment.
2432	// We start with a path_value of the exact amount we want, and if that generates a route we may
2433	// return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
2434	// amount we want in total across paths, selecting the best subset at the end.
2435	const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
2436	let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
2437	let mut path_value_msat = final_value_msat;
2438
2439	// Routing Fragmentation Mitigation heuristic:
2440	//
2441	// Routing fragmentation across many payment paths increases the overall routing
2442	// fees as you have irreducible routing fees per-link used (`fee_base_msat`).
2443	// Taking too many smaller paths also increases the chance of payment failure.
2444	// Thus to avoid this effect, we require from our collected links to provide
2445	// at least a minimal contribution to the recommended value yet-to-be-fulfilled.
2446	// This requirement is currently set to be 1/max_path_count of the payment
2447	// value to ensure we only ever return routes that do not violate this limit.
2448	let minimal_value_contribution_msat: u64 = if allow_mpp {
2449		(final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
2450	} else {
2451		final_value_msat
2452	};
2453
2454	// When we start collecting routes we enforce the max_channel_saturation_power_of_half
2455	// requirement strictly. After we've collected enough (or if we fail to find new routes) we
2456	// drop the requirement by setting this to 0.
2457	let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
2458
2459	// In order to already account for some of the privacy enhancing random CLTV
2460	// expiry delta offset we add on top later, we subtract a rough estimate
2461	// (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
2462	let max_total_cltv_expiry_delta: u16 =
2463		(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2464		.checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
2465		.unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
2466		.try_into()
2467		.unwrap_or(u16::MAX);
2468
2469	// Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
2470	// determine if the channel can be used by additional MPP paths or to inform path finding
2471	// decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
2472	// is used. Hence, liquidity used in one direction will not offset any used in the opposite
2473	// direction.
2474	let mut used_liquidities: HashMap<CandidateHopId, u64> =
2475		hash_map_with_capacity(network_nodes.len());
2476
2477	// Keeping track of how much value we already collected across other paths. Helps to decide
2478	// when we want to stop looking for new paths.
2479	let mut already_collected_value_msat = 0;
2480
2481	for (_, (channels, _)) in first_hop_targets.iter_mut() {
2482		sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
2483			our_node_pubkey);
2484	}
2485
2486	log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
2487		LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
2488
2489	// Remember how many candidates we ignored to allow for some logging afterwards.
2490	let mut num_ignored_value_contribution: u32 = 0;
2491	let mut num_ignored_path_length_limit: u32 = 0;
2492	let mut num_ignored_cltv_delta_limit: u32 = 0;
2493	let mut num_ignored_previously_failed: u32 = 0;
2494	let mut num_ignored_total_fee_limit: u32 = 0;
2495	let mut num_ignored_avoid_overpayment: u32 = 0;
2496	let mut num_ignored_htlc_minimum_msat_limit: u32 = 0;
2497
2498	macro_rules! add_entry {
2499		// Adds entry which goes from $candidate.source() to $candidate.target() over the $candidate hop.
2500		// $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
2501		// since that value has to be transferred over this channel.
2502		// Returns the contribution amount of $candidate if the channel caused an update to `targets`.
2503		( $candidate: expr, $next_hops_fee_msat: expr,
2504			$next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
2505			$next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
2506			// We "return" whether we updated the path at the end, and how much we can route via
2507			// this channel, via this:
2508			let mut hop_contribution_amt_msat = None;
2509
2510			#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2511			if let Some(counter) = $candidate.target_node_counter() {
2512				// Once we are adding paths backwards from a given target, we've selected the best
2513				// path from that target to the destination and it should no longer change. We thus
2514				// set the best-path selected flag and check that it doesn't change below.
2515				if let Some(node) = &mut dist[counter as usize] {
2516					node.best_path_from_hop_selected = true;
2517				} else if counter != payee_node_counter {
2518					panic!("No dist entry for target node counter {}", counter);
2519				}
2520			}
2521
2522			// Channels to self should not be used. This is more of belt-and-suspenders, because in
2523			// practice these cases should be caught earlier:
2524			// - for regular channels at channel announcement (TODO)
2525			// - for first and last hops early in get_route
2526			let src_node_id = $candidate.source();
2527			if Some(src_node_id) != $candidate.target() {
2528				let scid_opt = $candidate.short_channel_id();
2529				let effective_capacity = $candidate.effective_capacity();
2530				let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
2531
2532				// It is tricky to subtract $next_hops_fee_msat from available liquidity here.
2533				// It may be misleading because we might later choose to reduce the value transferred
2534				// over these channels, and the channel which was insufficient might become sufficient.
2535				// Worst case: we drop a good channel here because it can't cover the high following
2536				// fees caused by one expensive channel, but then this channel could have been used
2537				// if the amount being transferred over this path is lower.
2538				// We do this for now, but this is a subject for removal.
2539				if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
2540					let cltv_expiry_delta = $candidate.cltv_expiry_delta();
2541					let htlc_minimum_msat = $candidate.htlc_minimum_msat();
2542					let used_liquidity_msat = used_liquidities
2543						.get(&$candidate.id())
2544						.map_or(0, |used_liquidity_msat| {
2545							available_value_contribution_msat = available_value_contribution_msat
2546								.saturating_sub(*used_liquidity_msat);
2547							*used_liquidity_msat
2548						});
2549
2550					// Do not consider candidate hops that would exceed the maximum path length.
2551					let path_length_to_node = $next_hops_path_length
2552						+ if $candidate.blinded_hint_idx().is_some() { 0 } else { 1 };
2553					let exceeds_max_path_length = path_length_to_node > max_path_length;
2554
2555					// Do not consider candidates that exceed the maximum total cltv expiry limit.
2556					let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
2557						.saturating_add(cltv_expiry_delta);
2558					let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta as u32;
2559
2560					let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
2561					// Verify the liquidity offered by this channel complies to the minimal contribution.
2562					let contributes_sufficient_value = value_contribution_msat >= minimal_value_contribution_msat;
2563					// Includes paying fees for the use of the following channels.
2564					let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
2565						Some(result) => result,
2566						// Can't overflow due to how the values were computed right above.
2567						None => unreachable!(),
2568					};
2569					#[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2570					let over_path_minimum_msat = amount_to_transfer_over_msat >= htlc_minimum_msat &&
2571						amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
2572
2573					#[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
2574					let may_overpay_to_meet_path_minimum_msat =
2575						(amount_to_transfer_over_msat < htlc_minimum_msat &&
2576						  recommended_value_msat >= htlc_minimum_msat) ||
2577						(amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
2578						 recommended_value_msat >= $next_hops_path_htlc_minimum_msat);
2579
2580					let payment_failed_on_this_channel = match scid_opt {
2581						Some(scid) => payment_params.previously_failed_channels.contains(&scid),
2582						None => match $candidate.blinded_hint_idx() {
2583							Some(idx) => {
2584								payment_params.previously_failed_blinded_path_idxs.contains(&(idx as u64))
2585							},
2586							None => false,
2587						},
2588					};
2589
2590					let (should_log_candidate, first_hop_details) = match $candidate {
2591						CandidateRouteHop::FirstHop(hop) => (true, Some(hop.details)),
2592						CandidateRouteHop::PrivateHop(_) => (true, None),
2593						CandidateRouteHop::Blinded(_) => (true, None),
2594						CandidateRouteHop::OneHopBlinded(_) => (true, None),
2595						_ => (false, None),
2596					};
2597
2598					// If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
2599					// bother considering this channel. If retrying with recommended_value_msat may
2600					// allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
2601					// around again with a higher amount.
2602					if !contributes_sufficient_value {
2603						if should_log_candidate {
2604							log_trace!(logger, "Ignoring {} due to insufficient value contribution (channel max {:?}).",
2605								LoggedCandidateHop(&$candidate),
2606								effective_capacity);
2607						}
2608						num_ignored_value_contribution += 1;
2609					} else if exceeds_max_path_length {
2610						if should_log_candidate {
2611							log_trace!(logger, "Ignoring {} due to exceeding maximum path length limit.", LoggedCandidateHop(&$candidate));
2612						}
2613						num_ignored_path_length_limit += 1;
2614					} else if exceeds_cltv_delta_limit {
2615						if should_log_candidate {
2616							log_trace!(logger, "Ignoring {} due to exceeding CLTV delta limit.", LoggedCandidateHop(&$candidate));
2617
2618							if let Some(_) = first_hop_details {
2619								log_trace!(logger,
2620									"First hop candidate cltv_expiry_delta: {}. Limit: {}",
2621									hop_total_cltv_delta,
2622									max_total_cltv_expiry_delta,
2623								);
2624							}
2625						}
2626						num_ignored_cltv_delta_limit += 1;
2627					} else if payment_failed_on_this_channel {
2628						if should_log_candidate {
2629							log_trace!(logger, "Ignoring {} due to a failed previous payment attempt.", LoggedCandidateHop(&$candidate));
2630						}
2631						num_ignored_previously_failed += 1;
2632					} else if may_overpay_to_meet_path_minimum_msat {
2633						if should_log_candidate {
2634							log_trace!(logger,
2635								"Ignoring {} to avoid overpaying to meet htlc_minimum_msat limit ({}).",
2636								LoggedCandidateHop(&$candidate), $candidate.htlc_minimum_msat());
2637						}
2638						num_ignored_avoid_overpayment += 1;
2639						hit_minimum_limit = true;
2640					} else if over_path_minimum_msat {
2641						// Note that low contribution here (limited by available_liquidity_msat)
2642						// might violate htlc_minimum_msat on the hops which are next along the
2643						// payment path (upstream to the payee). To avoid that, we recompute
2644						// path fees knowing the final path contribution after constructing it.
2645						let curr_min = cmp::max(
2646							$next_hops_path_htlc_minimum_msat, htlc_minimum_msat
2647						);
2648						let src_node_counter = $candidate.src_node_counter();
2649						let mut candidate_fees = $candidate.fees();
2650						if src_node_counter == payer_node_counter {
2651							// We do not charge ourselves a fee to use our own channels.
2652							candidate_fees = RoutingFees {
2653								proportional_millionths: 0,
2654								base_msat: 0,
2655							};
2656						}
2657						let path_htlc_minimum_msat = compute_fees_saturating(curr_min, candidate_fees)
2658							.saturating_add(curr_min);
2659
2660						let dist_entry = &mut dist[src_node_counter as usize];
2661						let old_entry = if let Some(hop) = dist_entry {
2662							hop
2663						} else {
2664							// If there was previously no known way to access the source node
2665							// (recall it goes payee-to-payer) of short_channel_id, first add a
2666							// semi-dummy record just to compute the fees to reach the source node.
2667							// This will affect our decision on selecting short_channel_id
2668							// as a way to reach the $candidate.target() node.
2669							*dist_entry = Some(PathBuildingHop {
2670								candidate: $candidate.clone(),
2671								fee_msat: 0,
2672								next_hops_fee_msat: u64::max_value(),
2673								hop_use_fee_msat: u64::max_value(),
2674								total_fee_msat: u64::max_value(),
2675								path_htlc_minimum_msat,
2676								path_penalty_msat: u64::max_value(),
2677								was_processed: false,
2678								is_first_hop_target: false,
2679								is_last_hop_target: false,
2680								#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2681								best_path_from_hop_selected: false,
2682								value_contribution_msat,
2683							});
2684							dist_entry.as_mut().unwrap()
2685						};
2686
2687						#[allow(unused_mut)] // We only use the mut in cfg(test)
2688						let mut should_process = !old_entry.was_processed;
2689						#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2690						{
2691							// In test/fuzzing builds, we do extra checks to make sure the skipping
2692							// of already-seen nodes only happens in cases we expect (see below).
2693							if !should_process { should_process = true; }
2694						}
2695
2696						if should_process {
2697							let mut hop_use_fee_msat = 0;
2698							let mut total_fee_msat: u64 = $next_hops_fee_msat;
2699
2700							// Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
2701							// will have the same effective-fee
2702							if src_node_id != our_node_id {
2703								// Note that `u64::max_value` means we'll always fail the
2704								// `old_entry.total_fee_msat > total_fee_msat` check below
2705								hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, candidate_fees);
2706								total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
2707							}
2708
2709							// Ignore hops if augmenting the current path to them would put us over `max_total_routing_fee_msat`
2710							if total_fee_msat > max_total_routing_fee_msat {
2711								if should_log_candidate {
2712									log_trace!(logger, "Ignoring {} with fee {total_fee_msat} due to exceeding max total routing fee limit {max_total_routing_fee_msat}.", LoggedCandidateHop(&$candidate));
2713
2714									if let Some(_) = first_hop_details {
2715										log_trace!(logger,
2716											"First hop candidate routing fee: {}. Limit: {}",
2717											total_fee_msat,
2718											max_total_routing_fee_msat,
2719										);
2720									}
2721								}
2722								num_ignored_total_fee_limit += 1;
2723							} else {
2724								let channel_usage = ChannelUsage {
2725									amount_msat: amount_to_transfer_over_msat,
2726									inflight_htlc_msat: used_liquidity_msat,
2727									effective_capacity,
2728								};
2729								let channel_penalty_msat =
2730									scorer.channel_penalty_msat($candidate,
2731										channel_usage,
2732										score_params);
2733								let path_penalty_msat = $next_hops_path_penalty_msat
2734									.saturating_add(channel_penalty_msat);
2735
2736								// Update the way of reaching $candidate.source()
2737								// with the given short_channel_id (from $candidate.target()),
2738								// if this way is cheaper than the already known
2739								// (considering the cost to "reach" this channel from the route destination,
2740								// the cost of using this channel,
2741								// and the cost of routing to the source node of this channel).
2742								// Also, consider that htlc_minimum_msat_difference, because we might end up
2743								// paying it. Consider the following exploit:
2744								// we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
2745								// and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
2746								// 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
2747								// by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
2748								// to this channel.
2749								// Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
2750								// but it may require additional tracking - we don't want to double-count
2751								// the fees included in $next_hops_path_htlc_minimum_msat, but also
2752								// can't use something that may decrease on future hops.
2753								let old_fee_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
2754									.saturating_add(old_entry.path_penalty_msat);
2755								let new_fee_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
2756									.saturating_add(path_penalty_msat);
2757								// The actual score we use for our heap is the cost divided by how
2758								// much we are thinking of sending over this channel. This avoids
2759								// prioritizing channels that have a very low fee because we aren't
2760								// sending very much over them.
2761								// In order to avoid integer division precision loss, we simply
2762								// shift the costs up to the top half of a u128 and divide by the
2763								// value (which is, at max, just under a u64).
2764								let old_cost = if old_fee_cost != u64::MAX && old_entry.value_contribution_msat != 0 {
2765									((old_fee_cost as u128) << 64) / old_entry.value_contribution_msat as u128
2766								} else {
2767									u128::MAX
2768								};
2769								let new_cost = if new_fee_cost != u64::MAX {
2770									// value_contribution_msat is always >= 1, checked above via
2771									// `contributes_sufficient_value`.
2772									((new_fee_cost as u128) << 64) / value_contribution_msat as u128
2773								} else {
2774									u128::MAX
2775								};
2776
2777								if !old_entry.was_processed && new_cost < old_cost {
2778									#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2779									{
2780										assert!(!old_entry.best_path_from_hop_selected);
2781										assert!(hop_total_cltv_delta <= u16::MAX as u32);
2782									}
2783
2784									let new_graph_node = RouteGraphNode {
2785										node_counter: src_node_counter,
2786										score: new_cost,
2787										total_cltv_delta: hop_total_cltv_delta as u16,
2788										value_contribution_msat,
2789										path_length_to_node,
2790									};
2791									targets.push(new_graph_node);
2792									old_entry.next_hops_fee_msat = $next_hops_fee_msat;
2793									old_entry.hop_use_fee_msat = hop_use_fee_msat;
2794									old_entry.total_fee_msat = total_fee_msat;
2795									old_entry.candidate = $candidate.clone();
2796									old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
2797									old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
2798									old_entry.path_penalty_msat = path_penalty_msat;
2799									old_entry.value_contribution_msat = value_contribution_msat;
2800									hop_contribution_amt_msat = Some(value_contribution_msat);
2801								} else if old_entry.was_processed && new_cost < old_cost {
2802									#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2803									{
2804										// If we're skipping processing a node which was previously
2805										// processed even though we found another path to it with a
2806										// cheaper fee, check that it was because the second path we
2807										// found (which we are processing now) has a lower value
2808										// contribution due to an HTLC minimum limit.
2809										//
2810										// e.g. take a graph with two paths from node 1 to node 2, one
2811										// through channel A, and one through channel B. Channel A and
2812										// B are both in the to-process heap, with their scores set by
2813										// a higher htlc_minimum than fee.
2814										// Channel A is processed first, and the channels onwards from
2815										// node 1 are added to the to-process heap. Thereafter, we pop
2816										// Channel B off of the heap, note that it has a much more
2817										// restrictive htlc_maximum_msat, and recalculate the fees for
2818										// all of node 1's channels using the new, reduced, amount.
2819										//
2820										// This would be bogus - we'd be selecting a higher-fee path
2821										// with a lower htlc_maximum_msat instead of the one we'd
2822										// already decided to use.
2823										debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
2824										debug_assert!(
2825											value_contribution_msat + path_penalty_msat <
2826											old_entry.value_contribution_msat + old_entry.path_penalty_msat
2827										);
2828									}
2829								}
2830							}
2831						}
2832					} else {
2833						if should_log_candidate {
2834							log_trace!(logger,
2835								"Ignoring {} due to its htlc_minimum_msat limit.",
2836								LoggedCandidateHop(&$candidate));
2837
2838							if let Some(details) = first_hop_details {
2839								log_trace!(logger,
2840									"First hop candidate next_outbound_htlc_minimum_msat: {}",
2841									details.next_outbound_htlc_minimum_msat,
2842								);
2843							}
2844						}
2845						num_ignored_htlc_minimum_msat_limit += 1;
2846					}
2847				}
2848			}
2849			hop_contribution_amt_msat
2850		} }
2851	}
2852
2853	let default_node_features = default_node_features();
2854
2855	// Find ways (channels with destination) to reach a given node and store them
2856	// in the corresponding data structures (routing graph etc).
2857	// $fee_to_target_msat represents how much it costs to reach to this node from the payee,
2858	// meaning how much will be paid in fees after this node (to the best of our knowledge).
2859	// This data can later be helpful to optimize routing (pay lower fees).
2860	macro_rules! add_entries_to_cheapest_to_target_node {
2861		( $node_counter: expr, $node_id: expr, $next_hops_value_contribution: expr,
2862		  $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
2863			let fee_to_target_msat;
2864			let next_hops_path_htlc_minimum_msat;
2865			let next_hops_path_penalty_msat;
2866			let (is_first_hop_target, is_last_hop_target);
2867			let skip_node = if let Some(elem) = &mut dist[$node_counter as usize] {
2868				let was_processed = elem.was_processed;
2869				elem.was_processed = true;
2870				fee_to_target_msat = elem.total_fee_msat;
2871				next_hops_path_htlc_minimum_msat = elem.path_htlc_minimum_msat;
2872				next_hops_path_penalty_msat = elem.path_penalty_msat;
2873				is_first_hop_target = elem.is_first_hop_target;
2874				is_last_hop_target = elem.is_last_hop_target;
2875				was_processed
2876			} else {
2877				// Entries are added to dist in add_entry!() when there is a channel from a node.
2878				// Because there are no channels from payee, it will not have a dist entry at this point.
2879				// If we're processing any other node, it is always be the result of a channel from it.
2880				debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
2881
2882				fee_to_target_msat = 0;
2883				next_hops_path_htlc_minimum_msat = 0;
2884				next_hops_path_penalty_msat = 0;
2885				is_first_hop_target = false;
2886				is_last_hop_target = false;
2887				false
2888			};
2889
2890			if !skip_node {
2891				if is_last_hop_target {
2892					if let Some(candidates) = last_hop_candidates.get(&$node_counter) {
2893						for candidate in candidates {
2894							add_entry!(candidate, fee_to_target_msat,
2895								$next_hops_value_contribution,
2896								next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2897								$next_hops_cltv_delta, $next_hops_path_length);
2898						}
2899					}
2900				}
2901				if is_first_hop_target {
2902					if let Some((first_channels, peer_node_counter)) = first_hop_targets.get(&$node_id) {
2903						for details in first_channels {
2904							debug_assert_eq!(*peer_node_counter, $node_counter);
2905							let candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
2906								details, payer_node_id: &our_node_id, payer_node_counter,
2907								target_node_counter: $node_counter,
2908							});
2909							add_entry!(&candidate, fee_to_target_msat,
2910								$next_hops_value_contribution,
2911								next_hops_path_htlc_minimum_msat, next_hops_path_penalty_msat,
2912								$next_hops_cltv_delta, $next_hops_path_length);
2913						}
2914					}
2915				}
2916
2917				if let Some(node) = network_nodes.get(&$node_id) {
2918					let features = if let Some(node_info) = node.announcement_info.as_ref() {
2919						&node_info.features()
2920					} else {
2921						&default_node_features
2922					};
2923
2924					if !features.requires_unknown_bits() {
2925						for chan_id in node.channels.iter() {
2926							let chan = network_channels.get(chan_id).unwrap();
2927							if !chan.features.requires_unknown_bits() {
2928								if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
2929									if first_hops.is_none() || *source != our_node_id {
2930										if directed_channel.direction().enabled {
2931											let candidate = CandidateRouteHop::PublicHop(PublicHopCandidate {
2932												info: directed_channel,
2933												short_channel_id: *chan_id,
2934											});
2935											add_entry!(&candidate,
2936												fee_to_target_msat,
2937												$next_hops_value_contribution,
2938												next_hops_path_htlc_minimum_msat,
2939												next_hops_path_penalty_msat,
2940												$next_hops_cltv_delta, $next_hops_path_length);
2941										}
2942									}
2943								}
2944							}
2945						}
2946					}
2947				}
2948			}
2949		};
2950	}
2951
2952	let mut payment_paths = Vec::<PaymentPath>::new();
2953
2954	// TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
2955	'paths_collection: loop {
2956		// For every new path, start from scratch, except for used_liquidities, which
2957		// helps to avoid reusing previously selected paths in future iterations.
2958		targets.clear();
2959		for e in dist.iter_mut() {
2960			*e = None;
2961		}
2962
2963		// Step (2).
2964		// Add entries for first-hop and last-hop channel hints to `dist` and add the payee node as
2965		// the best entry via `add_entry`.
2966		// For first- and last-hop hints we need only add dummy entries in `dist` with the relevant
2967		// flags set. As we walk the graph in `add_entries_to_cheapest_to_target_node` we'll check
2968		// those flags and add the channels described by the hints.
2969		// We then either add the payee using `add_entries_to_cheapest_to_target_node` or add the
2970		// blinded paths to the payee using `add_entry`, filling `targets` and setting us up for
2971		// our graph walk.
2972		for (_, (chans, peer_node_counter)) in first_hop_targets.iter() {
2973			// In order to avoid looking up whether each node is a first-hop target, we store a
2974			// dummy entry in dist for each first-hop target, allowing us to do this lookup for
2975			// free since we're already looking at the `was_processed` flag.
2976			//
2977			// Note that all the fields (except `is_{first,last}_hop_target`) will be overwritten
2978			// whenever we find a path to the target, so are left as dummies here.
2979			dist[*peer_node_counter as usize] = Some(PathBuildingHop {
2980				candidate: CandidateRouteHop::FirstHop(FirstHopCandidate {
2981					details: &chans[0],
2982					payer_node_id: &our_node_id,
2983					target_node_counter: u32::max_value(),
2984					payer_node_counter: u32::max_value(),
2985				}),
2986				fee_msat: 0,
2987				next_hops_fee_msat: u64::max_value(),
2988				hop_use_fee_msat: u64::max_value(),
2989				total_fee_msat: u64::max_value(),
2990				path_htlc_minimum_msat: u64::max_value(),
2991				path_penalty_msat: u64::max_value(),
2992				was_processed: false,
2993				is_first_hop_target: true,
2994				is_last_hop_target: false,
2995				value_contribution_msat: 0,
2996				#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
2997				best_path_from_hop_selected: false,
2998			});
2999		}
3000		for (target_node_counter, candidates) in last_hop_candidates.iter() {
3001			// In order to avoid looking up whether each node is a last-hop target, we store a
3002			// dummy entry in dist for each last-hop target, allowing us to do this lookup for
3003			// free since we're already looking at the `was_processed` flag.
3004			//
3005			// Note that all the fields (except `is_{first,last}_hop_target`) will be overwritten
3006			// whenever we find a path to the target, so are left as dummies here.
3007			debug_assert!(!candidates.is_empty());
3008			if candidates.is_empty() { continue }
3009			let entry = &mut dist[**target_node_counter as usize];
3010			if let Some(hop) = entry {
3011				hop.is_last_hop_target = true;
3012			} else {
3013				*entry = Some(PathBuildingHop {
3014					candidate: candidates[0].clone(),
3015					fee_msat: 0,
3016					next_hops_fee_msat: u64::max_value(),
3017					hop_use_fee_msat: u64::max_value(),
3018					total_fee_msat: u64::max_value(),
3019					path_htlc_minimum_msat: u64::max_value(),
3020					path_penalty_msat: u64::max_value(),
3021					was_processed: false,
3022					is_first_hop_target: false,
3023					is_last_hop_target: true,
3024					value_contribution_msat: 0,
3025					#[cfg(all(not(ldk_bench), any(test, fuzzing)))]
3026					best_path_from_hop_selected: false,
3027				});
3028			}
3029		}
3030		hit_minimum_limit = false;
3031
3032		if let Some(payee) = payee_node_id_opt {
3033			if let Some(entry) = &mut dist[payee_node_counter as usize] {
3034				// If we built a dummy entry above we need to reset the values to represent 0 fee
3035				// from the target "to the target".
3036				entry.next_hops_fee_msat = 0;
3037				entry.hop_use_fee_msat = 0;
3038				entry.total_fee_msat = 0;
3039				entry.path_htlc_minimum_msat = 0;
3040				entry.path_penalty_msat = 0;
3041				entry.value_contribution_msat = path_value_msat;
3042			}
3043			add_entries_to_cheapest_to_target_node!(
3044				payee_node_counter, payee, path_value_msat, 0, 0
3045			);
3046		}
3047
3048		debug_assert_eq!(
3049			payment_params.payee.blinded_route_hints().len(),
3050			introduction_node_id_cache.len(),
3051			"introduction_node_id_cache was built by iterating the blinded_route_hints, so they should be the same len"
3052		);
3053		let mut blind_intros_added = hash_map_with_capacity(payment_params.payee.blinded_route_hints().len());
3054		for (hint_idx, hint) in payment_params.payee.blinded_route_hints().iter().enumerate() {
3055			// Only add the hops in this route to our candidate set if either
3056			// we have a direct channel to the first hop or the first hop is
3057			// in the regular network graph.
3058			let source_node_opt = introduction_node_id_cache[hint_idx];
3059			let (source_node_id, source_node_counter) = if let Some(v) = source_node_opt { v } else { continue };
3060			if our_node_id == *source_node_id { continue }
3061			let candidate = if hint.blinded_hops().len() == 1 {
3062				CandidateRouteHop::OneHopBlinded(
3063					OneHopBlindedPathCandidate { source_node_counter, source_node_id, hint, hint_idx }
3064				)
3065			} else {
3066				CandidateRouteHop::Blinded(BlindedPathCandidate { source_node_counter, source_node_id, hint, hint_idx })
3067			};
3068			if let Some(hop_used_msat) = add_entry!(&candidate,
3069				0, path_value_msat, 0, 0_u64, 0, 0)
3070			{
3071				blind_intros_added.insert(source_node_id, (hop_used_msat, candidate));
3072			} else { continue }
3073		}
3074		// If we added a blinded path from an introduction node to the destination, where the
3075		// introduction node is one of our direct peers, we need to scan our `first_channels`
3076		// to detect this. However, doing so immediately after calling `add_entry`, above, could
3077		// result in incorrect behavior if we, in a later loop iteration, update the fee from the
3078		// same introduction point to the destination (due to a different blinded path with the
3079		// same introduction point having a lower score).
3080		// Thus, we track the nodes that we added paths from in `blind_intros_added` and scan for
3081		// introduction points we have a channel with after processing all blinded paths.
3082		for (source_node_id, (path_contribution_msat, candidate)) in blind_intros_added {
3083			if let Some((first_channels, peer_node_counter)) = first_hop_targets.get_mut(source_node_id) {
3084				sort_first_hop_channels(
3085					first_channels, &used_liquidities, recommended_value_msat, our_node_pubkey
3086				);
3087				for details in first_channels {
3088					let first_hop_candidate = CandidateRouteHop::FirstHop(FirstHopCandidate {
3089						details, payer_node_id: &our_node_id, payer_node_counter,
3090						target_node_counter: *peer_node_counter,
3091					});
3092					let blinded_path_fee = match compute_fees(path_contribution_msat, candidate.fees()) {
3093						Some(fee) => fee,
3094						None => continue
3095					};
3096					let path_min = candidate.htlc_minimum_msat().saturating_add(
3097						compute_fees_saturating(candidate.htlc_minimum_msat(), candidate.fees()));
3098					add_entry!(&first_hop_candidate, blinded_path_fee, path_contribution_msat, path_min,
3099						0_u64, candidate.cltv_expiry_delta(), 0);
3100				}
3101			}
3102		}
3103
3104		log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
3105
3106		// At this point, targets are filled with the data from first and
3107		// last hops communicated by the caller, and the payment receiver.
3108		let mut found_new_path = false;
3109
3110		// Step (3).
3111		// If this loop terminates due the exhaustion of targets, two situations are possible:
3112		// - not enough outgoing liquidity:
3113		//   0 < already_collected_value_msat < final_value_msat
3114		// - enough outgoing liquidity:
3115		//   final_value_msat <= already_collected_value_msat < recommended_value_msat
3116		// Both these cases (and other cases except reaching recommended_value_msat) mean that
3117		// paths_collection will be stopped because found_new_path==false.
3118		// This is not necessarily a routing failure.
3119		'path_construction: while let Some(RouteGraphNode { node_counter, total_cltv_delta, mut value_contribution_msat, path_length_to_node, .. }) = targets.pop() {
3120
3121			// Since we're going payee-to-payer, hitting our node as a target means we should stop
3122			// traversing the graph and arrange the path out of what we found.
3123			if node_counter == payer_node_counter {
3124				let mut new_entry = dist[payer_node_counter as usize].take().unwrap();
3125				let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
3126
3127				'path_walk: loop {
3128					let mut features_set = false;
3129					let candidate = &ordered_hops.last().unwrap().0.candidate;
3130					let target = candidate.target().unwrap_or(maybe_dummy_payee_node_id);
3131					let target_node_counter = candidate.target_node_counter();
3132					if let Some((first_channels, _)) = first_hop_targets.get(&target) {
3133						for details in first_channels {
3134							if let CandidateRouteHop::FirstHop(FirstHopCandidate { details: last_hop_details, .. })
3135								= candidate
3136							{
3137								if details.get_outbound_payment_scid() == last_hop_details.get_outbound_payment_scid() {
3138									ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
3139									features_set = true;
3140									break;
3141								}
3142							}
3143						}
3144					}
3145					if !features_set {
3146						if let Some(node) = network_nodes.get(&target) {
3147							if let Some(node_info) = node.announcement_info.as_ref() {
3148								ordered_hops.last_mut().unwrap().1 = node_info.features().clone();
3149							} else {
3150								ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
3151							}
3152						} else {
3153							// We can fill in features for everything except hops which were
3154							// provided via the invoice we're paying. We could guess based on the
3155							// recipient's features but for now we simply avoid guessing at all.
3156						}
3157					}
3158
3159					// Means we successfully traversed from the payer to the payee, now
3160					// save this path for the payment route. Also, update the liquidity
3161					// remaining on the used hops, so that we take them into account
3162					// while looking for more paths.
3163					if target_node_counter.is_none() {
3164						break 'path_walk;
3165					}
3166					if target_node_counter == Some(payee_node_counter) { break 'path_walk; }
3167
3168					new_entry = match dist[target_node_counter.unwrap() as usize].take() {
3169						Some(payment_hop) => payment_hop,
3170						// We can't arrive at None because, if we ever add an entry to targets,
3171						// we also fill in the entry in dist (see add_entry!).
3172						None => unreachable!(),
3173					};
3174					// We "propagate" the fees one hop backward (topologically) here,
3175					// so that fees paid for a HTLC forwarding on the current channel are
3176					// associated with the previous channel (where they will be subtracted).
3177					ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
3178					ordered_hops.push((new_entry.clone(), default_node_features.clone()));
3179				}
3180				ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
3181				ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
3182
3183				log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
3184					ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
3185
3186				let mut payment_path = PaymentPath {hops: ordered_hops};
3187
3188				// We could have possibly constructed a slightly inconsistent path: since we reduce
3189				// value being transferred along the way, we could have violated htlc_minimum_msat
3190				// on some channels we already passed (assuming dest->source direction). Here, we
3191				// recompute the fees again, so that if that's the case, we match the currently
3192				// underpaid htlc_minimum_msat with fees.
3193				debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
3194				let max_path_contribution_msat = payment_path.compute_max_final_value_contribution(
3195					&used_liquidities, channel_saturation_pow_half
3196				);
3197				let desired_value_contribution = cmp::min(max_path_contribution_msat, final_value_msat);
3198				value_contribution_msat = payment_path.update_value_and_recompute_fees(desired_value_contribution);
3199
3200				// Since a path allows to transfer as much value as
3201				// the smallest channel it has ("bottleneck"), we should recompute
3202				// the fees so sender HTLC don't overpay fees when traversing
3203				// larger channels than the bottleneck. This may happen because
3204				// when we were selecting those channels we were not aware how much value
3205				// this path will transfer, and the relative fee for them
3206				// might have been computed considering a larger value.
3207				// Remember that we used these channels so that we don't rely
3208				// on the same liquidity in future paths.
3209				for (hop, _) in payment_path.hops.iter() {
3210					let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
3211					let used_liquidity_msat = used_liquidities
3212						.entry(hop.candidate.id())
3213						.and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
3214						.or_insert(spent_on_hop_msat);
3215					let hop_capacity = hop.candidate.effective_capacity();
3216					let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
3217					debug_assert!(*used_liquidity_msat <= hop_max_msat);
3218				}
3219				if max_path_contribution_msat > value_contribution_msat {
3220					// If we weren't capped by hitting a liquidity limit on a channel in the path,
3221					// we'll probably end up picking the same path again on the next iteration.
3222					// Decrease the available liquidity of a hop in the middle of the path.
3223					let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
3224					let exhausted = u64::max_value();
3225					log_trace!(logger,
3226						"Disabling route candidate {} for future path building iterations to avoid duplicates.",
3227						LoggedCandidateHop(victim_candidate));
3228					if let Some(scid) = victim_candidate.short_channel_id() {
3229						*used_liquidities.entry(CandidateHopId::Clear((scid, false))).or_default() = exhausted;
3230						*used_liquidities.entry(CandidateHopId::Clear((scid, true))).or_default() = exhausted;
3231					}
3232				}
3233
3234				// Track the total amount all our collected paths allow to send so that we know
3235				// when to stop looking for more paths
3236				already_collected_value_msat += value_contribution_msat;
3237
3238				payment_paths.push(payment_path);
3239				found_new_path = true;
3240				break 'path_construction;
3241			}
3242
3243			// If we found a path back to the payee, we shouldn't try to process it again. This is
3244			// the equivalent of the `elem.was_processed` check in
3245			// add_entries_to_cheapest_to_target_node!() (see comment there for more info).
3246			if node_counter == payee_node_counter { continue 'path_construction; }
3247
3248			let node_id = if let Some(entry) = &dist[node_counter as usize] {
3249				entry.candidate.source()
3250			} else {
3251				debug_assert!(false, "Best nodes in the heap should have entries in dist");
3252				continue 'path_construction;
3253			};
3254
3255			// Otherwise, since the current target node is not us,
3256			// keep "unrolling" the payment graph from payee to payer by
3257			// finding a way to reach the current target from the payer side.
3258			add_entries_to_cheapest_to_target_node!(
3259				node_counter, node_id,
3260				value_contribution_msat,
3261				total_cltv_delta, path_length_to_node
3262			);
3263		}
3264
3265		if !allow_mpp {
3266			if !found_new_path && channel_saturation_pow_half != 0 {
3267				channel_saturation_pow_half = 0;
3268				continue 'paths_collection;
3269			}
3270			// If we don't support MPP, no use trying to gather more value ever.
3271			break 'paths_collection;
3272		}
3273
3274		// Step (4).
3275		// Stop either when the recommended value is reached or if no new path was found in this
3276		// iteration.
3277		// In the latter case, making another path finding attempt won't help,
3278		// because we deterministically terminated the search due to low liquidity.
3279		if !found_new_path && channel_saturation_pow_half != 0 {
3280			channel_saturation_pow_half = 0;
3281		} else if !found_new_path && hit_minimum_limit && already_collected_value_msat < final_value_msat && path_value_msat != recommended_value_msat {
3282			log_trace!(logger, "Failed to collect enough value, but running again to collect extra paths with a potentially higher limit.");
3283			path_value_msat = recommended_value_msat;
3284		} else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
3285			log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
3286				already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
3287			break 'paths_collection;
3288		} else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
3289			// Further, if this was our first walk of the graph, and we weren't limited by an
3290			// htlc_minimum_msat, return immediately because this path should suffice. If we were
3291			// limited by an htlc_minimum_msat value, find another path with a higher value,
3292			// potentially allowing us to pay fees to meet the htlc_minimum on the new path while
3293			// still keeping a lower total fee than this path.
3294			if !hit_minimum_limit {
3295				log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
3296				break 'paths_collection;
3297			}
3298			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.");
3299			path_value_msat = recommended_value_msat;
3300		}
3301	}
3302
3303	let num_ignored_total = num_ignored_value_contribution + num_ignored_path_length_limit +
3304		num_ignored_cltv_delta_limit + num_ignored_previously_failed +
3305		num_ignored_avoid_overpayment + num_ignored_htlc_minimum_msat_limit +
3306		num_ignored_total_fee_limit;
3307	if num_ignored_total > 0 {
3308		log_trace!(logger,
3309			"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.",
3310			num_ignored_value_contribution, num_ignored_path_length_limit,
3311			num_ignored_cltv_delta_limit, num_ignored_previously_failed,
3312			num_ignored_htlc_minimum_msat_limit, num_ignored_avoid_overpayment,
3313			num_ignored_total_fee_limit, num_ignored_total);
3314	}
3315
3316	// Step (5).
3317	if payment_paths.len() == 0 {
3318		return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3319	}
3320
3321	if already_collected_value_msat < final_value_msat {
3322		return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
3323	}
3324
3325	// Step (6).
3326	let mut selected_route = payment_paths;
3327
3328	debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
3329	let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
3330
3331	// First, sort by the cost-per-value of the path, dropping the paths that cost the most for
3332	// the value they contribute towards the payment amount.
3333	// We sort in descending order as we will remove from the front in `retain`, next.
3334	selected_route.sort_unstable_by(|a, b| b.get_cost_per_msat().cmp(&a.get_cost_per_msat()));
3335
3336	// We should make sure that at least 1 path left.
3337	let mut paths_left = selected_route.len();
3338	selected_route.retain(|path| {
3339		if paths_left == 1 {
3340			return true
3341		}
3342		let path_value_msat = path.get_value_msat();
3343		if path_value_msat <= overpaid_value_msat {
3344			overpaid_value_msat -= path_value_msat;
3345			paths_left -= 1;
3346			return false;
3347		}
3348		true
3349	});
3350	debug_assert!(selected_route.len() > 0);
3351
3352	if overpaid_value_msat != 0 {
3353		// Step (7).
3354		// Now, subtract the remaining overpaid value from the most-expensive path.
3355		// TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
3356		// so that the sender pays less fees overall. And also htlc_minimum_msat.
3357		selected_route.sort_unstable_by(|a, b| {
3358			let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3359			let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
3360			a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
3361		});
3362		let expensive_payment_path = selected_route.first_mut().unwrap();
3363
3364		// We already dropped all the paths with value below `overpaid_value_msat` above, thus this
3365		// can't go negative.
3366		let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
3367		expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
3368	}
3369
3370	// Step (8).
3371	// Sort by the path itself and combine redundant paths.
3372	// Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
3373	// compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
3374	// across nodes.
3375	selected_route.sort_unstable_by_key(|path| {
3376		let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
3377		debug_assert!(path.hops.len() <= key.len());
3378		for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id()).zip(key.iter_mut()) {
3379			*key = scid;
3380		}
3381		key
3382	});
3383	for idx in 0..(selected_route.len() - 1) {
3384		if idx + 1 >= selected_route.len() { break; }
3385		if iter_equal(selected_route[idx    ].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target())),
3386		              selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.id(), h.0.candidate.target()))) {
3387			let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
3388			selected_route[idx].update_value_and_recompute_fees(new_value);
3389			selected_route.remove(idx + 1);
3390		}
3391	}
3392
3393	let mut paths = Vec::new();
3394	for payment_path in selected_route {
3395		let mut hops = Vec::with_capacity(payment_path.hops.len());
3396		for (hop, node_features) in payment_path.hops.iter()
3397			.filter(|(h, _)| h.candidate.short_channel_id().is_some())
3398		{
3399			let target = hop.candidate.target().expect("target is defined when short_channel_id is defined");
3400			let maybe_announced_channel = if let CandidateRouteHop::PublicHop(_) = hop.candidate {
3401				// If we sourced the hop from the graph we're sure the target node is announced.
3402				true
3403			} else if let CandidateRouteHop::FirstHop(first_hop) = &hop.candidate {
3404				// If this is a first hop we also know if it's announced.
3405				first_hop.details.is_announced
3406			} else {
3407				// If we sourced it any other way, we double-check the network graph to see if
3408				// there are announced channels between the endpoints. If so, the hop might be
3409				// referring to any of the announced channels, as its `short_channel_id` might be
3410				// an alias, in which case we don't take any chances here.
3411				network_graph.node(&target).map_or(false, |hop_node|
3412					hop_node.channels.iter().any(|scid| network_graph.channel(*scid)
3413							.map_or(false, |c| c.as_directed_from(&hop.candidate.source()).is_some()))
3414				)
3415			};
3416
3417			hops.push(RouteHop {
3418				pubkey: PublicKey::from_slice(target.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &target), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
3419				node_features: node_features.clone(),
3420				short_channel_id: hop.candidate.short_channel_id().unwrap(),
3421				channel_features: hop.candidate.features(),
3422				fee_msat: hop.fee_msat,
3423				cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
3424				maybe_announced_channel,
3425			});
3426		}
3427		let mut final_cltv_delta = final_cltv_expiry_delta;
3428		let blinded_tail = payment_path.hops.last().and_then(|(h, _)| {
3429			if let Some(blinded_path) = h.candidate.blinded_path() {
3430				final_cltv_delta = h.candidate.cltv_expiry_delta();
3431				Some(BlindedTail {
3432					hops: blinded_path.blinded_hops().to_vec(),
3433					blinding_point: blinded_path.blinding_point(),
3434					excess_final_cltv_expiry_delta: 0,
3435					final_value_msat: h.fee_msat,
3436				})
3437			} else { None }
3438		});
3439		// Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
3440		// applicable for the previous hop.
3441		hops.iter_mut().rev().fold(final_cltv_delta, |prev_cltv_expiry_delta, hop| {
3442			core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
3443		});
3444
3445		paths.push(Path { hops, blinded_tail });
3446	}
3447	// Make sure we would never create a route with more paths than we allow.
3448	debug_assert!(paths.len() <= payment_params.max_path_count.into());
3449
3450	if let Some(node_features) = payment_params.payee.node_features() {
3451		for path in paths.iter_mut() {
3452			path.hops.last_mut().unwrap().node_features = node_features.clone();
3453		}
3454	}
3455
3456	let route = Route { paths, route_params: Some(route_params.clone()) };
3457
3458	// Make sure we would never create a route whose total fees exceed max_total_routing_fee_msat.
3459	if let Some(max_total_routing_fee_msat) = route_params.max_total_routing_fee_msat {
3460		if route.get_total_fees() > max_total_routing_fee_msat {
3461			return Err(LightningError{err: format!("Failed to find route that adheres to the maximum total fee limit of {}msat",
3462				max_total_routing_fee_msat), action: ErrorAction::IgnoreError});
3463		}
3464	}
3465
3466	log_info!(logger, "Got route: {}", log_route!(route));
3467	Ok(route)
3468}
3469
3470// When an adversarial intermediary node observes a payment, it may be able to infer its
3471// destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
3472// graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
3473// payment path by adding a randomized 'shadow route' offset to the final hop.
3474fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
3475	network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
3476) {
3477	let network_channels = network_graph.channels();
3478	let network_nodes = network_graph.nodes();
3479
3480	for path in route.paths.iter_mut() {
3481		let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
3482
3483		// Remember the last three nodes of the random walk and avoid looping back on them.
3484		// Init with the last three nodes from the actual path, if possible.
3485		let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
3486			NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
3487			NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
3488
3489		// Choose the last publicly known node as the starting point for the random walk.
3490		let mut cur_hop: Option<NodeId> = None;
3491		let mut path_nonce = [0u8; 12];
3492		if let Some(starting_hop) = path.hops.iter().rev()
3493			.find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
3494				cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
3495				path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
3496		}
3497
3498		// Init PRNG with the path-dependant nonce, which is static for private paths.
3499		let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
3500		let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
3501
3502		// Pick a random path length in [1 .. 3]
3503		prng.process_in_place(&mut random_path_bytes);
3504		let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
3505
3506		for random_hop in 0..random_walk_length {
3507			// If we don't find a suitable offset in the public network graph, we default to
3508			// MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3509			let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
3510
3511			if let Some(cur_node_id) = cur_hop {
3512				if let Some(cur_node) = network_nodes.get(&cur_node_id) {
3513					// Randomly choose the next unvisited hop.
3514					prng.process_in_place(&mut random_path_bytes);
3515					if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
3516						.checked_rem(cur_node.channels.len())
3517						.and_then(|index| cur_node.channels.get(index))
3518						.and_then(|id| network_channels.get(id)) {
3519							random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
3520								if !nodes_to_avoid.iter().any(|x| x == next_id) {
3521									nodes_to_avoid[random_hop] = *next_id;
3522									random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
3523									cur_hop = Some(*next_id);
3524								}
3525							});
3526						}
3527				}
3528			}
3529
3530			shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
3531				.checked_add(random_hop_offset)
3532				.unwrap_or(shadow_ctlv_expiry_delta_offset);
3533		}
3534
3535		// Limit the total offset to reduce the worst-case locked liquidity timevalue
3536		const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
3537		shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
3538
3539		// Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
3540		// we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
3541		let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
3542		let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
3543		max_path_offset = cmp::max(
3544			max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
3545			max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
3546		shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
3547
3548		// Add 'shadow' CLTV offset to the final hop
3549		if let Some(tail) = path.blinded_tail.as_mut() {
3550			tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
3551				.checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
3552		}
3553		if let Some(last_hop) = path.hops.last_mut() {
3554			last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
3555				.checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
3556		}
3557	}
3558}
3559
3560/// Construct a route from us (payer) to the target node (payee) via the given hops (which should
3561/// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
3562///
3563/// Re-uses logic from `find_route`, so the restrictions described there also apply here.
3564pub fn build_route_from_hops<L: Deref, GL: Deref>(
3565	our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3566	network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
3567) -> Result<Route, LightningError>
3568where L::Target: Logger, GL::Target: Logger {
3569	let graph_lock = network_graph.read_only();
3570	let mut route = build_route_from_hops_internal(our_node_pubkey, hops, &route_params,
3571		&graph_lock, logger, random_seed_bytes)?;
3572	add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
3573	Ok(route)
3574}
3575
3576fn build_route_from_hops_internal<L: Deref>(
3577	our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
3578	network_graph: &ReadOnlyNetworkGraph, logger: L, random_seed_bytes: &[u8; 32],
3579) -> Result<Route, LightningError> where L::Target: Logger {
3580
3581	struct HopScorer {
3582		our_node_id: NodeId,
3583		hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
3584	}
3585
3586	impl ScoreLookUp for HopScorer {
3587		type ScoreParams = ();
3588		fn channel_penalty_msat(&self, candidate: &CandidateRouteHop,
3589			_usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
3590		{
3591			let mut cur_id = self.our_node_id;
3592			for i in 0..self.hop_ids.len() {
3593				if let Some(next_id) = self.hop_ids[i] {
3594					if cur_id == candidate.source() && Some(next_id) == candidate.target() {
3595						return 0;
3596					}
3597					cur_id = next_id;
3598				} else {
3599					break;
3600				}
3601			}
3602			u64::max_value()
3603		}
3604	}
3605
3606	impl<'a> Writeable for HopScorer {
3607		#[inline]
3608		fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
3609			unreachable!();
3610		}
3611	}
3612
3613	if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
3614		return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
3615	}
3616
3617	let our_node_id = NodeId::from_pubkey(our_node_pubkey);
3618	let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
3619	for i in 0..hops.len() {
3620		hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
3621	}
3622
3623	let scorer = HopScorer { our_node_id, hop_ids };
3624
3625	get_route(our_node_pubkey, route_params, network_graph, None, logger, &scorer, &Default::default(), random_seed_bytes)
3626}
3627
3628#[cfg(test)]
3629mod tests {
3630	use crate::blinded_path::BlindedHop;
3631	use crate::blinded_path::payment::{BlindedPayInfo, BlindedPaymentPath};
3632	use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
3633	use crate::routing::utxo::UtxoResult;
3634	use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
3635		BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
3636		DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE, RouteParameters, CandidateRouteHop, PublicHopCandidate};
3637	use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, ScoreLookUp, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
3638	use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
3639	use crate::chain::transaction::OutPoint;
3640	use crate::ln::channel_state::{ChannelCounterparty, ChannelDetails, ChannelShutdownState};
3641	use crate::ln::types::ChannelId;
3642	use crate::types::features::{BlindedHopFeatures, ChannelFeatures, InitFeatures, NodeFeatures};
3643	use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
3644	use crate::ln::channelmanager;
3645	use crate::util::config::UserConfig;
3646	use crate::util::test_utils as ln_test_utils;
3647	use crate::crypto::chacha20::ChaCha20;
3648	use crate::util::ser::{FixedLengthReader, Readable, ReadableArgs, Writeable};
3649	#[cfg(c_bindings)]
3650	use crate::util::ser::Writer;
3651
3652	use bitcoin::amount::Amount;
3653	use bitcoin::hashes::Hash;
3654	use bitcoin::network::Network;
3655	use bitcoin::constants::ChainHash;
3656	use bitcoin::script::Builder;
3657	use bitcoin::opcodes;
3658	use bitcoin::transaction::TxOut;
3659	use bitcoin::hex::FromHex;
3660	use bitcoin::secp256k1::{PublicKey,SecretKey};
3661	use bitcoin::secp256k1::Secp256k1;
3662
3663	use crate::io::Cursor;
3664	use crate::prelude::*;
3665	use crate::sync::Arc;
3666
3667	fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
3668			features: InitFeatures, outbound_capacity_msat: u64) -> ChannelDetails {
3669		#[allow(deprecated)] // TODO: Remove once balance_msat is removed.
3670		ChannelDetails {
3671			channel_id: ChannelId::new_zero(),
3672			counterparty: ChannelCounterparty {
3673				features,
3674				node_id,
3675				unspendable_punishment_reserve: 0,
3676				forwarding_info: None,
3677				outbound_htlc_minimum_msat: None,
3678				outbound_htlc_maximum_msat: None,
3679			},
3680			funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
3681			channel_type: None,
3682			short_channel_id,
3683			outbound_scid_alias: None,
3684			inbound_scid_alias: None,
3685			channel_value_satoshis: 0,
3686			user_channel_id: 0,
3687			outbound_capacity_msat,
3688			next_outbound_htlc_limit_msat: outbound_capacity_msat,
3689			next_outbound_htlc_minimum_msat: 0,
3690			inbound_capacity_msat: 42,
3691			unspendable_punishment_reserve: None,
3692			confirmations_required: None,
3693			confirmations: None,
3694			force_close_spend_delay: None,
3695			is_outbound: true, is_channel_ready: true,
3696			is_usable: true, is_announced: true,
3697			inbound_htlc_minimum_msat: None,
3698			inbound_htlc_maximum_msat: None,
3699			config: None,
3700			feerate_sat_per_1000_weight: None,
3701			channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
3702			pending_inbound_htlcs: Vec::new(),
3703			pending_outbound_htlcs: Vec::new(),
3704		}
3705	}
3706
3707	fn dummy_blinded_path(intro_node: PublicKey, payinfo: BlindedPayInfo) -> BlindedPaymentPath {
3708		BlindedPaymentPath::from_raw(
3709			intro_node, ln_test_utils::pubkey(42),
3710			vec![
3711				BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
3712				BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
3713			],
3714			payinfo
3715		)
3716	}
3717
3718	fn dummy_one_hop_blinded_path(intro_node: PublicKey, payinfo: BlindedPayInfo) -> BlindedPaymentPath {
3719		BlindedPaymentPath::from_raw(
3720			intro_node, ln_test_utils::pubkey(42),
3721			vec![
3722				BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
3723			],
3724			payinfo
3725		)
3726	}
3727
3728	#[test]
3729	fn simple_route_test() {
3730		let (secp_ctx, network_graph, _, _, logger) = build_graph();
3731		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3732		let mut payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3733		let scorer = ln_test_utils::TestScorer::new();
3734		let random_seed_bytes = [42; 32];
3735
3736		// Simple route to 2 via 1
3737
3738		let route_params = RouteParameters::from_payment_params_and_value(
3739			payment_params.clone(), 0);
3740		if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3741			&route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3742			&Default::default(), &random_seed_bytes) {
3743				assert_eq!(err, "Cannot send a payment of 0 msat");
3744		} else { panic!(); }
3745
3746		payment_params.max_path_length = 2;
3747		let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3748		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3749			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3750		assert_eq!(route.paths[0].hops.len(), 2);
3751
3752		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3753		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3754		assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3755		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3756		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3757		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3758
3759		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3760		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3761		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3762		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3763		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3764		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3765
3766		route_params.payment_params.max_path_length = 1;
3767		get_route(&our_id, &route_params, &network_graph.read_only(), None,
3768			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
3769	}
3770
3771	#[test]
3772	fn invalid_first_hop_test() {
3773		let (secp_ctx, network_graph, _, _, logger) = build_graph();
3774		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3775		let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3776		let scorer = ln_test_utils::TestScorer::new();
3777		let random_seed_bytes = [42; 32];
3778
3779		// Simple route to 2 via 1
3780
3781		let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
3782
3783		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
3784		if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3785			&route_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()),
3786			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
3787				assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
3788		} else { panic!(); }
3789
3790		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3791			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3792		assert_eq!(route.paths[0].hops.len(), 2);
3793	}
3794
3795	#[test]
3796	fn htlc_minimum_test() {
3797		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3798		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3799		let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3800		let scorer = ln_test_utils::TestScorer::new();
3801		let random_seed_bytes = [42; 32];
3802
3803		// Simple route to 2 via 1
3804
3805		// Disable other paths
3806		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3807			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3808			short_channel_id: 12,
3809			timestamp: 2,
3810			message_flags: 1, // Only must_be_one
3811			channel_flags: 2, // to disable
3812			cltv_expiry_delta: 0,
3813			htlc_minimum_msat: 0,
3814			htlc_maximum_msat: MAX_VALUE_MSAT,
3815			fee_base_msat: 0,
3816			fee_proportional_millionths: 0,
3817			excess_data: Vec::new()
3818		});
3819		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3820			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3821			short_channel_id: 3,
3822			timestamp: 2,
3823			message_flags: 1, // Only must_be_one
3824			channel_flags: 2, // to disable
3825			cltv_expiry_delta: 0,
3826			htlc_minimum_msat: 0,
3827			htlc_maximum_msat: MAX_VALUE_MSAT,
3828			fee_base_msat: 0,
3829			fee_proportional_millionths: 0,
3830			excess_data: Vec::new()
3831		});
3832		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3833			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3834			short_channel_id: 13,
3835			timestamp: 2,
3836			message_flags: 1, // Only must_be_one
3837			channel_flags: 2, // to disable
3838			cltv_expiry_delta: 0,
3839			htlc_minimum_msat: 0,
3840			htlc_maximum_msat: MAX_VALUE_MSAT,
3841			fee_base_msat: 0,
3842			fee_proportional_millionths: 0,
3843			excess_data: Vec::new()
3844		});
3845		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3846			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3847			short_channel_id: 6,
3848			timestamp: 2,
3849			message_flags: 1, // Only must_be_one
3850			channel_flags: 2, // to disable
3851			cltv_expiry_delta: 0,
3852			htlc_minimum_msat: 0,
3853			htlc_maximum_msat: MAX_VALUE_MSAT,
3854			fee_base_msat: 0,
3855			fee_proportional_millionths: 0,
3856			excess_data: Vec::new()
3857		});
3858		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3859			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3860			short_channel_id: 7,
3861			timestamp: 2,
3862			message_flags: 1, // Only must_be_one
3863			channel_flags: 2, // to disable
3864			cltv_expiry_delta: 0,
3865			htlc_minimum_msat: 0,
3866			htlc_maximum_msat: MAX_VALUE_MSAT,
3867			fee_base_msat: 0,
3868			fee_proportional_millionths: 0,
3869			excess_data: Vec::new()
3870		});
3871
3872		// Check against amount_to_transfer_over_msat.
3873		// Set minimal HTLC of 200_000_000 msat.
3874		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3875			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3876			short_channel_id: 2,
3877			timestamp: 3,
3878			message_flags: 1, // Only must_be_one
3879			channel_flags: 0,
3880			cltv_expiry_delta: 0,
3881			htlc_minimum_msat: 200_000_000,
3882			htlc_maximum_msat: MAX_VALUE_MSAT,
3883			fee_base_msat: 0,
3884			fee_proportional_millionths: 0,
3885			excess_data: Vec::new()
3886		});
3887
3888		// Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
3889		// be used.
3890		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3891			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3892			short_channel_id: 4,
3893			timestamp: 3,
3894			message_flags: 1, // Only must_be_one
3895			channel_flags: 0,
3896			cltv_expiry_delta: 0,
3897			htlc_minimum_msat: 0,
3898			htlc_maximum_msat: 199_999_999,
3899			fee_base_msat: 0,
3900			fee_proportional_millionths: 0,
3901			excess_data: Vec::new()
3902		});
3903
3904		// Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
3905		let route_params = RouteParameters::from_payment_params_and_value(
3906			payment_params, 199_999_999);
3907		if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
3908			&route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
3909			&Default::default(), &random_seed_bytes) {
3910				assert_eq!(err, "Failed to find a path to the given destination");
3911		} else { panic!(); }
3912
3913		// Lift the restriction on the first hop.
3914		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3915			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3916			short_channel_id: 2,
3917			timestamp: 4,
3918			message_flags: 1, // Only must_be_one
3919			channel_flags: 0,
3920			cltv_expiry_delta: 0,
3921			htlc_minimum_msat: 0,
3922			htlc_maximum_msat: MAX_VALUE_MSAT,
3923			fee_base_msat: 0,
3924			fee_proportional_millionths: 0,
3925			excess_data: Vec::new()
3926		});
3927
3928		// A payment above the minimum should pass
3929		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
3930			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
3931		assert_eq!(route.paths[0].hops.len(), 2);
3932	}
3933
3934	#[test]
3935	fn htlc_minimum_overpay_test() {
3936		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3937		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3938		let config = UserConfig::default();
3939		let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
3940			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
3941			.unwrap();
3942		let scorer = ln_test_utils::TestScorer::new();
3943		let random_seed_bytes = [42; 32];
3944
3945		// A route to node#2 via two paths.
3946		// One path allows transferring 35-40 sats, another one also allows 35-40 sats.
3947		// Thus, they can't send 60 without overpaying.
3948		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3949			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3950			short_channel_id: 2,
3951			timestamp: 2,
3952			message_flags: 1, // Only must_be_one
3953			channel_flags: 0,
3954			cltv_expiry_delta: 0,
3955			htlc_minimum_msat: 35_000,
3956			htlc_maximum_msat: 40_000,
3957			fee_base_msat: 0,
3958			fee_proportional_millionths: 0,
3959			excess_data: Vec::new()
3960		});
3961		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3962			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3963			short_channel_id: 12,
3964			timestamp: 3,
3965			message_flags: 1, // Only must_be_one
3966			channel_flags: 0,
3967			cltv_expiry_delta: 0,
3968			htlc_minimum_msat: 35_000,
3969			htlc_maximum_msat: 40_000,
3970			fee_base_msat: 0,
3971			fee_proportional_millionths: 0,
3972			excess_data: Vec::new()
3973		});
3974
3975		// Make 0 fee.
3976		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3977			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3978			short_channel_id: 13,
3979			timestamp: 2,
3980			message_flags: 1, // Only must_be_one
3981			channel_flags: 0,
3982			cltv_expiry_delta: 0,
3983			htlc_minimum_msat: 0,
3984			htlc_maximum_msat: MAX_VALUE_MSAT,
3985			fee_base_msat: 0,
3986			fee_proportional_millionths: 0,
3987			excess_data: Vec::new()
3988		});
3989		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3990			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
3991			short_channel_id: 4,
3992			timestamp: 2,
3993			message_flags: 1, // Only must_be_one
3994			channel_flags: 0,
3995			cltv_expiry_delta: 0,
3996			htlc_minimum_msat: 0,
3997			htlc_maximum_msat: MAX_VALUE_MSAT,
3998			fee_base_msat: 0,
3999			fee_proportional_millionths: 0,
4000			excess_data: Vec::new()
4001		});
4002
4003		// Disable other paths
4004		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4005			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4006			short_channel_id: 1,
4007			timestamp: 3,
4008			message_flags: 1, // Only must_be_one
4009			channel_flags: 2, // to disable
4010			cltv_expiry_delta: 0,
4011			htlc_minimum_msat: 0,
4012			htlc_maximum_msat: MAX_VALUE_MSAT,
4013			fee_base_msat: 0,
4014			fee_proportional_millionths: 0,
4015			excess_data: Vec::new()
4016		});
4017
4018		let mut route_params = RouteParameters::from_payment_params_and_value(
4019			payment_params.clone(), 60_000);
4020		route_params.max_total_routing_fee_msat = Some(15_000);
4021		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4022			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4023		// Overpay fees to hit htlc_minimum_msat.
4024		let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
4025		// TODO: this could be better balanced to overpay 10k and not 15k.
4026		assert_eq!(overpaid_fees, 15_000);
4027
4028		// Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
4029		// while taking even more fee to match htlc_minimum_msat.
4030		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4031			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4032			short_channel_id: 12,
4033			timestamp: 4,
4034			message_flags: 1, // Only must_be_one
4035			channel_flags: 0,
4036			cltv_expiry_delta: 0,
4037			htlc_minimum_msat: 65_000,
4038			htlc_maximum_msat: 80_000,
4039			fee_base_msat: 0,
4040			fee_proportional_millionths: 0,
4041			excess_data: Vec::new()
4042		});
4043		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4044			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4045			short_channel_id: 2,
4046			timestamp: 3,
4047			message_flags: 1, // Only must_be_one
4048			channel_flags: 0,
4049			cltv_expiry_delta: 0,
4050			htlc_minimum_msat: 0,
4051			htlc_maximum_msat: MAX_VALUE_MSAT,
4052			fee_base_msat: 0,
4053			fee_proportional_millionths: 0,
4054			excess_data: Vec::new()
4055		});
4056		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4057			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4058			short_channel_id: 4,
4059			timestamp: 4,
4060			message_flags: 1, // Only must_be_one
4061			channel_flags: 0,
4062			cltv_expiry_delta: 0,
4063			htlc_minimum_msat: 0,
4064			htlc_maximum_msat: MAX_VALUE_MSAT,
4065			fee_base_msat: 0,
4066			fee_proportional_millionths: 100_000,
4067			excess_data: Vec::new()
4068		});
4069
4070		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4071			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4072		// Fine to overpay for htlc_minimum_msat if it allows us to save fee.
4073		assert_eq!(route.paths.len(), 1);
4074		assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
4075		let fees = route.paths[0].hops[0].fee_msat;
4076		assert_eq!(fees, 5_000);
4077
4078		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 50_000);
4079		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4080			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4081		// Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
4082		// the other channel.
4083		assert_eq!(route.paths.len(), 1);
4084		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4085		let fees = route.paths[0].hops[0].fee_msat;
4086		assert_eq!(fees, 5_000);
4087	}
4088
4089	#[test]
4090	fn htlc_minimum_recipient_overpay_test() {
4091		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4092		let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4093		let config = UserConfig::default();
4094		let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
4095		let scorer = ln_test_utils::TestScorer::new();
4096		let random_seed_bytes = [42; 32];
4097
4098		// Route to node2 over a single path which requires overpaying the recipient themselves.
4099
4100		// First disable all paths except the us -> node1 -> node2 path
4101		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4102			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4103			short_channel_id: 13,
4104			timestamp: 2,
4105			message_flags: 1, // Only must_be_one
4106			channel_flags: 3,
4107			cltv_expiry_delta: 0,
4108			htlc_minimum_msat: 0,
4109			htlc_maximum_msat: 0,
4110			fee_base_msat: 0,
4111			fee_proportional_millionths: 0,
4112			excess_data: Vec::new()
4113		});
4114
4115		// Set channel 4 to free but with a high htlc_minimum_msat
4116		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4117			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4118			short_channel_id: 4,
4119			timestamp: 2,
4120			message_flags: 1, // Only must_be_one
4121			channel_flags: 0,
4122			cltv_expiry_delta: 0,
4123			htlc_minimum_msat: 15_000,
4124			htlc_maximum_msat: MAX_VALUE_MSAT,
4125			fee_base_msat: 0,
4126			fee_proportional_millionths: 0,
4127			excess_data: Vec::new()
4128		});
4129
4130		// Now check that we'll fail to find a path if we fail to find a path if the htlc_minimum
4131		// is overrun. Note that the fees are actually calculated on 3*payment amount as that's
4132		// what we try to find a route for, so this test only just happens to work out to exactly
4133		// the fee limit.
4134		let mut route_params = RouteParameters::from_payment_params_and_value(
4135			payment_params.clone(), 5_000);
4136		route_params.max_total_routing_fee_msat = Some(9_999);
4137		if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4138			&route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4139			&Default::default(), &random_seed_bytes) {
4140				assert_eq!(err, "Failed to find route that adheres to the maximum total fee limit of 9999msat");
4141		} else { panic!(); }
4142
4143		let mut route_params = RouteParameters::from_payment_params_and_value(
4144			payment_params.clone(), 5_000);
4145		route_params.max_total_routing_fee_msat = Some(10_000);
4146		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4147			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4148		assert_eq!(route.get_total_fees(), 10_000);
4149	}
4150
4151	#[test]
4152	fn disable_channels_test() {
4153		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4154		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4155		let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4156		let scorer = ln_test_utils::TestScorer::new();
4157		let random_seed_bytes = [42; 32];
4158
4159		// // Disable channels 4 and 12 by flags=2
4160		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4161			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4162			short_channel_id: 4,
4163			timestamp: 2,
4164			message_flags: 1, // Only must_be_one
4165			channel_flags: 2, // to disable
4166			cltv_expiry_delta: 0,
4167			htlc_minimum_msat: 0,
4168			htlc_maximum_msat: MAX_VALUE_MSAT,
4169			fee_base_msat: 0,
4170			fee_proportional_millionths: 0,
4171			excess_data: Vec::new()
4172		});
4173		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4174			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4175			short_channel_id: 12,
4176			timestamp: 2,
4177			message_flags: 1, // Only must_be_one
4178			channel_flags: 2, // to disable
4179			cltv_expiry_delta: 0,
4180			htlc_minimum_msat: 0,
4181			htlc_maximum_msat: MAX_VALUE_MSAT,
4182			fee_base_msat: 0,
4183			fee_proportional_millionths: 0,
4184			excess_data: Vec::new()
4185		});
4186
4187		// If all the channels require some features we don't understand, route should fail
4188		let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4189		if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4190			&route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4191			&Default::default(), &random_seed_bytes) {
4192				assert_eq!(err, "Failed to find a path to the given destination");
4193		} else { panic!(); }
4194
4195		// If we specify a channel to node7, that overrides our local channel view and that gets used
4196		let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
4197			InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4198		route_params.payment_params.max_path_length = 2;
4199		let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4200			Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4201			&Default::default(), &random_seed_bytes).unwrap();
4202		assert_eq!(route.paths[0].hops.len(), 2);
4203
4204		assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
4205		assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4206		assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4207		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
4208		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
4209		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4210
4211		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4212		assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4213		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4214		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4215		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4216		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4217	}
4218
4219	#[test]
4220	fn disable_node_test() {
4221		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4222		let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4223		let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4224		let scorer = ln_test_utils::TestScorer::new();
4225		let random_seed_bytes = [42; 32];
4226
4227		// Disable nodes 1, 2, and 8 by requiring unknown feature bits
4228		let mut unknown_features = NodeFeatures::empty();
4229		unknown_features.set_unknown_feature_required();
4230		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
4231		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
4232		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
4233
4234		// If all nodes require some features we don't understand, route should fail
4235		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4236		if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4237			&route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4238			&Default::default(), &random_seed_bytes) {
4239				assert_eq!(err, "Failed to find a path to the given destination");
4240		} else { panic!(); }
4241
4242		// If we specify a channel to node7, that overrides our local channel view and that gets used
4243		let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
4244			InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4245		let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4246			Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4247			&Default::default(), &random_seed_bytes).unwrap();
4248		assert_eq!(route.paths[0].hops.len(), 2);
4249
4250		assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
4251		assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4252		assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4253		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
4254		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
4255		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4256
4257		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4258		assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4259		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4260		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4261		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4262		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4263
4264		// Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
4265		// naively) assume that the user checked the feature bits on the invoice, which override
4266		// the node_announcement.
4267	}
4268
4269	#[test]
4270	fn our_chans_test() {
4271		let (secp_ctx, network_graph, _, _, logger) = build_graph();
4272		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4273		let scorer = ln_test_utils::TestScorer::new();
4274		let random_seed_bytes = [42; 32];
4275
4276		// Route to 1 via 2 and 3 because our channel to 1 is disabled
4277		let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
4278		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4279		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4280			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4281		assert_eq!(route.paths[0].hops.len(), 3);
4282
4283		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4284		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4285		assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4286		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4287		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4288		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4289
4290		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4291		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4292		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4293		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
4294		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4295		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4296
4297		assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
4298		assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
4299		assert_eq!(route.paths[0].hops[2].fee_msat, 100);
4300		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
4301		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
4302		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
4303
4304		// If we specify a channel to node7, that overrides our local channel view and that gets used
4305		let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4306		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4307		let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(),
4308			InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4309		let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4310			Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4311			&Default::default(), &random_seed_bytes).unwrap();
4312		assert_eq!(route.paths[0].hops.len(), 2);
4313
4314		assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
4315		assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4316		assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4317		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
4318		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4319		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4320
4321		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4322		assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
4323		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4324		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4325		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4326		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
4327	}
4328
4329	fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4330		let zero_fees = RoutingFees {
4331			base_msat: 0,
4332			proportional_millionths: 0,
4333		};
4334		vec![RouteHint(vec![RouteHintHop {
4335			src_node_id: nodes[3],
4336			short_channel_id: 8,
4337			fees: zero_fees,
4338			cltv_expiry_delta: (8 << 4) | 1,
4339			htlc_minimum_msat: None,
4340			htlc_maximum_msat: None,
4341		}
4342		]), RouteHint(vec![RouteHintHop {
4343			src_node_id: nodes[4],
4344			short_channel_id: 9,
4345			fees: RoutingFees {
4346				base_msat: 1001,
4347				proportional_millionths: 0,
4348			},
4349			cltv_expiry_delta: (9 << 4) | 1,
4350			htlc_minimum_msat: None,
4351			htlc_maximum_msat: None,
4352		}]), RouteHint(vec![RouteHintHop {
4353			src_node_id: nodes[5],
4354			short_channel_id: 10,
4355			fees: zero_fees,
4356			cltv_expiry_delta: (10 << 4) | 1,
4357			htlc_minimum_msat: None,
4358			htlc_maximum_msat: None,
4359		}])]
4360	}
4361
4362	fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4363		let zero_fees = RoutingFees {
4364			base_msat: 0,
4365			proportional_millionths: 0,
4366		};
4367		vec![RouteHint(vec![RouteHintHop {
4368			src_node_id: nodes[2],
4369			short_channel_id: 5,
4370			fees: RoutingFees {
4371				base_msat: 100,
4372				proportional_millionths: 0,
4373			},
4374			cltv_expiry_delta: (5 << 4) | 1,
4375			htlc_minimum_msat: None,
4376			htlc_maximum_msat: None,
4377		}, RouteHintHop {
4378			src_node_id: nodes[3],
4379			short_channel_id: 8,
4380			fees: zero_fees,
4381			cltv_expiry_delta: (8 << 4) | 1,
4382			htlc_minimum_msat: None,
4383			htlc_maximum_msat: None,
4384		}
4385		]), RouteHint(vec![RouteHintHop {
4386			src_node_id: nodes[4],
4387			short_channel_id: 9,
4388			fees: RoutingFees {
4389				base_msat: 1001,
4390				proportional_millionths: 0,
4391			},
4392			cltv_expiry_delta: (9 << 4) | 1,
4393			htlc_minimum_msat: None,
4394			htlc_maximum_msat: None,
4395		}]), RouteHint(vec![RouteHintHop {
4396			src_node_id: nodes[5],
4397			short_channel_id: 10,
4398			fees: zero_fees,
4399			cltv_expiry_delta: (10 << 4) | 1,
4400			htlc_minimum_msat: None,
4401			htlc_maximum_msat: None,
4402		}])]
4403	}
4404
4405	#[test]
4406	fn partial_route_hint_test() {
4407		let (secp_ctx, network_graph, _, _, logger) = build_graph();
4408		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4409		let scorer = ln_test_utils::TestScorer::new();
4410		let random_seed_bytes = [42; 32];
4411
4412		// Simple test across 2, 3, 5, and 4 via a last_hop channel
4413		// Tests the behaviour when the RouteHint contains a suboptimal hop.
4414		// RouteHint may be partially used by the algo to build the best path.
4415
4416		// First check that last hop can't have its source as the payee.
4417		let invalid_last_hop = RouteHint(vec![RouteHintHop {
4418			src_node_id: nodes[6],
4419			short_channel_id: 8,
4420			fees: RoutingFees {
4421				base_msat: 1000,
4422				proportional_millionths: 0,
4423			},
4424			cltv_expiry_delta: (8 << 4) | 1,
4425			htlc_minimum_msat: None,
4426			htlc_maximum_msat: None,
4427		}]);
4428
4429		let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
4430		invalid_last_hops.push(invalid_last_hop);
4431		{
4432			let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4433				.with_route_hints(invalid_last_hops).unwrap();
4434			let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4435			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
4436				&route_params, &network_graph.read_only(), None, Arc::clone(&logger), &scorer,
4437				&Default::default(), &random_seed_bytes) {
4438					assert_eq!(err, "Route hint cannot have the payee as the source.");
4439			} else { panic!(); }
4440		}
4441
4442		let mut payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4443			.with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
4444		payment_params.max_path_length = 5;
4445		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4446		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4447			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4448		assert_eq!(route.paths[0].hops.len(), 5);
4449
4450		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4451		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4452		assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4453		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4454		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4455		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4456
4457		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4458		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4459		assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4460		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4461		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4462		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4463
4464		assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4465		assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4466		assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4467		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4468		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4469		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4470
4471		assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4472		assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4473		assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4474		assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4475		// If we have a peer in the node map, we'll use their features here since we don't have
4476		// a way of figuring out their features from the invoice:
4477		assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4478		assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4479
4480		assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4481		assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4482		assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4483		assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4484		assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4485		assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4486	}
4487
4488	fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4489		let zero_fees = RoutingFees {
4490			base_msat: 0,
4491			proportional_millionths: 0,
4492		};
4493		vec![RouteHint(vec![RouteHintHop {
4494			src_node_id: nodes[3],
4495			short_channel_id: 8,
4496			fees: zero_fees,
4497			cltv_expiry_delta: (8 << 4) | 1,
4498			htlc_minimum_msat: None,
4499			htlc_maximum_msat: None,
4500		}]), RouteHint(vec![
4501
4502		]), RouteHint(vec![RouteHintHop {
4503			src_node_id: nodes[5],
4504			short_channel_id: 10,
4505			fees: zero_fees,
4506			cltv_expiry_delta: (10 << 4) | 1,
4507			htlc_minimum_msat: None,
4508			htlc_maximum_msat: None,
4509		}])]
4510	}
4511
4512	#[test]
4513	fn ignores_empty_last_hops_test() {
4514		let (secp_ctx, network_graph, _, _, logger) = build_graph();
4515		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4516		let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
4517		let scorer = ln_test_utils::TestScorer::new();
4518		let random_seed_bytes = [42; 32];
4519
4520		// Test handling of an empty RouteHint passed in Invoice.
4521		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4522		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4523			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4524		assert_eq!(route.paths[0].hops.len(), 5);
4525
4526		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4527		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4528		assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4529		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4530		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4531		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4532
4533		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4534		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4535		assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4536		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4537		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4538		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4539
4540		assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4541		assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4542		assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4543		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4544		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4545		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4546
4547		assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4548		assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4549		assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4550		assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4551		// If we have a peer in the node map, we'll use their features here since we don't have
4552		// a way of figuring out their features from the invoice:
4553		assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4554		assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4555
4556		assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4557		assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4558		assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4559		assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4560		assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4561		assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4562	}
4563
4564	/// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
4565	/// and 0xff01.
4566	fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
4567		let zero_fees = RoutingFees {
4568			base_msat: 0,
4569			proportional_millionths: 0,
4570		};
4571		vec![RouteHint(vec![RouteHintHop {
4572			src_node_id: hint_hops[0],
4573			short_channel_id: 0xff00,
4574			fees: RoutingFees {
4575				base_msat: 100,
4576				proportional_millionths: 0,
4577			},
4578			cltv_expiry_delta: (5 << 4) | 1,
4579			htlc_minimum_msat: None,
4580			htlc_maximum_msat: None,
4581		}, RouteHintHop {
4582			src_node_id: hint_hops[1],
4583			short_channel_id: 0xff01,
4584			fees: zero_fees,
4585			cltv_expiry_delta: (8 << 4) | 1,
4586			htlc_minimum_msat: None,
4587			htlc_maximum_msat: None,
4588		}])]
4589	}
4590
4591	#[test]
4592	fn multi_hint_last_hops_test() {
4593		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4594		let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4595		let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
4596		let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4597		let scorer = ln_test_utils::TestScorer::new();
4598		let random_seed_bytes = [42; 32];
4599
4600		// Test through channels 2, 3, 0xff00, 0xff01.
4601		// Test shows that multi-hop route hints are considered and factored correctly into the
4602		// max path length.
4603
4604		// Disabling channels 6 & 7 by flags=2
4605		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4606			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4607			short_channel_id: 6,
4608			timestamp: 2,
4609			message_flags: 1, // Only must_be_one
4610			channel_flags: 2, // to disable
4611			cltv_expiry_delta: 0,
4612			htlc_minimum_msat: 0,
4613			htlc_maximum_msat: MAX_VALUE_MSAT,
4614			fee_base_msat: 0,
4615			fee_proportional_millionths: 0,
4616			excess_data: Vec::new()
4617		});
4618		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4619			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4620			short_channel_id: 7,
4621			timestamp: 2,
4622			message_flags: 1, // Only must_be_one
4623			channel_flags: 2, // to disable
4624			cltv_expiry_delta: 0,
4625			htlc_minimum_msat: 0,
4626			htlc_maximum_msat: MAX_VALUE_MSAT,
4627			fee_base_msat: 0,
4628			fee_proportional_millionths: 0,
4629			excess_data: Vec::new()
4630		});
4631
4632		let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4633		route_params.payment_params.max_path_length = 4;
4634		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4635			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4636		assert_eq!(route.paths[0].hops.len(), 4);
4637
4638		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4639		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4640		assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4641		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4642		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4643		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4644
4645		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4646		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4647		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4648		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4649		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4650		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4651
4652		assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
4653		assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4654		assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4655		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4656		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
4657		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4658
4659		assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4660		assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4661		assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4662		assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4663		assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4664		assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4665		route_params.payment_params.max_path_length = 3;
4666		get_route(&our_id, &route_params, &network_graph.read_only(), None,
4667			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
4668	}
4669
4670	#[test]
4671	fn private_multi_hint_last_hops_test() {
4672		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4673		let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4674
4675		let non_announced_privkey = SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
4676		let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
4677
4678		let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
4679		let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
4680		let scorer = ln_test_utils::TestScorer::new();
4681		// Test through channels 2, 3, 0xff00, 0xff01.
4682		// Test shows that multiple hop hints are considered.
4683
4684		// Disabling channels 6 & 7 by flags=2
4685		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4686			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4687			short_channel_id: 6,
4688			timestamp: 2,
4689			message_flags: 1, // Only must_be_one
4690			channel_flags: 2, // to disable
4691			cltv_expiry_delta: 0,
4692			htlc_minimum_msat: 0,
4693			htlc_maximum_msat: MAX_VALUE_MSAT,
4694			fee_base_msat: 0,
4695			fee_proportional_millionths: 0,
4696			excess_data: Vec::new()
4697		});
4698		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4699			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
4700			short_channel_id: 7,
4701			timestamp: 2,
4702			message_flags: 1, // Only must_be_one
4703			channel_flags: 2, // to disable
4704			cltv_expiry_delta: 0,
4705			htlc_minimum_msat: 0,
4706			htlc_maximum_msat: MAX_VALUE_MSAT,
4707			fee_base_msat: 0,
4708			fee_proportional_millionths: 0,
4709			excess_data: Vec::new()
4710		});
4711
4712		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4713		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4714			Arc::clone(&logger), &scorer, &Default::default(), &[42u8; 32]).unwrap();
4715		assert_eq!(route.paths[0].hops.len(), 4);
4716
4717		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4718		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4719		assert_eq!(route.paths[0].hops[0].fee_msat, 200);
4720		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
4721		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4722		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4723
4724		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4725		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4726		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4727		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
4728		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4729		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4730
4731		assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
4732		assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
4733		assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4734		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
4735		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4736		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4737
4738		assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4739		assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
4740		assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4741		assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4742		assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4743		assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4744	}
4745
4746	fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
4747		let zero_fees = RoutingFees {
4748			base_msat: 0,
4749			proportional_millionths: 0,
4750		};
4751		vec![RouteHint(vec![RouteHintHop {
4752			src_node_id: nodes[4],
4753			short_channel_id: 11,
4754			fees: zero_fees,
4755			cltv_expiry_delta: (11 << 4) | 1,
4756			htlc_minimum_msat: None,
4757			htlc_maximum_msat: None,
4758		}, RouteHintHop {
4759			src_node_id: nodes[3],
4760			short_channel_id: 8,
4761			fees: zero_fees,
4762			cltv_expiry_delta: (8 << 4) | 1,
4763			htlc_minimum_msat: None,
4764			htlc_maximum_msat: None,
4765		}]), RouteHint(vec![RouteHintHop {
4766			src_node_id: nodes[4],
4767			short_channel_id: 9,
4768			fees: RoutingFees {
4769				base_msat: 1001,
4770				proportional_millionths: 0,
4771			},
4772			cltv_expiry_delta: (9 << 4) | 1,
4773			htlc_minimum_msat: None,
4774			htlc_maximum_msat: None,
4775		}]), RouteHint(vec![RouteHintHop {
4776			src_node_id: nodes[5],
4777			short_channel_id: 10,
4778			fees: zero_fees,
4779			cltv_expiry_delta: (10 << 4) | 1,
4780			htlc_minimum_msat: None,
4781			htlc_maximum_msat: None,
4782		}])]
4783	}
4784
4785	#[test]
4786	fn last_hops_with_public_channel_test() {
4787		let (secp_ctx, network_graph, _, _, logger) = build_graph();
4788		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4789		let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
4790		let scorer = ln_test_utils::TestScorer::new();
4791		let random_seed_bytes = [42; 32];
4792
4793		// This test shows that public routes can be present in the invoice
4794		// which would be handled in the same manner.
4795
4796		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4797		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4798			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4799		assert_eq!(route.paths[0].hops.len(), 5);
4800
4801		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4802		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4803		assert_eq!(route.paths[0].hops[0].fee_msat, 100);
4804		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4805		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4806		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4807
4808		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4809		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4810		assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4811		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4812		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4813		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4814
4815		assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4816		assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4817		assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4818		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4819		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4820		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4821
4822		assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4823		assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4824		assert_eq!(route.paths[0].hops[3].fee_msat, 0);
4825		assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4826		// If we have a peer in the node map, we'll use their features here since we don't have
4827		// a way of figuring out their features from the invoice:
4828		assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4829		assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4830
4831		assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4832		assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4833		assert_eq!(route.paths[0].hops[4].fee_msat, 100);
4834		assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4835		assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4836		assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4837	}
4838
4839	#[test]
4840	fn our_chans_last_hop_connect_test() {
4841		let (secp_ctx, network_graph, _, _, logger) = build_graph();
4842		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4843		let scorer = ln_test_utils::TestScorer::new();
4844		let random_seed_bytes = [42; 32];
4845
4846		// Simple test with outbound channel to 4 to test that last_hops and first_hops connect
4847		let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
4848		let mut last_hops = last_hops(&nodes);
4849		let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4850			.with_route_hints(last_hops.clone()).unwrap();
4851		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
4852		let route = get_route(&our_id, &route_params, &network_graph.read_only(),
4853			Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
4854			&Default::default(), &random_seed_bytes).unwrap();
4855		assert_eq!(route.paths[0].hops.len(), 2);
4856
4857		assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
4858		assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4859		assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4860		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
4861		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
4862		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
4863
4864		assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
4865		assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
4866		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4867		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
4868		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4869		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4870
4871		last_hops[0].0[0].fees.base_msat = 1000;
4872
4873		// Revert to via 6 as the fee on 8 goes up
4874		let payment_params = PaymentParameters::from_node_id(nodes[6], 42)
4875			.with_route_hints(last_hops).unwrap();
4876		let route_params = RouteParameters::from_payment_params_and_value(
4877			payment_params.clone(), 100);
4878		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4879			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4880		assert_eq!(route.paths[0].hops.len(), 4);
4881
4882		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4883		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4884		assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
4885		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4886		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4887		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4888
4889		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4890		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4891		assert_eq!(route.paths[0].hops[1].fee_msat, 100);
4892		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
4893		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4894		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4895
4896		assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
4897		assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
4898		assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4899		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
4900		// If we have a peer in the node map, we'll use their features here since we don't have
4901		// a way of figuring out their features from the invoice:
4902		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
4903		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
4904
4905		assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
4906		assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
4907		assert_eq!(route.paths[0].hops[3].fee_msat, 100);
4908		assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
4909		assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4910		assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4911
4912		// ...but still use 8 for larger payments as 6 has a variable feerate
4913		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 2000);
4914		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
4915			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
4916		assert_eq!(route.paths[0].hops.len(), 5);
4917
4918		assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
4919		assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
4920		assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
4921		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
4922		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
4923		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
4924
4925		assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
4926		assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
4927		assert_eq!(route.paths[0].hops[1].fee_msat, 0);
4928		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
4929		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
4930		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
4931
4932		assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
4933		assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
4934		assert_eq!(route.paths[0].hops[2].fee_msat, 0);
4935		assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
4936		assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
4937		assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
4938
4939		assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
4940		assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
4941		assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
4942		assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
4943		// If we have a peer in the node map, we'll use their features here since we don't have
4944		// a way of figuring out their features from the invoice:
4945		assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
4946		assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
4947
4948		assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
4949		assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
4950		assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
4951		assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
4952		assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
4953		assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
4954	}
4955
4956	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> {
4957		let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
4958		let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4959		let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4960
4961		// If we specify a channel to a middle hop, that overrides our local channel view and that gets used
4962		let last_hops = RouteHint(vec![RouteHintHop {
4963			src_node_id: middle_node_id,
4964			short_channel_id: 8,
4965			fees: RoutingFees {
4966				base_msat: 1000,
4967				proportional_millionths: last_hop_fee_prop,
4968			},
4969			cltv_expiry_delta: (8 << 4) | 1,
4970			htlc_minimum_msat: None,
4971			htlc_maximum_msat: last_hop_htlc_max,
4972		}]);
4973		let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
4974		let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
4975		let scorer = ln_test_utils::TestScorer::new();
4976		let random_seed_bytes = [42; 32];
4977		let logger = ln_test_utils::TestLogger::new();
4978		let network_graph = NetworkGraph::new(Network::Testnet, &logger);
4979		let route_params = RouteParameters::from_payment_params_and_value(payment_params, route_val);
4980		let route = get_route(&source_node_id, &route_params, &network_graph.read_only(),
4981				Some(&our_chans.iter().collect::<Vec<_>>()), &logger, &scorer, &Default::default(),
4982				&random_seed_bytes);
4983		route
4984	}
4985
4986	#[test]
4987	fn unannounced_path_test() {
4988		// We should be able to send a payment to a destination without any help of a routing graph
4989		// if we have a channel with a common counterparty that appears in the first and last hop
4990		// hints.
4991		let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
4992
4993		let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
4994		let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&<Vec<u8>>::from_hex(&format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
4995		assert_eq!(route.paths[0].hops.len(), 2);
4996
4997		assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
4998		assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
4999		assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
5000		assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
5001		assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
5002		assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
5003
5004		assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
5005		assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
5006		assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
5007		assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5008		assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
5009		assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
5010	}
5011
5012	#[test]
5013	fn overflow_unannounced_path_test_liquidity_underflow() {
5014		// Previously, when we had a last-hop hint connected directly to a first-hop channel, where
5015		// the last-hop had a fee which overflowed a u64, we'd panic.
5016		// This was due to us adding the first-hop from us unconditionally, causing us to think
5017		// we'd built a path (as our node is in the "best candidate" set), when we had not.
5018		// In this test, we previously hit a subtraction underflow due to having less available
5019		// liquidity at the last hop than 0.
5020		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());
5021	}
5022
5023	#[test]
5024	fn overflow_unannounced_path_test_feerate_overflow() {
5025		// This tests for the same case as above, except instead of hitting a subtraction
5026		// underflow, we hit a case where the fee charged at a hop overflowed.
5027		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());
5028	}
5029
5030	#[test]
5031	fn available_amount_while_routing_test() {
5032		// Tests whether we choose the correct available channel amount while routing.
5033
5034		let (secp_ctx, network_graph, gossip_sync, chain_monitor, logger) = build_graph();
5035		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5036		let scorer = ln_test_utils::TestScorer::new();
5037		let random_seed_bytes = [42; 32];
5038		let config = UserConfig::default();
5039		let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5040			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5041			.unwrap();
5042
5043		// We will use a simple single-path route from
5044		// our node to node2 via node0: channels {1, 3}.
5045
5046		// First disable all other paths.
5047		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5048			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5049			short_channel_id: 2,
5050			timestamp: 2,
5051			message_flags: 1, // Only must_be_one
5052			channel_flags: 2,
5053			cltv_expiry_delta: 0,
5054			htlc_minimum_msat: 0,
5055			htlc_maximum_msat: 100_000,
5056			fee_base_msat: 0,
5057			fee_proportional_millionths: 0,
5058			excess_data: Vec::new()
5059		});
5060		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5061			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5062			short_channel_id: 12,
5063			timestamp: 2,
5064			message_flags: 1, // Only must_be_one
5065			channel_flags: 2,
5066			cltv_expiry_delta: 0,
5067			htlc_minimum_msat: 0,
5068			htlc_maximum_msat: 100_000,
5069			fee_base_msat: 0,
5070			fee_proportional_millionths: 0,
5071			excess_data: Vec::new()
5072		});
5073
5074		// Make the first channel (#1) very permissive,
5075		// and we will be testing all limits on the second channel.
5076		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5077			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5078			short_channel_id: 1,
5079			timestamp: 2,
5080			message_flags: 1, // Only must_be_one
5081			channel_flags: 0,
5082			cltv_expiry_delta: 0,
5083			htlc_minimum_msat: 0,
5084			htlc_maximum_msat: 1_000_000_000,
5085			fee_base_msat: 0,
5086			fee_proportional_millionths: 0,
5087			excess_data: Vec::new()
5088		});
5089
5090		// First, let's see if routing works if we have absolutely no idea about the available amount.
5091		// In this case, it should be set to 250_000 sats.
5092		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5093			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5094			short_channel_id: 3,
5095			timestamp: 2,
5096			message_flags: 1, // Only must_be_one
5097			channel_flags: 0,
5098			cltv_expiry_delta: 0,
5099			htlc_minimum_msat: 0,
5100			htlc_maximum_msat: 250_000_000,
5101			fee_base_msat: 0,
5102			fee_proportional_millionths: 0,
5103			excess_data: Vec::new()
5104		});
5105
5106		{
5107			// Attempt to route more than available results in a failure.
5108			let route_params = RouteParameters::from_payment_params_and_value(
5109				payment_params.clone(), 250_000_001);
5110			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5111					&our_id, &route_params, &network_graph.read_only(), None,
5112					Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5113						assert_eq!(err, "Failed to find a sufficient route to the given destination");
5114			} else { panic!(); }
5115		}
5116
5117		{
5118			// Now, attempt to route an exact amount we have should be fine.
5119			let route_params = RouteParameters::from_payment_params_and_value(
5120				payment_params.clone(), 250_000_000);
5121			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5122				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5123			assert_eq!(route.paths.len(), 1);
5124			let path = route.paths.last().unwrap();
5125			assert_eq!(path.hops.len(), 2);
5126			assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5127			assert_eq!(path.final_value_msat(), 250_000_000);
5128		}
5129
5130		// Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
5131		// Disable channel #1 and use another first hop.
5132		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5133			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5134			short_channel_id: 1,
5135			timestamp: 3,
5136			message_flags: 1, // Only must_be_one
5137			channel_flags: 2,
5138			cltv_expiry_delta: 0,
5139			htlc_minimum_msat: 0,
5140			htlc_maximum_msat: 1_000_000_000,
5141			fee_base_msat: 0,
5142			fee_proportional_millionths: 0,
5143			excess_data: Vec::new()
5144		});
5145
5146		// Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
5147		let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
5148
5149		{
5150			// Attempt to route more than available results in a failure.
5151			let route_params = RouteParameters::from_payment_params_and_value(
5152				payment_params.clone(), 200_000_001);
5153			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5154					&our_id, &route_params, &network_graph.read_only(),
5155					Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
5156					&Default::default(), &random_seed_bytes) {
5157						assert_eq!(err, "Failed to find a sufficient route to the given destination");
5158			} else { panic!(); }
5159		}
5160
5161		{
5162			// Now, attempt to route an exact amount we have should be fine.
5163			let route_params = RouteParameters::from_payment_params_and_value(
5164				payment_params.clone(), 200_000_000);
5165			let route = get_route(&our_id, &route_params, &network_graph.read_only(),
5166				Some(&our_chans.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
5167				&Default::default(), &random_seed_bytes).unwrap();
5168			assert_eq!(route.paths.len(), 1);
5169			let path = route.paths.last().unwrap();
5170			assert_eq!(path.hops.len(), 2);
5171			assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5172			assert_eq!(path.final_value_msat(), 200_000_000);
5173		}
5174
5175		// Enable channel #1 back.
5176		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5177			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5178			short_channel_id: 1,
5179			timestamp: 4,
5180			message_flags: 1, // Only must_be_one
5181			channel_flags: 0,
5182			cltv_expiry_delta: 0,
5183			htlc_minimum_msat: 0,
5184			htlc_maximum_msat: 1_000_000_000,
5185			fee_base_msat: 0,
5186			fee_proportional_millionths: 0,
5187			excess_data: Vec::new()
5188		});
5189
5190
5191		// Now let's see if routing works if we know only htlc_maximum_msat.
5192		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5193			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5194			short_channel_id: 3,
5195			timestamp: 3,
5196			message_flags: 1, // Only must_be_one
5197			channel_flags: 0,
5198			cltv_expiry_delta: 0,
5199			htlc_minimum_msat: 0,
5200			htlc_maximum_msat: 15_000,
5201			fee_base_msat: 0,
5202			fee_proportional_millionths: 0,
5203			excess_data: Vec::new()
5204		});
5205
5206		{
5207			// Attempt to route more than available results in a failure.
5208			let route_params = RouteParameters::from_payment_params_and_value(
5209				payment_params.clone(), 15_001);
5210			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5211					&our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5212					&scorer, &Default::default(), &random_seed_bytes) {
5213						assert_eq!(err, "Failed to find a sufficient route to the given destination");
5214			} else { panic!(); }
5215		}
5216
5217		{
5218			// Now, attempt to route an exact amount we have should be fine.
5219			let route_params = RouteParameters::from_payment_params_and_value(
5220				payment_params.clone(), 15_000);
5221			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5222				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5223			assert_eq!(route.paths.len(), 1);
5224			let path = route.paths.last().unwrap();
5225			assert_eq!(path.hops.len(), 2);
5226			assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5227			assert_eq!(path.final_value_msat(), 15_000);
5228		}
5229
5230		// Now let's see if routing works if we know only capacity from the UTXO.
5231
5232		// We can't change UTXO capacity on the fly, so we'll disable
5233		// the existing channel and add another one with the capacity we need.
5234		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5235			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5236			short_channel_id: 3,
5237			timestamp: 4,
5238			message_flags: 1, // Only must_be_one
5239			channel_flags: 2,
5240			cltv_expiry_delta: 0,
5241			htlc_minimum_msat: 0,
5242			htlc_maximum_msat: MAX_VALUE_MSAT,
5243			fee_base_msat: 0,
5244			fee_proportional_millionths: 0,
5245			excess_data: Vec::new()
5246		});
5247
5248		let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
5249		.push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
5250		.push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
5251		.push_opcode(opcodes::all::OP_PUSHNUM_2)
5252		.push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_p2wsh();
5253
5254		*chain_monitor.utxo_ret.lock().unwrap() =
5255			UtxoResult::Sync(Ok(TxOut { value: Amount::from_sat(15), script_pubkey: good_script.clone() }));
5256		gossip_sync.add_utxo_lookup(Some(chain_monitor));
5257
5258		add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
5259		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5260			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5261			short_channel_id: 333,
5262			timestamp: 1,
5263			message_flags: 1, // Only must_be_one
5264			channel_flags: 0,
5265			cltv_expiry_delta: (3 << 4) | 1,
5266			htlc_minimum_msat: 0,
5267			htlc_maximum_msat: 15_000,
5268			fee_base_msat: 0,
5269			fee_proportional_millionths: 0,
5270			excess_data: Vec::new()
5271		});
5272		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5273			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5274			short_channel_id: 333,
5275			timestamp: 1,
5276			message_flags: 1, // Only must_be_one
5277			channel_flags: 1,
5278			cltv_expiry_delta: (3 << 4) | 2,
5279			htlc_minimum_msat: 0,
5280			htlc_maximum_msat: 15_000,
5281			fee_base_msat: 100,
5282			fee_proportional_millionths: 0,
5283			excess_data: Vec::new()
5284		});
5285
5286		{
5287			// Attempt to route more than available results in a failure.
5288			let route_params = RouteParameters::from_payment_params_and_value(
5289				payment_params.clone(), 15_001);
5290			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5291					&our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5292					&scorer, &Default::default(), &random_seed_bytes) {
5293						assert_eq!(err, "Failed to find a sufficient route to the given destination");
5294			} else { panic!(); }
5295		}
5296
5297		{
5298			// Now, attempt to route an exact amount we have should be fine.
5299			let route_params = RouteParameters::from_payment_params_and_value(
5300				payment_params.clone(), 15_000);
5301			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5302				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5303			assert_eq!(route.paths.len(), 1);
5304			let path = route.paths.last().unwrap();
5305			assert_eq!(path.hops.len(), 2);
5306			assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5307			assert_eq!(path.final_value_msat(), 15_000);
5308		}
5309
5310		// Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
5311		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5312			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5313			short_channel_id: 333,
5314			timestamp: 6,
5315			message_flags: 1, // Only must_be_one
5316			channel_flags: 0,
5317			cltv_expiry_delta: 0,
5318			htlc_minimum_msat: 0,
5319			htlc_maximum_msat: 10_000,
5320			fee_base_msat: 0,
5321			fee_proportional_millionths: 0,
5322			excess_data: Vec::new()
5323		});
5324
5325		{
5326			// Attempt to route more than available results in a failure.
5327			let route_params = RouteParameters::from_payment_params_and_value(
5328				payment_params.clone(), 10_001);
5329			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5330					&our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5331					&scorer, &Default::default(), &random_seed_bytes) {
5332						assert_eq!(err, "Failed to find a sufficient route to the given destination");
5333			} else { panic!(); }
5334		}
5335
5336		{
5337			// Now, attempt to route an exact amount we have should be fine.
5338			let route_params = RouteParameters::from_payment_params_and_value(
5339				payment_params.clone(), 10_000);
5340			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5341				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5342			assert_eq!(route.paths.len(), 1);
5343			let path = route.paths.last().unwrap();
5344			assert_eq!(path.hops.len(), 2);
5345			assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5346			assert_eq!(path.final_value_msat(), 10_000);
5347		}
5348	}
5349
5350	#[test]
5351	fn available_liquidity_last_hop_test() {
5352		// Check that available liquidity properly limits the path even when only
5353		// one of the latter hops is limited.
5354		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5355		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5356		let scorer = ln_test_utils::TestScorer::new();
5357		let random_seed_bytes = [42; 32];
5358		let config = UserConfig::default();
5359		let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5360			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5361			.unwrap();
5362
5363		// Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5364		// {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
5365		// Total capacity: 50 sats.
5366
5367		// Disable other potential paths.
5368		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5369			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5370			short_channel_id: 2,
5371			timestamp: 2,
5372			message_flags: 1, // Only must_be_one
5373			channel_flags: 2,
5374			cltv_expiry_delta: 0,
5375			htlc_minimum_msat: 0,
5376			htlc_maximum_msat: 100_000,
5377			fee_base_msat: 0,
5378			fee_proportional_millionths: 0,
5379			excess_data: Vec::new()
5380		});
5381		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5382			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5383			short_channel_id: 7,
5384			timestamp: 2,
5385			message_flags: 1, // Only must_be_one
5386			channel_flags: 2,
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		// Limit capacities
5396
5397		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5398			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5399			short_channel_id: 12,
5400			timestamp: 2,
5401			message_flags: 1, // Only must_be_one
5402			channel_flags: 0,
5403			cltv_expiry_delta: 0,
5404			htlc_minimum_msat: 0,
5405			htlc_maximum_msat: 100_000,
5406			fee_base_msat: 0,
5407			fee_proportional_millionths: 0,
5408			excess_data: Vec::new()
5409		});
5410		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5411			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5412			short_channel_id: 13,
5413			timestamp: 2,
5414			message_flags: 1, // Only must_be_one
5415			channel_flags: 0,
5416			cltv_expiry_delta: 0,
5417			htlc_minimum_msat: 0,
5418			htlc_maximum_msat: 100_000,
5419			fee_base_msat: 0,
5420			fee_proportional_millionths: 0,
5421			excess_data: Vec::new()
5422		});
5423
5424		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5425			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5426			short_channel_id: 6,
5427			timestamp: 2,
5428			message_flags: 1, // Only must_be_one
5429			channel_flags: 0,
5430			cltv_expiry_delta: 0,
5431			htlc_minimum_msat: 0,
5432			htlc_maximum_msat: 50_000,
5433			fee_base_msat: 0,
5434			fee_proportional_millionths: 0,
5435			excess_data: Vec::new()
5436		});
5437		update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5438			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5439			short_channel_id: 11,
5440			timestamp: 2,
5441			message_flags: 1, // Only must_be_one
5442			channel_flags: 0,
5443			cltv_expiry_delta: 0,
5444			htlc_minimum_msat: 0,
5445			htlc_maximum_msat: 100_000,
5446			fee_base_msat: 0,
5447			fee_proportional_millionths: 0,
5448			excess_data: Vec::new()
5449		});
5450		{
5451			// Attempt to route more than available results in a failure.
5452			let route_params = RouteParameters::from_payment_params_and_value(
5453				payment_params.clone(), 60_000);
5454			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5455					&our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
5456					&scorer, &Default::default(), &random_seed_bytes) {
5457						assert_eq!(err, "Failed to find a sufficient route to the given destination");
5458			} else { panic!(); }
5459		}
5460
5461		{
5462			// Now, attempt to route 49 sats (just a bit below the capacity).
5463			let route_params = RouteParameters::from_payment_params_and_value(
5464				payment_params.clone(), 49_000);
5465			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5466				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5467			assert_eq!(route.paths.len(), 1);
5468			let mut total_amount_paid_msat = 0;
5469			for path in &route.paths {
5470				assert_eq!(path.hops.len(), 4);
5471				assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5472				total_amount_paid_msat += path.final_value_msat();
5473			}
5474			assert_eq!(total_amount_paid_msat, 49_000);
5475		}
5476
5477		{
5478			// Attempt to route an exact amount is also fine
5479			let route_params = RouteParameters::from_payment_params_and_value(
5480				payment_params, 50_000);
5481			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5482				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5483			assert_eq!(route.paths.len(), 1);
5484			let mut total_amount_paid_msat = 0;
5485			for path in &route.paths {
5486				assert_eq!(path.hops.len(), 4);
5487				assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5488				total_amount_paid_msat += path.final_value_msat();
5489			}
5490			assert_eq!(total_amount_paid_msat, 50_000);
5491		}
5492	}
5493
5494	#[test]
5495	fn ignore_fee_first_hop_test() {
5496		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5497		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5498		let scorer = ln_test_utils::TestScorer::new();
5499		let random_seed_bytes = [42; 32];
5500		let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5501
5502		// Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5503		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5504			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5505			short_channel_id: 1,
5506			timestamp: 2,
5507			message_flags: 1, // Only must_be_one
5508			channel_flags: 0,
5509			cltv_expiry_delta: 0,
5510			htlc_minimum_msat: 0,
5511			htlc_maximum_msat: 100_000,
5512			fee_base_msat: 1_000_000,
5513			fee_proportional_millionths: 0,
5514			excess_data: Vec::new()
5515		});
5516		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5517			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5518			short_channel_id: 3,
5519			timestamp: 2,
5520			message_flags: 1, // Only must_be_one
5521			channel_flags: 0,
5522			cltv_expiry_delta: 0,
5523			htlc_minimum_msat: 0,
5524			htlc_maximum_msat: 50_000,
5525			fee_base_msat: 0,
5526			fee_proportional_millionths: 0,
5527			excess_data: Vec::new()
5528		});
5529
5530		{
5531			let route_params = RouteParameters::from_payment_params_and_value(
5532				payment_params, 50_000);
5533			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5534				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5535			assert_eq!(route.paths.len(), 1);
5536			let mut total_amount_paid_msat = 0;
5537			for path in &route.paths {
5538				assert_eq!(path.hops.len(), 2);
5539				assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5540				total_amount_paid_msat += path.final_value_msat();
5541			}
5542			assert_eq!(total_amount_paid_msat, 50_000);
5543		}
5544	}
5545
5546	#[test]
5547	fn simple_mpp_route_test() {
5548		let (secp_ctx, _, _, _, _) = build_graph();
5549		let (_, _, _, nodes) = get_nodes(&secp_ctx);
5550		let config = UserConfig::default();
5551		let clear_payment_params = PaymentParameters::from_node_id(nodes[2], 42)
5552			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5553			.unwrap();
5554		do_simple_mpp_route_test(clear_payment_params);
5555
5556		// MPP to a 1-hop blinded path for nodes[2]
5557		let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
5558		let blinded_payinfo = BlindedPayInfo { // These fields are ignored for 1-hop blinded paths
5559			fee_base_msat: 0,
5560			fee_proportional_millionths: 0,
5561			htlc_minimum_msat: 0,
5562			htlc_maximum_msat: 0,
5563			cltv_expiry_delta: 0,
5564			features: BlindedHopFeatures::empty(),
5565		};
5566		let blinded_path = dummy_one_hop_blinded_path(nodes[2], blinded_payinfo.clone());
5567		let one_hop_blinded_payment_params = PaymentParameters::blinded(vec![blinded_path.clone()])
5568			.with_bolt12_features(bolt12_features.clone()).unwrap();
5569		do_simple_mpp_route_test(one_hop_blinded_payment_params.clone());
5570
5571		// MPP to 3 2-hop blinded paths
5572		let mut node_0_payinfo = blinded_payinfo.clone();
5573		node_0_payinfo.htlc_maximum_msat = 50_000;
5574		let blinded_path_node_0 = dummy_blinded_path(nodes[0], node_0_payinfo);
5575
5576		let mut node_7_payinfo = blinded_payinfo.clone();
5577		node_7_payinfo.htlc_maximum_msat = 60_000;
5578		let blinded_path_node_7 = dummy_blinded_path(nodes[7], node_7_payinfo);
5579
5580		let mut node_1_payinfo = blinded_payinfo;
5581		node_1_payinfo.htlc_maximum_msat = 180_000;
5582		let blinded_path_node_1 = dummy_blinded_path(nodes[1], node_1_payinfo);
5583
5584		let two_hop_blinded_payment_params = PaymentParameters::blinded(
5585			vec![blinded_path_node_0, blinded_path_node_7, blinded_path_node_1])
5586			.with_bolt12_features(bolt12_features).unwrap();
5587		do_simple_mpp_route_test(two_hop_blinded_payment_params);
5588	}
5589
5590
5591	fn do_simple_mpp_route_test(payment_params: PaymentParameters) {
5592		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5593		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5594		let scorer = ln_test_utils::TestScorer::new();
5595		let random_seed_bytes = [42; 32];
5596
5597		// We need a route consisting of 3 paths:
5598		// From our node to node2 via node0, node7, node1 (three paths one hop each).
5599		// To achieve this, the amount being transferred should be around
5600		// the total capacity of these 3 paths.
5601
5602		// First, we set limits on these (previously unlimited) channels.
5603		// Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
5604
5605		// Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
5606		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5607			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5608			short_channel_id: 1,
5609			timestamp: 2,
5610			message_flags: 1, // Only must_be_one
5611			channel_flags: 0,
5612			cltv_expiry_delta: 0,
5613			htlc_minimum_msat: 0,
5614			htlc_maximum_msat: 100_000,
5615			fee_base_msat: 0,
5616			fee_proportional_millionths: 0,
5617			excess_data: Vec::new()
5618		});
5619		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5620			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5621			short_channel_id: 3,
5622			timestamp: 2,
5623			message_flags: 1, // Only must_be_one
5624			channel_flags: 0,
5625			cltv_expiry_delta: 0,
5626			htlc_minimum_msat: 0,
5627			htlc_maximum_msat: 50_000,
5628			fee_base_msat: 0,
5629			fee_proportional_millionths: 0,
5630			excess_data: Vec::new()
5631		});
5632
5633		// Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
5634		// (total limit 60).
5635		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5636			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5637			short_channel_id: 12,
5638			timestamp: 2,
5639			message_flags: 1, // Only must_be_one
5640			channel_flags: 0,
5641			cltv_expiry_delta: 0,
5642			htlc_minimum_msat: 0,
5643			htlc_maximum_msat: 60_000,
5644			fee_base_msat: 0,
5645			fee_proportional_millionths: 0,
5646			excess_data: Vec::new()
5647		});
5648		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5649			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5650			short_channel_id: 13,
5651			timestamp: 2,
5652			message_flags: 1, // Only must_be_one
5653			channel_flags: 0,
5654			cltv_expiry_delta: 0,
5655			htlc_minimum_msat: 0,
5656			htlc_maximum_msat: 60_000,
5657			fee_base_msat: 0,
5658			fee_proportional_millionths: 0,
5659			excess_data: Vec::new()
5660		});
5661
5662		// Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
5663		// (total capacity 180 sats).
5664		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5665			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5666			short_channel_id: 2,
5667			timestamp: 2,
5668			message_flags: 1, // Only must_be_one
5669			channel_flags: 0,
5670			cltv_expiry_delta: 0,
5671			htlc_minimum_msat: 0,
5672			htlc_maximum_msat: 200_000,
5673			fee_base_msat: 0,
5674			fee_proportional_millionths: 0,
5675			excess_data: Vec::new()
5676		});
5677		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5678			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5679			short_channel_id: 4,
5680			timestamp: 2,
5681			message_flags: 1, // Only must_be_one
5682			channel_flags: 0,
5683			cltv_expiry_delta: 0,
5684			htlc_minimum_msat: 0,
5685			htlc_maximum_msat: 180_000,
5686			fee_base_msat: 0,
5687			fee_proportional_millionths: 0,
5688			excess_data: Vec::new()
5689		});
5690
5691		{
5692			// Attempt to route more than available results in a failure.
5693			let route_params = RouteParameters::from_payment_params_and_value(
5694				payment_params.clone(), 300_000);
5695			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5696				&our_id, &route_params, &network_graph.read_only(), None,
5697				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5698					assert_eq!(err, "Failed to find a sufficient route to the given destination");
5699			} else { panic!(); }
5700		}
5701
5702		{
5703			// Attempt to route while setting max_path_count to 0 results in a failure.
5704			let zero_payment_params = payment_params.clone().with_max_path_count(0);
5705			let route_params = RouteParameters::from_payment_params_and_value(
5706				zero_payment_params, 100);
5707			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5708				&our_id, &route_params, &network_graph.read_only(), None,
5709				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5710					assert_eq!(err, "Can't find a route with no paths allowed.");
5711			} else { panic!(); }
5712		}
5713
5714		{
5715			// Attempt to route while setting max_path_count to 3 results in a failure.
5716			// This is the case because the minimal_value_contribution_msat would require each path
5717			// to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
5718			let fail_payment_params = payment_params.clone().with_max_path_count(3);
5719			let route_params = RouteParameters::from_payment_params_and_value(
5720				fail_payment_params, 250_000);
5721			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5722				&our_id, &route_params, &network_graph.read_only(), None,
5723				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes) {
5724					assert_eq!(err, "Failed to find a sufficient route to the given destination");
5725			} else { panic!(); }
5726		}
5727
5728		{
5729			// Now, attempt to route 250 sats (just a bit below the capacity).
5730			// Our algorithm should provide us with these 3 paths.
5731			let route_params = RouteParameters::from_payment_params_and_value(
5732				payment_params.clone(), 250_000);
5733			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5734				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5735			assert_eq!(route.paths.len(), 3);
5736			let mut total_amount_paid_msat = 0;
5737			for path in &route.paths {
5738				if let Some(bt) = &path.blinded_tail {
5739					assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5740				} else {
5741					assert_eq!(path.hops.len(), 2);
5742					assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5743				}
5744				total_amount_paid_msat += path.final_value_msat();
5745			}
5746			assert_eq!(total_amount_paid_msat, 250_000);
5747		}
5748
5749		{
5750			// Attempt to route an exact amount is also fine
5751			let route_params = RouteParameters::from_payment_params_and_value(
5752				payment_params.clone(), 290_000);
5753			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5754				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
5755			assert_eq!(route.paths.len(), 3);
5756			let mut total_amount_paid_msat = 0;
5757			for path in &route.paths {
5758				if payment_params.payee.blinded_route_hints().len() != 0 {
5759					assert!(path.blinded_tail.is_some()) } else { assert!(path.blinded_tail.is_none()) }
5760				if let Some(bt) = &path.blinded_tail {
5761					assert_eq!(path.hops.len() + if bt.hops.len() == 1 { 0 } else { 1 }, 2);
5762					if bt.hops.len() > 1 {
5763						let network_graph = network_graph.read_only();
5764						assert_eq!(
5765							NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
5766							payment_params.payee.blinded_route_hints().iter()
5767								.find(|p| p.payinfo.htlc_maximum_msat == path.final_value_msat())
5768								.and_then(|p| p.public_introduction_node_id(&network_graph))
5769								.copied()
5770								.unwrap()
5771						);
5772					} else {
5773						assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5774					}
5775				} else {
5776					assert_eq!(path.hops.len(), 2);
5777					assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5778				}
5779				total_amount_paid_msat += path.final_value_msat();
5780			}
5781			assert_eq!(total_amount_paid_msat, 290_000);
5782		}
5783	}
5784
5785	#[test]
5786	fn mpp_tests() {
5787		let secp_ctx = Secp256k1::new();
5788		let (_, _, _, nodes) = get_nodes(&secp_ctx);
5789		{
5790			// Check that if we have two cheaper paths and a more expensive (fewer hops) path, we
5791			// choose the two cheaper paths:
5792			let route = do_mpp_route_tests(180_000).unwrap();
5793			assert_eq!(route.paths.len(), 2);
5794
5795			let mut total_value_transferred_msat = 0;
5796			let mut total_paid_msat = 0;
5797			for path in &route.paths {
5798				assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5799				total_value_transferred_msat += path.final_value_msat();
5800				for hop in &path.hops {
5801					total_paid_msat += hop.fee_msat;
5802				}
5803			}
5804			// If we paid fee, this would be higher.
5805			assert_eq!(total_value_transferred_msat, 180_000);
5806			let total_fees_paid = total_paid_msat - total_value_transferred_msat;
5807			assert_eq!(total_fees_paid, 0);
5808		}
5809		{
5810			// Check that if we use the same channels but need to send more than we could fit in
5811			// the cheaper paths we select all three paths:
5812			let route = do_mpp_route_tests(300_000).unwrap();
5813			assert_eq!(route.paths.len(), 3);
5814
5815			let mut total_amount_paid_msat = 0;
5816			for path in &route.paths {
5817				assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
5818				total_amount_paid_msat += path.final_value_msat();
5819			}
5820			assert_eq!(total_amount_paid_msat, 300_000);
5821		}
5822		// Check that trying to pay more than our available liquidity fails.
5823		assert!(do_mpp_route_tests(300_001).is_err());
5824	}
5825
5826	fn do_mpp_route_tests(amt: u64) -> Result<Route, LightningError> {
5827		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5828		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5829		let scorer = ln_test_utils::TestScorer::new();
5830		let random_seed_bytes = [42; 32];
5831		let config = UserConfig::default();
5832		let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
5833			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
5834			.unwrap();
5835
5836		// Build a setup where we have three potential paths from us to node3:
5837		//  {node0, node2, node4} (channels 1, 3, 6, 11), fee 0 msat,
5838		//  {node7, node2, node4} (channels 12, 13, 6, 11), fee 0 msat, and
5839		//  {node1} (channel 2, then a new channel 16), fee 1000 msat.
5840		// Note that these paths overlap on channels 6 and 11.
5841		// Each channel will have 100 sats capacity except for 6 and 11, which have 200.
5842
5843		// Disable other potential paths.
5844		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5845			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5846			short_channel_id: 7,
5847			timestamp: 2,
5848			message_flags: 1, // Only must_be_one
5849			channel_flags: 2,
5850			cltv_expiry_delta: 0,
5851			htlc_minimum_msat: 0,
5852			htlc_maximum_msat: 100_000,
5853			fee_base_msat: 0,
5854			fee_proportional_millionths: 0,
5855			excess_data: Vec::new()
5856		});
5857		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5858			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5859			short_channel_id: 4,
5860			timestamp: 2,
5861			message_flags: 1, // Only must_be_one
5862			channel_flags: 2,
5863			cltv_expiry_delta: 0,
5864			htlc_minimum_msat: 0,
5865			htlc_maximum_msat: 100_000,
5866			fee_base_msat: 0,
5867			fee_proportional_millionths: 0,
5868			excess_data: Vec::new()
5869		});
5870
5871		// Path via {node0, node2} is channels {1, 3, 5}.
5872		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5873			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5874			short_channel_id: 1,
5875			timestamp: 2,
5876			message_flags: 1, // Only must_be_one
5877			channel_flags: 0,
5878			cltv_expiry_delta: 0,
5879			htlc_minimum_msat: 0,
5880			htlc_maximum_msat: 100_000,
5881			fee_base_msat: 0,
5882			fee_proportional_millionths: 0,
5883			excess_data: Vec::new()
5884		});
5885		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5886			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5887			short_channel_id: 3,
5888			timestamp: 2,
5889			message_flags: 1, // Only must_be_one
5890			channel_flags: 0,
5891			cltv_expiry_delta: 0,
5892			htlc_minimum_msat: 0,
5893			htlc_maximum_msat: 100_000,
5894			fee_base_msat: 0,
5895			fee_proportional_millionths: 0,
5896			excess_data: Vec::new()
5897		});
5898
5899		add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(16)), 16);
5900		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5901			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5902			short_channel_id: 16,
5903			timestamp: 2,
5904			message_flags: 1, // Only must_be_one
5905			channel_flags: 0,
5906			cltv_expiry_delta: 0,
5907			htlc_minimum_msat: 0,
5908			htlc_maximum_msat: 100_000,
5909			fee_base_msat: 1_000,
5910			fee_proportional_millionths: 0,
5911			excess_data: Vec::new()
5912		});
5913		update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5914			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5915			short_channel_id: 16,
5916			timestamp: 2,
5917			message_flags: 1, // Only must_be_one
5918			channel_flags: 3, // disable direction 1
5919			cltv_expiry_delta: 0,
5920			htlc_minimum_msat: 0,
5921			htlc_maximum_msat: 100_000,
5922			fee_base_msat: 1_000,
5923			fee_proportional_millionths: 0,
5924			excess_data: Vec::new()
5925		});
5926
5927		// Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
5928		// Add 100 sats to the capacities of {12, 13}, because these channels
5929		// are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
5930		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5931			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5932			short_channel_id: 12,
5933			timestamp: 2,
5934			message_flags: 1, // Only must_be_one
5935			channel_flags: 0,
5936			cltv_expiry_delta: 0,
5937			htlc_minimum_msat: 0,
5938			htlc_maximum_msat: 100_000,
5939			fee_base_msat: 0,
5940			fee_proportional_millionths: 0,
5941			excess_data: Vec::new()
5942		});
5943		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5944			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5945			short_channel_id: 13,
5946			timestamp: 2,
5947			message_flags: 1, // Only must_be_one
5948			channel_flags: 0,
5949			cltv_expiry_delta: 0,
5950			htlc_minimum_msat: 0,
5951			htlc_maximum_msat: 100_000,
5952			fee_base_msat: 0,
5953			fee_proportional_millionths: 0,
5954			excess_data: Vec::new()
5955		});
5956
5957		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5958			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5959			short_channel_id: 6,
5960			timestamp: 2,
5961			message_flags: 1, // Only must_be_one
5962			channel_flags: 0,
5963			cltv_expiry_delta: 0,
5964			htlc_minimum_msat: 0,
5965			htlc_maximum_msat: 200_000,
5966			fee_base_msat: 0,
5967			fee_proportional_millionths: 0,
5968			excess_data: Vec::new()
5969		});
5970		update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5971			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
5972			short_channel_id: 11,
5973			timestamp: 2,
5974			message_flags: 1, // Only must_be_one
5975			channel_flags: 0,
5976			cltv_expiry_delta: 0,
5977			htlc_minimum_msat: 0,
5978			htlc_maximum_msat: 200_000,
5979			fee_base_msat: 0,
5980			fee_proportional_millionths: 0,
5981			excess_data: Vec::new()
5982		});
5983
5984		// Path via {node7, node2} is channels {12, 13, 5}.
5985		// We already limited them to 200 sats (they are used twice for 100 sats).
5986		// Nothing to do here.
5987
5988		let route_params = RouteParameters::from_payment_params_and_value(
5989			payment_params, amt);
5990		let res = get_route(&our_id, &route_params, &network_graph.read_only(), None,
5991			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes);
5992		res
5993	}
5994
5995	#[test]
5996	fn fees_on_mpp_route_test() {
5997		// This test makes sure that MPP algorithm properly takes into account
5998		// fees charged on the channels, by making the fees impactful:
5999		// if the fee is not properly accounted for, the behavior is different.
6000		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6001		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6002		let scorer = ln_test_utils::TestScorer::new();
6003		let random_seed_bytes = [42; 32];
6004		let config = UserConfig::default();
6005		let payment_params = PaymentParameters::from_node_id(nodes[3], 42)
6006			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6007			.unwrap();
6008
6009		// We need a route consisting of 2 paths:
6010		// From our node to node3 via {node0, node2} and {node7, node2, node4}.
6011		// We will route 200 sats, Each path will have 100 sats capacity.
6012
6013		// This test is not particularly stable: e.g.,
6014		// there's a way to route via {node0, node2, node4}.
6015		// It works while pathfinding is deterministic, but can be broken otherwise.
6016		// It's fine to ignore this concern for now.
6017
6018		// Disable other potential paths.
6019		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6020			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6021			short_channel_id: 2,
6022			timestamp: 2,
6023			message_flags: 1, // Only must_be_one
6024			channel_flags: 2,
6025			cltv_expiry_delta: 0,
6026			htlc_minimum_msat: 0,
6027			htlc_maximum_msat: 100_000,
6028			fee_base_msat: 0,
6029			fee_proportional_millionths: 0,
6030			excess_data: Vec::new()
6031		});
6032
6033		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6034			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6035			short_channel_id: 7,
6036			timestamp: 2,
6037			message_flags: 1, // Only must_be_one
6038			channel_flags: 2,
6039			cltv_expiry_delta: 0,
6040			htlc_minimum_msat: 0,
6041			htlc_maximum_msat: 100_000,
6042			fee_base_msat: 0,
6043			fee_proportional_millionths: 0,
6044			excess_data: Vec::new()
6045		});
6046
6047		// Path via {node0, node2} is channels {1, 3, 5}.
6048		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6049			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6050			short_channel_id: 1,
6051			timestamp: 2,
6052			message_flags: 1, // Only must_be_one
6053			channel_flags: 0,
6054			cltv_expiry_delta: 0,
6055			htlc_minimum_msat: 0,
6056			htlc_maximum_msat: 100_000,
6057			fee_base_msat: 0,
6058			fee_proportional_millionths: 0,
6059			excess_data: Vec::new()
6060		});
6061		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6062			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6063			short_channel_id: 3,
6064			timestamp: 2,
6065			message_flags: 1, // Only must_be_one
6066			channel_flags: 0,
6067			cltv_expiry_delta: 0,
6068			htlc_minimum_msat: 0,
6069			htlc_maximum_msat: 100_000,
6070			fee_base_msat: 0,
6071			fee_proportional_millionths: 0,
6072			excess_data: Vec::new()
6073		});
6074
6075		add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6076		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6077			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6078			short_channel_id: 5,
6079			timestamp: 2,
6080			message_flags: 1, // Only must_be_one
6081			channel_flags: 0,
6082			cltv_expiry_delta: 0,
6083			htlc_minimum_msat: 0,
6084			htlc_maximum_msat: 100_000,
6085			fee_base_msat: 0,
6086			fee_proportional_millionths: 0,
6087			excess_data: Vec::new()
6088		});
6089		update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
6090			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6091			short_channel_id: 5,
6092			timestamp: 2,
6093			message_flags: 1, // Only must_be_one
6094			channel_flags: 3, // Disable direction 1
6095			cltv_expiry_delta: 0,
6096			htlc_minimum_msat: 0,
6097			htlc_maximum_msat: 100_000,
6098			fee_base_msat: 0,
6099			fee_proportional_millionths: 0,
6100			excess_data: Vec::new()
6101		});
6102
6103		// Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
6104		// All channels should be 100 sats capacity. But for the fee experiment,
6105		// we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
6106		// Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
6107		// 100 sats (and pay 150 sats in fees for the use of channel 6),
6108		// so no matter how large are other channels,
6109		// the whole path will be limited by 100 sats with just these 2 conditions:
6110		// - channel 12 capacity is 250 sats
6111		// - fee for channel 6 is 150 sats
6112		// Let's test this by enforcing these 2 conditions and removing other limits.
6113		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6114			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6115			short_channel_id: 12,
6116			timestamp: 2,
6117			message_flags: 1, // Only must_be_one
6118			channel_flags: 0,
6119			cltv_expiry_delta: 0,
6120			htlc_minimum_msat: 0,
6121			htlc_maximum_msat: 250_000,
6122			fee_base_msat: 0,
6123			fee_proportional_millionths: 0,
6124			excess_data: Vec::new()
6125		});
6126		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6127			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6128			short_channel_id: 13,
6129			timestamp: 2,
6130			message_flags: 1, // Only must_be_one
6131			channel_flags: 0,
6132			cltv_expiry_delta: 0,
6133			htlc_minimum_msat: 0,
6134			htlc_maximum_msat: MAX_VALUE_MSAT,
6135			fee_base_msat: 0,
6136			fee_proportional_millionths: 0,
6137			excess_data: Vec::new()
6138		});
6139
6140		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
6141			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6142			short_channel_id: 6,
6143			timestamp: 2,
6144			message_flags: 1, // Only must_be_one
6145			channel_flags: 0,
6146			cltv_expiry_delta: 0,
6147			htlc_minimum_msat: 0,
6148			htlc_maximum_msat: MAX_VALUE_MSAT,
6149			fee_base_msat: 150_000,
6150			fee_proportional_millionths: 0,
6151			excess_data: Vec::new()
6152		});
6153		update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
6154			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6155			short_channel_id: 11,
6156			timestamp: 2,
6157			message_flags: 1, // Only must_be_one
6158			channel_flags: 0,
6159			cltv_expiry_delta: 0,
6160			htlc_minimum_msat: 0,
6161			htlc_maximum_msat: MAX_VALUE_MSAT,
6162			fee_base_msat: 0,
6163			fee_proportional_millionths: 0,
6164			excess_data: Vec::new()
6165		});
6166
6167		{
6168			// Attempt to route more than available results in a failure.
6169			let route_params = RouteParameters::from_payment_params_and_value(
6170				payment_params.clone(), 210_000);
6171			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6172					&our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6173					&scorer, &Default::default(), &random_seed_bytes) {
6174						assert_eq!(err, "Failed to find a sufficient route to the given destination");
6175			} else { panic!(); }
6176		}
6177
6178		{
6179			// Attempt to route while setting max_total_routing_fee_msat to 149_999 results in a failure.
6180			let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6181				max_total_routing_fee_msat: Some(149_999) };
6182			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6183				&our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6184				&scorer, &Default::default(), &random_seed_bytes) {
6185					assert_eq!(err, "Failed to find a sufficient route to the given destination");
6186			} else { panic!(); }
6187		}
6188
6189		{
6190			// Now, attempt to route 200 sats (exact amount we can route).
6191			let route_params = RouteParameters { payment_params: payment_params.clone(), final_value_msat: 200_000,
6192				max_total_routing_fee_msat: Some(150_000) };
6193			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6194				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6195			assert_eq!(route.paths.len(), 2);
6196
6197			let mut total_amount_paid_msat = 0;
6198			for path in &route.paths {
6199				assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
6200				total_amount_paid_msat += path.final_value_msat();
6201			}
6202			assert_eq!(total_amount_paid_msat, 200_000);
6203			assert_eq!(route.get_total_fees(), 150_000);
6204		}
6205	}
6206
6207	#[test]
6208	fn mpp_with_last_hops() {
6209		// Previously, if we tried to send an MPP payment to a destination which was only reachable
6210		// via a single last-hop route hint, we'd fail to route if we first collected routes
6211		// totaling close but not quite enough to fund the full payment.
6212		//
6213		// This was because we considered last-hop hints to have exactly the sought payment amount
6214		// instead of the amount we were trying to collect, needlessly limiting our path searching
6215		// at the very first hop.
6216		//
6217		// Specifically, this interacted with our "all paths must fund at least 5% of total target"
6218		// criterion to cause us to refuse all routes at the last hop hint which would be considered
6219		// to only have the remaining to-collect amount in available liquidity.
6220		//
6221		// This bug appeared in production in some specific channel configurations.
6222		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6223		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6224		let scorer = ln_test_utils::TestScorer::new();
6225		let random_seed_bytes = [42; 32];
6226		let config = UserConfig::default();
6227		let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42)
6228			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
6229			.with_route_hints(vec![RouteHint(vec![RouteHintHop {
6230				src_node_id: nodes[2],
6231				short_channel_id: 42,
6232				fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
6233				cltv_expiry_delta: 42,
6234				htlc_minimum_msat: None,
6235				htlc_maximum_msat: None,
6236			}])]).unwrap().with_max_channel_saturation_power_of_half(0);
6237
6238		// Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
6239		// no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
6240		// would first use the no-fee route and then fail to find a path along the second route as
6241		// we think we can only send up to 1 additional sat over the last-hop but refuse to as its
6242		// under 5% of our payment amount.
6243		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6244			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6245			short_channel_id: 1,
6246			timestamp: 2,
6247			message_flags: 1, // Only must_be_one
6248			channel_flags: 0,
6249			cltv_expiry_delta: (5 << 4) | 5,
6250			htlc_minimum_msat: 0,
6251			htlc_maximum_msat: 99_000,
6252			fee_base_msat: u32::max_value(),
6253			fee_proportional_millionths: u32::max_value(),
6254			excess_data: Vec::new()
6255		});
6256		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6257			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6258			short_channel_id: 2,
6259			timestamp: 2,
6260			message_flags: 1, // Only must_be_one
6261			channel_flags: 0,
6262			cltv_expiry_delta: (5 << 4) | 3,
6263			htlc_minimum_msat: 0,
6264			htlc_maximum_msat: 99_000,
6265			fee_base_msat: u32::max_value(),
6266			fee_proportional_millionths: u32::max_value(),
6267			excess_data: Vec::new()
6268		});
6269		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6270			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6271			short_channel_id: 4,
6272			timestamp: 2,
6273			message_flags: 1, // Only must_be_one
6274			channel_flags: 0,
6275			cltv_expiry_delta: (4 << 4) | 1,
6276			htlc_minimum_msat: 0,
6277			htlc_maximum_msat: MAX_VALUE_MSAT,
6278			fee_base_msat: 1,
6279			fee_proportional_millionths: 0,
6280			excess_data: Vec::new()
6281		});
6282		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6283			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6284			short_channel_id: 13,
6285			timestamp: 2,
6286			message_flags: 1, // Only must_be_one
6287			channel_flags: 0|2, // Channel disabled
6288			cltv_expiry_delta: (13 << 4) | 1,
6289			htlc_minimum_msat: 0,
6290			htlc_maximum_msat: MAX_VALUE_MSAT,
6291			fee_base_msat: 0,
6292			fee_proportional_millionths: 2000000,
6293			excess_data: Vec::new()
6294		});
6295
6296		// Get a route for 100 sats and check that we found the MPP route no problem and didn't
6297		// overpay at all.
6298		let route_params = RouteParameters::from_payment_params_and_value(
6299			payment_params, 100_000);
6300		let mut route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6301			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6302		assert_eq!(route.paths.len(), 2);
6303		route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
6304		// Paths are manually ordered ordered by SCID, so:
6305		// * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
6306		// * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
6307		assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
6308		assert_eq!(route.paths[0].hops[0].fee_msat, 0);
6309		assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
6310		assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
6311		assert_eq!(route.paths[1].hops[0].fee_msat, 1);
6312		assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
6313		assert_eq!(route.get_total_fees(), 1);
6314		assert_eq!(route.get_total_amount(), 100_000);
6315	}
6316
6317	#[test]
6318	fn drop_lowest_channel_mpp_route_test() {
6319		// This test checks that low-capacity channel is dropped when after
6320		// path finding we realize that we found more capacity than we need.
6321		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6322		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6323		let scorer = ln_test_utils::TestScorer::new();
6324		let random_seed_bytes = [42; 32];
6325		let config = UserConfig::default();
6326		let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6327			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6328			.unwrap()
6329			.with_max_channel_saturation_power_of_half(0);
6330
6331		// We need a route consisting of 3 paths:
6332		// From our node to node2 via node0, node7, node1 (three paths one hop each).
6333
6334		// The first and the second paths should be sufficient, but the third should be
6335		// cheaper, so that we select it but drop later.
6336
6337		// First, we set limits on these (previously unlimited) channels.
6338		// Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
6339
6340		// Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
6341		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6342			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6343			short_channel_id: 1,
6344			timestamp: 2,
6345			message_flags: 1, // Only must_be_one
6346			channel_flags: 0,
6347			cltv_expiry_delta: 0,
6348			htlc_minimum_msat: 0,
6349			htlc_maximum_msat: 100_000,
6350			fee_base_msat: 0,
6351			fee_proportional_millionths: 0,
6352			excess_data: Vec::new()
6353		});
6354		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
6355			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6356			short_channel_id: 3,
6357			timestamp: 2,
6358			message_flags: 1, // Only must_be_one
6359			channel_flags: 0,
6360			cltv_expiry_delta: 0,
6361			htlc_minimum_msat: 0,
6362			htlc_maximum_msat: 50_000,
6363			fee_base_msat: 100,
6364			fee_proportional_millionths: 0,
6365			excess_data: Vec::new()
6366		});
6367
6368		// Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
6369		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6370			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6371			short_channel_id: 12,
6372			timestamp: 2,
6373			message_flags: 1, // Only must_be_one
6374			channel_flags: 0,
6375			cltv_expiry_delta: 0,
6376			htlc_minimum_msat: 0,
6377			htlc_maximum_msat: 60_000,
6378			fee_base_msat: 100,
6379			fee_proportional_millionths: 0,
6380			excess_data: Vec::new()
6381		});
6382		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
6383			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6384			short_channel_id: 13,
6385			timestamp: 2,
6386			message_flags: 1, // Only must_be_one
6387			channel_flags: 0,
6388			cltv_expiry_delta: 0,
6389			htlc_minimum_msat: 0,
6390			htlc_maximum_msat: 60_000,
6391			fee_base_msat: 0,
6392			fee_proportional_millionths: 0,
6393			excess_data: Vec::new()
6394		});
6395
6396		// Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
6397		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6398			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6399			short_channel_id: 2,
6400			timestamp: 2,
6401			message_flags: 1, // Only must_be_one
6402			channel_flags: 0,
6403			cltv_expiry_delta: 0,
6404			htlc_minimum_msat: 0,
6405			htlc_maximum_msat: 20_000,
6406			fee_base_msat: 0,
6407			fee_proportional_millionths: 0,
6408			excess_data: Vec::new()
6409		});
6410		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6411			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6412			short_channel_id: 4,
6413			timestamp: 2,
6414			message_flags: 1, // Only must_be_one
6415			channel_flags: 0,
6416			cltv_expiry_delta: 0,
6417			htlc_minimum_msat: 0,
6418			htlc_maximum_msat: 20_000,
6419			fee_base_msat: 0,
6420			fee_proportional_millionths: 0,
6421			excess_data: Vec::new()
6422		});
6423
6424		{
6425			// Attempt to route more than available results in a failure.
6426			let route_params = RouteParameters::from_payment_params_and_value(
6427				payment_params.clone(), 150_000);
6428			if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
6429					&our_id, &route_params, &network_graph.read_only(), None, Arc::clone(&logger),
6430					&scorer, &Default::default(), &random_seed_bytes) {
6431						assert_eq!(err, "Failed to find a sufficient route to the given destination");
6432			} else { panic!(); }
6433		}
6434
6435		{
6436			// Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
6437			// Our algorithm should provide us with these 3 paths.
6438			let route_params = RouteParameters::from_payment_params_and_value(
6439				payment_params.clone(), 125_000);
6440			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6441				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6442			assert_eq!(route.paths.len(), 3);
6443			let mut total_amount_paid_msat = 0;
6444			for path in &route.paths {
6445				assert_eq!(path.hops.len(), 2);
6446				assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6447				total_amount_paid_msat += path.final_value_msat();
6448			}
6449			assert_eq!(total_amount_paid_msat, 125_000);
6450		}
6451
6452		{
6453			// Attempt to route without the last small cheap channel
6454			let route_params = RouteParameters::from_payment_params_and_value(
6455				payment_params, 90_000);
6456			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6457				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6458			assert_eq!(route.paths.len(), 2);
6459			let mut total_amount_paid_msat = 0;
6460			for path in &route.paths {
6461				assert_eq!(path.hops.len(), 2);
6462				assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
6463				total_amount_paid_msat += path.final_value_msat();
6464			}
6465			assert_eq!(total_amount_paid_msat, 90_000);
6466		}
6467	}
6468
6469	#[test]
6470	fn min_criteria_consistency() {
6471		// Test that we don't use an inconsistent metric between updating and walking nodes during
6472		// our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
6473		// was updated with a different criterion from the heap sorting, resulting in loops in
6474		// calculated paths. We test for that specific case here.
6475
6476		// We construct a network that looks like this:
6477		//
6478		//            node2 -1(3)2- node3
6479		//              2          2
6480		//               (2)     (4)
6481		//                  1   1
6482		//    node1 -1(5)2- node4 -1(1)2- node6
6483		//    2
6484		//   (6)
6485		//	  1
6486		// our_node
6487		//
6488		// We create a loop on the side of our real path - our destination is node 6, with a
6489		// previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
6490		// followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
6491		// (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
6492		// other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
6493		// payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
6494		// "previous hop" being set to node 3, creating a loop in the path.
6495		let secp_ctx = Secp256k1::new();
6496		let logger = Arc::new(ln_test_utils::TestLogger::new());
6497		let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6498		let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
6499		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6500		let scorer = ln_test_utils::TestScorer::new();
6501		let random_seed_bytes = [42; 32];
6502		let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
6503
6504		add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
6505		for (key, channel_flags) in [(&our_privkey, 0), (&privkeys[1], 3)] {
6506			update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6507				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6508				short_channel_id: 6,
6509				timestamp: 1,
6510				message_flags: 1, // Only must_be_one
6511				channel_flags,
6512				cltv_expiry_delta: (6 << 4) | 0,
6513				htlc_minimum_msat: 0,
6514				htlc_maximum_msat: MAX_VALUE_MSAT,
6515				fee_base_msat: 0,
6516				fee_proportional_millionths: 0,
6517				excess_data: Vec::new()
6518			});
6519		}
6520		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
6521
6522		add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
6523		for (key, channel_flags) in [(&privkeys[1], 0), (&privkeys[4], 3)] {
6524			update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6525				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6526				short_channel_id: 5,
6527				timestamp: 1,
6528				message_flags: 1, // Only must_be_one
6529				channel_flags,
6530				cltv_expiry_delta: (5 << 4) | 0,
6531				htlc_minimum_msat: 0,
6532				htlc_maximum_msat: MAX_VALUE_MSAT,
6533				fee_base_msat: 100,
6534				fee_proportional_millionths: 0,
6535				excess_data: Vec::new()
6536			});
6537		}
6538		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
6539
6540		add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
6541		for (key, channel_flags) in [(&privkeys[4], 0), (&privkeys[3], 3)] {
6542			update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6543				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6544				short_channel_id: 4,
6545				timestamp: 1,
6546				message_flags: 1, // Only must_be_one
6547				channel_flags,
6548				cltv_expiry_delta: (4 << 4) | 0,
6549				htlc_minimum_msat: 0,
6550				htlc_maximum_msat: MAX_VALUE_MSAT,
6551				fee_base_msat: 0,
6552				fee_proportional_millionths: 0,
6553				excess_data: Vec::new()
6554			});
6555		}
6556		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
6557
6558		add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
6559		for (key, channel_flags) in [(&privkeys[3], 0), (&privkeys[2], 3)] {
6560			update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6561				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6562				short_channel_id: 3,
6563				timestamp: 1,
6564				message_flags: 1, // Only must_be_one
6565				channel_flags,
6566				cltv_expiry_delta: (3 << 4) | 0,
6567				htlc_minimum_msat: 0,
6568				htlc_maximum_msat: MAX_VALUE_MSAT,
6569				fee_base_msat: 0,
6570				fee_proportional_millionths: 0,
6571				excess_data: Vec::new()
6572			});
6573		}
6574		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
6575
6576		add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
6577		for (key, channel_flags) in [(&privkeys[2], 0), (&privkeys[4], 3)] {
6578			update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6579				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6580				short_channel_id: 2,
6581				timestamp: 1,
6582				message_flags: 1, // Only must_be_one
6583				channel_flags,
6584				cltv_expiry_delta: (2 << 4) | 0,
6585				htlc_minimum_msat: 0,
6586				htlc_maximum_msat: MAX_VALUE_MSAT,
6587				fee_base_msat: 0,
6588				fee_proportional_millionths: 0,
6589				excess_data: Vec::new()
6590			});
6591		}
6592
6593		add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
6594		for (key, channel_flags) in [(&privkeys[4], 0), (&privkeys[6], 3)] {
6595			update_channel(&gossip_sync, &secp_ctx, key, UnsignedChannelUpdate {
6596				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6597				short_channel_id: 1,
6598				timestamp: 1,
6599				message_flags: 1, // Only must_be_one
6600				channel_flags,
6601				cltv_expiry_delta: (1 << 4) | 0,
6602				htlc_minimum_msat: 100,
6603				htlc_maximum_msat: MAX_VALUE_MSAT,
6604				fee_base_msat: 0,
6605				fee_proportional_millionths: 0,
6606				excess_data: Vec::new()
6607			});
6608		}
6609		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
6610
6611		{
6612			// Now ensure the route flows simply over nodes 1 and 4 to 6.
6613			let route_params = RouteParameters::from_payment_params_and_value(
6614				payment_params, 10_000);
6615			let route = get_route(&our_id, &route_params, &network.read_only(), None,
6616				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6617			assert_eq!(route.paths.len(), 1);
6618			assert_eq!(route.paths[0].hops.len(), 3);
6619
6620			assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
6621			assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6622			assert_eq!(route.paths[0].hops[0].fee_msat, 100);
6623			assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
6624			assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
6625			assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
6626
6627			assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
6628			assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
6629			assert_eq!(route.paths[0].hops[1].fee_msat, 0);
6630			assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
6631			assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
6632			assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
6633
6634			assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
6635			assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
6636			assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
6637			assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
6638			assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
6639			assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
6640		}
6641	}
6642
6643
6644	#[test]
6645	fn exact_fee_liquidity_limit() {
6646		// Test that if, while walking the graph, we find a hop that has exactly enough liquidity
6647		// for us, including later hop fees, we take it. In the first version of our MPP algorithm
6648		// we calculated fees on a higher value, resulting in us ignoring such paths.
6649		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6650		let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
6651		let scorer = ln_test_utils::TestScorer::new();
6652		let random_seed_bytes = [42; 32];
6653		let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
6654
6655		// We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
6656		// send.
6657		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6658			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6659			short_channel_id: 2,
6660			timestamp: 2,
6661			message_flags: 1, // Only must_be_one
6662			channel_flags: 0,
6663			cltv_expiry_delta: 0,
6664			htlc_minimum_msat: 0,
6665			htlc_maximum_msat: 85_000,
6666			fee_base_msat: 0,
6667			fee_proportional_millionths: 0,
6668			excess_data: Vec::new()
6669		});
6670
6671		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6672			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6673			short_channel_id: 12,
6674			timestamp: 2,
6675			message_flags: 1, // Only must_be_one
6676			channel_flags: 0,
6677			cltv_expiry_delta: (4 << 4) | 1,
6678			htlc_minimum_msat: 0,
6679			htlc_maximum_msat: 270_000,
6680			fee_base_msat: 0,
6681			fee_proportional_millionths: 1000000,
6682			excess_data: Vec::new()
6683		});
6684
6685		{
6686			// Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
6687			// 200% fee charged channel 13 in the 1-to-2 direction.
6688			let mut route_params = RouteParameters::from_payment_params_and_value(
6689				payment_params, 90_000);
6690			route_params.max_total_routing_fee_msat = Some(90_000*2);
6691			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6692				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6693			assert_eq!(route.paths.len(), 1);
6694			assert_eq!(route.paths[0].hops.len(), 2);
6695
6696			assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6697			assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6698			assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6699			assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6700			assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6701			assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6702
6703			assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6704			assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6705			assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6706			assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6707			assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
6708			assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6709		}
6710	}
6711
6712	#[test]
6713	fn htlc_max_reduction_below_min() {
6714		// Test that if, while walking the graph, we reduce the value being sent to meet an
6715		// htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
6716		// initial version of MPP we'd accept such routes but reject them while recalculating fees,
6717		// resulting in us thinking there is no possible path, even if other paths exist.
6718		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
6719		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
6720		let scorer = ln_test_utils::TestScorer::new();
6721		let random_seed_bytes = [42; 32];
6722		let config = UserConfig::default();
6723		let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
6724			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6725			.unwrap();
6726
6727		// We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
6728		// gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
6729		// then try to send 90_000.
6730		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
6731			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6732			short_channel_id: 2,
6733			timestamp: 2,
6734			message_flags: 1, // Only must_be_one
6735			channel_flags: 0,
6736			cltv_expiry_delta: 0,
6737			htlc_minimum_msat: 0,
6738			htlc_maximum_msat: 80_000,
6739			fee_base_msat: 0,
6740			fee_proportional_millionths: 0,
6741			excess_data: Vec::new()
6742		});
6743		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
6744			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
6745			short_channel_id: 4,
6746			timestamp: 2,
6747			message_flags: 1, // Only must_be_one
6748			channel_flags: 0,
6749			cltv_expiry_delta: (4 << 4) | 1,
6750			htlc_minimum_msat: 90_000,
6751			htlc_maximum_msat: MAX_VALUE_MSAT,
6752			fee_base_msat: 0,
6753			fee_proportional_millionths: 0,
6754			excess_data: Vec::new()
6755		});
6756
6757		{
6758			// Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
6759			// overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
6760			// expensive) channels 12-13 path.
6761			let mut route_params = RouteParameters::from_payment_params_and_value(
6762				payment_params, 90_000);
6763			route_params.max_total_routing_fee_msat = Some(90_000*2);
6764			let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
6765				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6766			assert_eq!(route.paths.len(), 1);
6767			assert_eq!(route.paths[0].hops.len(), 2);
6768
6769			assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
6770			assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
6771			assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
6772			assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
6773			assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
6774			assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
6775
6776			assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
6777			assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
6778			assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
6779			assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
6780			assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_bolt11_invoice_features(&config).le_flags());
6781			assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
6782		}
6783	}
6784
6785	#[test]
6786	fn multiple_direct_first_hops() {
6787		// Previously we'd only ever considered one first hop path per counterparty.
6788		// However, as we don't restrict users to one channel per peer, we really need to support
6789		// looking at all first hop paths.
6790		// Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
6791		// we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
6792		// route over multiple channels with the same first hop.
6793		let secp_ctx = Secp256k1::new();
6794		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6795		let logger = Arc::new(ln_test_utils::TestLogger::new());
6796		let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
6797		let scorer = ln_test_utils::TestScorer::new();
6798		let config = UserConfig::default();
6799		let payment_params = PaymentParameters::from_node_id(nodes[0], 42)
6800			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
6801			.unwrap();
6802		let random_seed_bytes = [42; 32];
6803
6804		{
6805			let route_params = RouteParameters::from_payment_params_and_value(
6806				payment_params.clone(), 100_000);
6807			let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6808				&get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
6809				&get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
6810			]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6811			assert_eq!(route.paths.len(), 1);
6812			assert_eq!(route.paths[0].hops.len(), 1);
6813
6814			assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6815			assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
6816			assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6817		}
6818		{
6819			let route_params = RouteParameters::from_payment_params_and_value(
6820				payment_params.clone(), 100_000);
6821			let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6822				&get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6823				&get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6824			]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6825			assert_eq!(route.paths.len(), 2);
6826			assert_eq!(route.paths[0].hops.len(), 1);
6827			assert_eq!(route.paths[1].hops.len(), 1);
6828
6829			assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
6830				(route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
6831
6832			assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6833			assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
6834
6835			assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
6836			assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
6837		}
6838
6839		{
6840			// If we have a bunch of outbound channels to the same node, where most are not
6841			// sufficient to pay the full payment, but one is, we should default to just using the
6842			// one single channel that has sufficient balance, avoiding MPP.
6843			//
6844			// If we have several options above the 3xpayment value threshold, we should pick the
6845			// smallest of them, avoiding further fragmenting our available outbound balance to
6846			// this node.
6847			let route_params = RouteParameters::from_payment_params_and_value(
6848				payment_params, 100_000);
6849			let route = get_route(&our_id, &route_params, &network_graph.read_only(), Some(&[
6850				&get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6851				&get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6852				&get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6853				&get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
6854				&get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6855				&get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6856				&get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
6857				&get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
6858			]), Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6859			assert_eq!(route.paths.len(), 1);
6860			assert_eq!(route.paths[0].hops.len(), 1);
6861
6862			assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
6863			assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
6864			assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
6865		}
6866	}
6867
6868	#[test]
6869	fn prefers_shorter_route_with_higher_fees() {
6870		let (secp_ctx, network_graph, _, _, logger) = build_graph();
6871		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6872		let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6873
6874		// Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
6875		let scorer = ln_test_utils::TestScorer::new();
6876		let random_seed_bytes = [42; 32];
6877		let route_params = RouteParameters::from_payment_params_and_value(
6878			payment_params.clone(), 100);
6879		let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6880			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6881		let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6882
6883		assert_eq!(route.get_total_fees(), 100);
6884		assert_eq!(route.get_total_amount(), 100);
6885		assert_eq!(path, vec![2, 4, 6, 11, 8]);
6886
6887		// Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
6888		// from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
6889		let scorer = FixedPenaltyScorer::with_penalty(100);
6890		let route_params = RouteParameters::from_payment_params_and_value(
6891			payment_params, 100);
6892		let route = get_route( &our_id, &route_params, &network_graph.read_only(), None,
6893			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
6894		let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6895
6896		assert_eq!(route.get_total_fees(), 300);
6897		assert_eq!(route.get_total_amount(), 100);
6898		assert_eq!(path, vec![2, 4, 7, 10]);
6899	}
6900
6901	struct BadChannelScorer {
6902		short_channel_id: u64,
6903	}
6904
6905	#[cfg(c_bindings)]
6906	impl Writeable for BadChannelScorer {
6907		fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6908	}
6909	impl ScoreLookUp for BadChannelScorer {
6910		type ScoreParams = ();
6911		fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6912			if candidate.short_channel_id() == Some(self.short_channel_id) { u64::max_value()  } else { 0  }
6913		}
6914	}
6915
6916	struct BadNodeScorer {
6917		node_id: NodeId,
6918	}
6919
6920	#[cfg(c_bindings)]
6921	impl Writeable for BadNodeScorer {
6922		fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
6923	}
6924
6925	impl ScoreLookUp for BadNodeScorer {
6926		type ScoreParams = ();
6927		fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
6928			if candidate.target() == Some(self.node_id) { u64::max_value() } else { 0 }
6929		}
6930	}
6931
6932	#[test]
6933	fn avoids_routing_through_bad_channels_and_nodes() {
6934		let (secp_ctx, network, _, _, logger) = build_graph();
6935		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6936		let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
6937		let network_graph = network.read_only();
6938
6939		// A path to nodes[6] exists when no penalties are applied to any channel.
6940		let scorer = ln_test_utils::TestScorer::new();
6941		let random_seed_bytes = [42; 32];
6942		let route_params = RouteParameters::from_payment_params_and_value(
6943			payment_params, 100);
6944		let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6945			&scorer, &Default::default(), &random_seed_bytes).unwrap();
6946		let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6947
6948		assert_eq!(route.get_total_fees(), 100);
6949		assert_eq!(route.get_total_amount(), 100);
6950		assert_eq!(path, vec![2, 4, 6, 11, 8]);
6951
6952		// A different path to nodes[6] exists if channel 6 cannot be routed over.
6953		let scorer = BadChannelScorer { short_channel_id: 6 };
6954		let route = get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6955			&scorer, &Default::default(), &random_seed_bytes).unwrap();
6956		let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
6957
6958		assert_eq!(route.get_total_fees(), 300);
6959		assert_eq!(route.get_total_amount(), 100);
6960		assert_eq!(path, vec![2, 4, 7, 10]);
6961
6962		// A path to nodes[6] does not exist if nodes[2] cannot be routed through.
6963		let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
6964		match get_route( &our_id, &route_params, &network_graph, None, Arc::clone(&logger),
6965			&scorer, &Default::default(), &random_seed_bytes) {
6966				Err(LightningError { err, .. } ) => {
6967					assert_eq!(err, "Failed to find a path to the given destination");
6968				},
6969				Ok(_) => panic!("Expected error"),
6970		}
6971	}
6972
6973	#[test]
6974	fn total_fees_single_path() {
6975		let route = Route {
6976			paths: vec![Path { hops: vec![
6977				RouteHop {
6978					pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
6979					channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6980					short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
6981				},
6982				RouteHop {
6983					pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
6984					channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6985					short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
6986				},
6987				RouteHop {
6988					pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
6989					channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
6990					short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0, maybe_announced_channel: true,
6991				},
6992			], blinded_tail: None }],
6993			route_params: None,
6994		};
6995
6996		assert_eq!(route.get_total_fees(), 250);
6997		assert_eq!(route.get_total_amount(), 225);
6998	}
6999
7000	#[test]
7001	fn total_fees_multi_path() {
7002		let route = Route {
7003			paths: vec![Path { hops: vec![
7004				RouteHop {
7005					pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
7006					channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
7007					short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
7008				},
7009				RouteHop {
7010					pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
7011					channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
7012					short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
7013				},
7014			], blinded_tail: None }, Path { hops: vec![
7015				RouteHop {
7016					pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
7017					channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
7018					short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0, maybe_announced_channel: true,
7019				},
7020				RouteHop {
7021					pubkey: PublicKey::from_slice(&<Vec<u8>>::from_hex("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
7022					channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
7023					short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0, maybe_announced_channel: true,
7024				},
7025			], blinded_tail: None }],
7026			route_params: None,
7027		};
7028
7029		assert_eq!(route.get_total_fees(), 200);
7030		assert_eq!(route.get_total_amount(), 300);
7031	}
7032
7033	#[test]
7034	fn total_empty_route_no_panic() {
7035		// In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
7036		// would both panic if the route was completely empty. We test to ensure they return 0
7037		// here, even though its somewhat nonsensical as a route.
7038		let route = Route { paths: Vec::new(), route_params: None };
7039
7040		assert_eq!(route.get_total_fees(), 0);
7041		assert_eq!(route.get_total_amount(), 0);
7042	}
7043
7044	#[test]
7045	fn limits_total_cltv_delta() {
7046		let (secp_ctx, network, _, _, logger) = build_graph();
7047		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7048		let network_graph = network.read_only();
7049
7050		let scorer = ln_test_utils::TestScorer::new();
7051
7052		// Make sure that generally there is at least one route available
7053		let feasible_max_total_cltv_delta = 1008;
7054		let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
7055			.with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
7056		let random_seed_bytes = [42; 32];
7057		let route_params = RouteParameters::from_payment_params_and_value(
7058			feasible_payment_params, 100);
7059		let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7060			&scorer, &Default::default(), &random_seed_bytes).unwrap();
7061		let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
7062		assert_ne!(path.len(), 0);
7063
7064		// But not if we exclude all paths on the basis of their accumulated CLTV delta
7065		let fail_max_total_cltv_delta = 23;
7066		let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
7067			.with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
7068		let route_params = RouteParameters::from_payment_params_and_value(
7069			fail_payment_params, 100);
7070		match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7071			&Default::default(), &random_seed_bytes)
7072		{
7073			Err(LightningError { err, .. } ) => {
7074				assert_eq!(err, "Failed to find a path to the given destination");
7075			},
7076			Ok(_) => panic!("Expected error"),
7077		}
7078	}
7079
7080	#[test]
7081	fn avoids_recently_failed_paths() {
7082		// Ensure that the router always avoids all of the `previously_failed_channels` channels by
7083		// randomly inserting channels into it until we can't find a route anymore.
7084		let (secp_ctx, network, _, _, logger) = build_graph();
7085		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7086		let network_graph = network.read_only();
7087
7088		let scorer = ln_test_utils::TestScorer::new();
7089		let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
7090			.with_max_path_count(1);
7091		let random_seed_bytes = [42; 32];
7092
7093		// We should be able to find a route initially, and then after we fail a few random
7094		// channels eventually we won't be able to any longer.
7095		let route_params = RouteParameters::from_payment_params_and_value(
7096			payment_params.clone(), 100);
7097		assert!(get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7098			&scorer, &Default::default(), &random_seed_bytes).is_ok());
7099		loop {
7100			let route_params = RouteParameters::from_payment_params_and_value(
7101				payment_params.clone(), 100);
7102			if let Ok(route) = get_route(&our_id, &route_params, &network_graph, None,
7103				Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes)
7104			{
7105				for chan in route.paths[0].hops.iter() {
7106					assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
7107				}
7108				let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
7109					% route.paths[0].hops.len();
7110				payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
7111			} else { break; }
7112		}
7113	}
7114
7115	#[test]
7116	fn limits_path_length() {
7117		let (secp_ctx, network, _, _, logger) = build_line_graph();
7118		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7119		let network_graph = network.read_only();
7120
7121		let scorer = ln_test_utils::TestScorer::new();
7122		let random_seed_bytes = [42; 32];
7123
7124		// First check we can actually create a long route on this graph.
7125		let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
7126		let route_params = RouteParameters::from_payment_params_and_value(
7127			feasible_payment_params, 100);
7128		let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7129			&scorer, &Default::default(), &random_seed_bytes).unwrap();
7130		let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
7131		assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
7132
7133		// But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
7134		let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
7135		let route_params = RouteParameters::from_payment_params_and_value(
7136			fail_payment_params, 100);
7137		match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7138			&Default::default(), &random_seed_bytes)
7139		{
7140			Err(LightningError { err, .. } ) => {
7141				assert_eq!(err, "Failed to find a path to the given destination");
7142			},
7143			Ok(_) => panic!("Expected error"),
7144		}
7145	}
7146
7147	#[test]
7148	fn adds_and_limits_cltv_offset() {
7149		let (secp_ctx, network_graph, _, _, logger) = build_graph();
7150		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7151
7152		let scorer = ln_test_utils::TestScorer::new();
7153
7154		let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
7155		let random_seed_bytes = [42; 32];
7156		let route_params = RouteParameters::from_payment_params_and_value(
7157			payment_params.clone(), 100);
7158		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7159			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
7160		assert_eq!(route.paths.len(), 1);
7161
7162		let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
7163
7164		// Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
7165		let mut route_default = route.clone();
7166		add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
7167		let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
7168		assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
7169		assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
7170		assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
7171
7172		// Check that no offset is added when we restrict the max_total_cltv_expiry_delta
7173		let mut route_limited = route.clone();
7174		let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
7175		let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
7176		add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
7177		let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
7178		assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
7179	}
7180
7181	#[test]
7182	fn adds_plausible_cltv_offset() {
7183		let (secp_ctx, network, _, _, logger) = build_graph();
7184		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7185		let network_graph = network.read_only();
7186		let network_nodes = network_graph.nodes();
7187		let network_channels = network_graph.channels();
7188		let scorer = ln_test_utils::TestScorer::new();
7189		let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7190		let random_seed_bytes = [42; 32];
7191
7192		let route_params = RouteParameters::from_payment_params_and_value(
7193			payment_params.clone(), 100);
7194		let mut route = get_route(&our_id, &route_params, &network_graph, None,
7195			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
7196		add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
7197
7198		let mut path_plausibility = vec![];
7199
7200		for p in route.paths {
7201			// 1. Select random observation point
7202			let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
7203			let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
7204
7205			prng.process_in_place(&mut random_bytes);
7206			let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
7207			let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
7208
7209			// 2. Calculate what CLTV expiry delta we would observe there
7210			let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
7211
7212			// 3. Starting from the observation point, find candidate paths
7213			let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
7214			candidates.push_back((observation_point, vec![]));
7215
7216			let mut found_plausible_candidate = false;
7217
7218			'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
7219				if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
7220					if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
7221						found_plausible_candidate = true;
7222						break 'candidate_loop;
7223					}
7224				}
7225
7226				if let Some(cur_node) = network_nodes.get(&cur_node_id) {
7227					for channel_id in &cur_node.channels {
7228						if let Some(channel_info) = network_channels.get(&channel_id) {
7229							if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
7230								let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
7231								if cur_path_cltv_deltas.iter().sum::<u32>()
7232									.saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
7233									let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
7234									new_path_cltv_deltas.push(next_cltv_expiry_delta);
7235									candidates.push_back((*next_id, new_path_cltv_deltas));
7236								}
7237							}
7238						}
7239					}
7240				}
7241			}
7242
7243			path_plausibility.push(found_plausible_candidate);
7244		}
7245		assert!(path_plausibility.iter().all(|x| *x));
7246	}
7247
7248	#[test]
7249	fn builds_correct_path_from_hops() {
7250		let (secp_ctx, network, _, _, logger) = build_graph();
7251		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7252		let network_graph = network.read_only();
7253
7254		let random_seed_bytes = [42; 32];
7255		let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
7256		let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
7257		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 100);
7258		let route = build_route_from_hops_internal(&our_id, &hops, &route_params, &network_graph,
7259			Arc::clone(&logger), &random_seed_bytes).unwrap();
7260		let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
7261		assert_eq!(hops.len(), route.paths[0].hops.len());
7262		for (idx, hop_pubkey) in hops.iter().enumerate() {
7263			assert!(*hop_pubkey == route_hop_pubkeys[idx]);
7264		}
7265	}
7266
7267	#[test]
7268	fn avoids_saturating_channels() {
7269		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
7270		let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
7271		let decay_params = ProbabilisticScoringDecayParameters::default();
7272		let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
7273
7274		// Set the fee on channel 13 to 0% to match channel 4 giving us two equivalent paths (us
7275		// -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
7276		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7277			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7278			short_channel_id: 4,
7279			timestamp: 2,
7280			message_flags: 1, // Only must_be_one
7281			channel_flags: 0,
7282			cltv_expiry_delta: (4 << 4) | 1,
7283			htlc_minimum_msat: 0,
7284			htlc_maximum_msat: 250_000_000,
7285			fee_base_msat: 0,
7286			fee_proportional_millionths: 0,
7287			excess_data: Vec::new()
7288		});
7289		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
7290			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7291			short_channel_id: 13,
7292			timestamp: 2,
7293			message_flags: 1, // Only must_be_one
7294			channel_flags: 0,
7295			cltv_expiry_delta: (13 << 4) | 1,
7296			htlc_minimum_msat: 0,
7297			htlc_maximum_msat: 250_000_000,
7298			fee_base_msat: 0,
7299			fee_proportional_millionths: 0,
7300			excess_data: Vec::new()
7301		});
7302
7303		let config = UserConfig::default();
7304		let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
7305			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7306			.unwrap();
7307		let random_seed_bytes = [42; 32];
7308
7309		// 75,000 sats is less than the available liquidity on each channel, set above, when
7310		// applying max_channel_saturation_power_of_half. This value also ensures the cost of paths
7311		// considered when applying max_channel_saturation_power_of_half is less than the cost of
7312		// those when it is not applied.
7313		let route_params = RouteParameters::from_payment_params_and_value(
7314			payment_params, 75_000_000);
7315		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
7316			Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
7317		assert_eq!(route.paths.len(), 2);
7318		assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
7319			(route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
7320	}
7321
7322	pub(super) fn random_init_seed() -> u64 {
7323		// Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
7324		use core::hash::{BuildHasher, Hasher};
7325		let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
7326		println!("Using seed of {}", seed);
7327		seed
7328	}
7329
7330	#[test]
7331	fn generate_routes() {
7332		use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7333
7334		let logger = ln_test_utils::TestLogger::new();
7335		let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7336			Ok(res) => res,
7337			Err(e) => {
7338				eprintln!("{}", e);
7339				return;
7340			},
7341		};
7342
7343		let params = ProbabilisticScoringFeeParameters::default();
7344		let features = super::Bolt11InvoiceFeatures::empty();
7345
7346		super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
7347	}
7348
7349	#[test]
7350	fn generate_routes_mpp() {
7351		use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7352
7353		let logger = ln_test_utils::TestLogger::new();
7354		let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7355			Ok(res) => res,
7356			Err(e) => {
7357				eprintln!("{}", e);
7358				return;
7359			},
7360		};
7361
7362		let params = ProbabilisticScoringFeeParameters::default();
7363		let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7364
7365		super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
7366	}
7367
7368	#[test]
7369	fn generate_large_mpp_routes() {
7370		use crate::routing::scoring::ProbabilisticScoringFeeParameters;
7371
7372		let logger = ln_test_utils::TestLogger::new();
7373		let (graph, mut scorer) = match super::bench_utils::read_graph_scorer(&logger) {
7374			Ok(res) => res,
7375			Err(e) => {
7376				eprintln!("{}", e);
7377				return;
7378			},
7379		};
7380
7381		let params = ProbabilisticScoringFeeParameters::default();
7382		let features = channelmanager::provided_bolt11_invoice_features(&UserConfig::default());
7383
7384		super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 1_000_000, 2);
7385	}
7386
7387	#[test]
7388	fn honors_manual_penalties() {
7389		let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
7390		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7391
7392		let random_seed_bytes = [42; 32];
7393		let mut scorer_params = ProbabilisticScoringFeeParameters::default();
7394		let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
7395
7396		// First check set manual penalties are returned by the scorer.
7397		let usage = ChannelUsage {
7398			amount_msat: 0,
7399			inflight_htlc_msat: 0,
7400			effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
7401		};
7402		scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
7403		scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
7404		let network_graph = network_graph.read_only();
7405		let channels = network_graph.channels();
7406		let channel = channels.get(&5).unwrap();
7407		let info = channel.as_directed_from(&NodeId::from_pubkey(&nodes[3])).unwrap();
7408		let candidate: CandidateRouteHop = CandidateRouteHop::PublicHop(PublicHopCandidate {
7409			info: info.0,
7410			short_channel_id: 5,
7411		});
7412		assert_eq!(scorer.channel_penalty_msat(&candidate, usage, &scorer_params), 456);
7413
7414		// Then check we can get a normal route
7415		let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
7416		let route_params = RouteParameters::from_payment_params_and_value(
7417			payment_params, 100);
7418		let route = get_route(&our_id, &route_params, &network_graph, None,
7419			Arc::clone(&logger), &scorer, &scorer_params, &random_seed_bytes);
7420		assert!(route.is_ok());
7421
7422		// Then check that we can't get a route if we ban an intermediate node.
7423		scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
7424		let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7425		assert!(route.is_err());
7426
7427		// Finally make sure we can route again, when we remove the ban.
7428		scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
7429		let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
7430		assert!(route.is_ok());
7431	}
7432
7433	#[test]
7434	fn abide_by_route_hint_max_htlc() {
7435		// Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
7436		// params in the final route.
7437		let (secp_ctx, network_graph, _, _, logger) = build_graph();
7438		let netgraph = network_graph.read_only();
7439		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7440		let scorer = ln_test_utils::TestScorer::new();
7441		let random_seed_bytes = [42; 32];
7442		let config = UserConfig::default();
7443
7444		let max_htlc_msat = 50_000;
7445		let route_hint_1 = RouteHint(vec![RouteHintHop {
7446			src_node_id: nodes[2],
7447			short_channel_id: 42,
7448			fees: RoutingFees {
7449				base_msat: 100,
7450				proportional_millionths: 0,
7451			},
7452			cltv_expiry_delta: 10,
7453			htlc_minimum_msat: None,
7454			htlc_maximum_msat: Some(max_htlc_msat),
7455		}]);
7456		let dest_node_id = ln_test_utils::pubkey(42);
7457		let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7458			.with_route_hints(vec![route_hint_1.clone()]).unwrap()
7459			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7460			.unwrap();
7461
7462		// Make sure we'll error if our route hints don't have enough liquidity according to their
7463		// htlc_maximum_msat.
7464		let mut route_params = RouteParameters::from_payment_params_and_value(
7465			payment_params, max_htlc_msat + 1);
7466		route_params.max_total_routing_fee_msat = None;
7467		if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
7468			&route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(),
7469			&random_seed_bytes)
7470		{
7471			assert_eq!(err, "Failed to find a sufficient route to the given destination");
7472		} else { panic!(); }
7473
7474		// Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
7475		let mut route_hint_2 = route_hint_1.clone();
7476		route_hint_2.0[0].short_channel_id = 43;
7477		let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7478			.with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7479			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7480			.unwrap();
7481		let mut route_params = RouteParameters::from_payment_params_and_value(
7482			payment_params, max_htlc_msat + 1);
7483		route_params.max_total_routing_fee_msat = Some(max_htlc_msat * 2);
7484		let route = get_route(&our_id, &route_params, &netgraph, None, Arc::clone(&logger),
7485			&scorer, &Default::default(), &random_seed_bytes).unwrap();
7486		assert_eq!(route.paths.len(), 2);
7487		assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7488		assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7489	}
7490
7491	#[test]
7492	fn direct_channel_to_hints_with_max_htlc() {
7493		// Check that if we have a first hop channel peer that's connected to multiple provided route
7494		// hints, that we properly split the payment between the route hints if needed.
7495		let logger = Arc::new(ln_test_utils::TestLogger::new());
7496		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7497		let scorer = ln_test_utils::TestScorer::new();
7498		let random_seed_bytes = [42; 32];
7499		let config = UserConfig::default();
7500
7501		let our_node_id = ln_test_utils::pubkey(42);
7502		let intermed_node_id = ln_test_utils::pubkey(43);
7503		let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7504
7505		let amt_msat = 900_000;
7506		let max_htlc_msat = 500_000;
7507		let route_hint_1 = RouteHint(vec![RouteHintHop {
7508			src_node_id: intermed_node_id,
7509			short_channel_id: 44,
7510			fees: RoutingFees {
7511				base_msat: 100,
7512				proportional_millionths: 0,
7513			},
7514			cltv_expiry_delta: 10,
7515			htlc_minimum_msat: None,
7516			htlc_maximum_msat: Some(max_htlc_msat),
7517		}, RouteHintHop {
7518			src_node_id: intermed_node_id,
7519			short_channel_id: 45,
7520			fees: RoutingFees {
7521				base_msat: 100,
7522				proportional_millionths: 0,
7523			},
7524			cltv_expiry_delta: 10,
7525			htlc_minimum_msat: None,
7526			// Check that later route hint max htlcs don't override earlier ones
7527			htlc_maximum_msat: Some(max_htlc_msat - 50),
7528		}]);
7529		let mut route_hint_2 = route_hint_1.clone();
7530		route_hint_2.0[0].short_channel_id = 46;
7531		route_hint_2.0[1].short_channel_id = 47;
7532		let dest_node_id = ln_test_utils::pubkey(44);
7533		let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
7534			.with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
7535			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
7536			.unwrap();
7537
7538		let route_params = RouteParameters::from_payment_params_and_value(
7539			payment_params, amt_msat);
7540		let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7541			Some(&first_hop.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7542			&Default::default(), &random_seed_bytes).unwrap();
7543		assert_eq!(route.paths.len(), 2);
7544		assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7545		assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7546		assert_eq!(route.get_total_amount(), amt_msat);
7547
7548		// Re-run but with two first hop channels connected to the same route hint peers that must be
7549		// split between.
7550		let first_hops = vec![
7551			get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7552			get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
7553		];
7554		let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7555			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7556			&Default::default(), &random_seed_bytes).unwrap();
7557		assert_eq!(route.paths.len(), 2);
7558		assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7559		assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7560		assert_eq!(route.get_total_amount(), amt_msat);
7561
7562		// Make sure this works for blinded route hints.
7563		let blinded_payinfo = BlindedPayInfo {
7564			fee_base_msat: 100,
7565			fee_proportional_millionths: 0,
7566			htlc_minimum_msat: 1,
7567			htlc_maximum_msat: max_htlc_msat,
7568			cltv_expiry_delta: 10,
7569			features: BlindedHopFeatures::empty(),
7570		};
7571		let blinded_path = dummy_blinded_path(intermed_node_id, blinded_payinfo);
7572		let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7573		let payment_params = PaymentParameters::blinded(vec![
7574			blinded_path.clone(), blinded_path.clone()
7575		]).with_bolt12_features(bolt12_features).unwrap();
7576		let route_params = RouteParameters::from_payment_params_and_value(
7577			payment_params, amt_msat);
7578		let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
7579			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7580			&Default::default(), &random_seed_bytes).unwrap();
7581		assert_eq!(route.paths.len(), 2);
7582		assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
7583		assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
7584		assert_eq!(route.get_total_amount(), amt_msat);
7585	}
7586
7587	#[test]
7588	fn blinded_route_ser() {
7589		// (De)serialize a Route with 1 blinded path out of two total paths.
7590		let mut route = Route { paths: vec![Path {
7591			hops: vec![RouteHop {
7592				pubkey: ln_test_utils::pubkey(50),
7593				node_features: NodeFeatures::empty(),
7594				short_channel_id: 42,
7595				channel_features: ChannelFeatures::empty(),
7596				fee_msat: 100,
7597				cltv_expiry_delta: 0,
7598				maybe_announced_channel: true,
7599			}],
7600			blinded_tail: Some(BlindedTail {
7601				hops: vec![
7602					BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
7603					BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
7604				],
7605				blinding_point: ln_test_utils::pubkey(43),
7606				excess_final_cltv_expiry_delta: 40,
7607				final_value_msat: 100,
7608			})}, Path {
7609			hops: vec![RouteHop {
7610				pubkey: ln_test_utils::pubkey(51),
7611				node_features: NodeFeatures::empty(),
7612				short_channel_id: 43,
7613				channel_features: ChannelFeatures::empty(),
7614				fee_msat: 100,
7615				cltv_expiry_delta: 0,
7616				maybe_announced_channel: true,
7617			}], blinded_tail: None }],
7618			route_params: None,
7619		};
7620		let encoded_route = route.encode();
7621		let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7622		assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7623		assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7624
7625		// (De)serialize a Route with two paths, each containing a blinded tail.
7626		route.paths[1].blinded_tail = Some(BlindedTail {
7627			hops: vec![
7628				BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
7629				BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
7630			],
7631			blinding_point: ln_test_utils::pubkey(47),
7632			excess_final_cltv_expiry_delta: 41,
7633			final_value_msat: 101,
7634		});
7635		let encoded_route = route.encode();
7636		let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
7637		assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
7638		assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
7639	}
7640
7641	#[test]
7642	fn blinded_path_inflight_processing() {
7643		// Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
7644		// account for the blinded tail's final amount_msat.
7645		let mut inflight_htlcs = InFlightHtlcs::new();
7646		let path = Path {
7647			hops: vec![RouteHop {
7648				pubkey: ln_test_utils::pubkey(42),
7649				node_features: NodeFeatures::empty(),
7650				short_channel_id: 42,
7651				channel_features: ChannelFeatures::empty(),
7652				fee_msat: 100,
7653				cltv_expiry_delta: 0,
7654				maybe_announced_channel: false,
7655			},
7656			RouteHop {
7657				pubkey: ln_test_utils::pubkey(43),
7658				node_features: NodeFeatures::empty(),
7659				short_channel_id: 43,
7660				channel_features: ChannelFeatures::empty(),
7661				fee_msat: 1,
7662				cltv_expiry_delta: 0,
7663				maybe_announced_channel: false,
7664			}],
7665			blinded_tail: Some(BlindedTail {
7666				hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
7667				blinding_point: ln_test_utils::pubkey(48),
7668				excess_final_cltv_expiry_delta: 0,
7669				final_value_msat: 200,
7670			}),
7671		};
7672		inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
7673		assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
7674		assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
7675	}
7676
7677	#[test]
7678	fn blinded_path_cltv_shadow_offset() {
7679		// Make sure we add a shadow offset when sending to blinded paths.
7680		let mut route = Route { paths: vec![Path {
7681			hops: vec![RouteHop {
7682				pubkey: ln_test_utils::pubkey(42),
7683				node_features: NodeFeatures::empty(),
7684				short_channel_id: 42,
7685				channel_features: ChannelFeatures::empty(),
7686				fee_msat: 100,
7687				cltv_expiry_delta: 0,
7688				maybe_announced_channel: false,
7689			},
7690			RouteHop {
7691				pubkey: ln_test_utils::pubkey(43),
7692				node_features: NodeFeatures::empty(),
7693				short_channel_id: 43,
7694				channel_features: ChannelFeatures::empty(),
7695				fee_msat: 1,
7696				cltv_expiry_delta: 0,
7697				maybe_announced_channel: false,
7698			}
7699			],
7700			blinded_tail: Some(BlindedTail {
7701				hops: vec![
7702					BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
7703					BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
7704				],
7705				blinding_point: ln_test_utils::pubkey(44),
7706				excess_final_cltv_expiry_delta: 0,
7707				final_value_msat: 200,
7708			}),
7709		}], route_params: None};
7710
7711		let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
7712		let (_, network_graph, _, _, _) = build_line_graph();
7713		add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
7714		assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
7715		assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
7716	}
7717
7718	#[test]
7719	fn simple_blinded_route_hints() {
7720		do_simple_blinded_route_hints(1);
7721		do_simple_blinded_route_hints(2);
7722		do_simple_blinded_route_hints(3);
7723	}
7724
7725	fn do_simple_blinded_route_hints(num_blinded_hops: usize) {
7726		// Check that we can generate a route to a blinded path with the expected hops.
7727		let (secp_ctx, network, _, _, logger) = build_graph();
7728		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7729		let network_graph = network.read_only();
7730
7731		let scorer = ln_test_utils::TestScorer::new();
7732		let random_seed_bytes = [42; 32];
7733
7734		let mut blinded_hops = Vec::new();
7735		for i in 0..num_blinded_hops {
7736			blinded_hops.push(
7737				BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 + i as u8), encrypted_payload: Vec::new() },
7738			);
7739		}
7740		let blinded_payinfo = BlindedPayInfo {
7741			fee_base_msat: 100,
7742			fee_proportional_millionths: 500,
7743			htlc_minimum_msat: 1000,
7744			htlc_maximum_msat: 100_000_000,
7745			cltv_expiry_delta: 15,
7746			features: BlindedHopFeatures::empty(),
7747		};
7748		let blinded_path = BlindedPaymentPath::from_raw(nodes[2], ln_test_utils::pubkey(42), blinded_hops, blinded_payinfo.clone());
7749		let payment_params = PaymentParameters::blinded(vec![blinded_path.clone(), blinded_path.clone()]);
7750
7751		// Make sure we can round-trip read and write blinded payment params.
7752		let encoded_params = payment_params.encode();
7753		let mut s = Cursor::new(&encoded_params);
7754		let mut reader = FixedLengthReader::new(&mut s, encoded_params.len() as u64);
7755		let decoded_params: PaymentParameters = ReadableArgs::read(&mut reader, 42).unwrap();
7756		assert_eq!(payment_params, decoded_params);
7757
7758		let route_params = RouteParameters::from_payment_params_and_value(
7759			payment_params, 1001);
7760		let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7761			&scorer, &Default::default(), &random_seed_bytes).unwrap();
7762		assert_eq!(route.paths.len(), 1);
7763		assert_eq!(route.paths[0].hops.len(), 2);
7764
7765		let tail = route.paths[0].blinded_tail.as_ref().unwrap();
7766		assert_eq!(&tail.hops, blinded_path.blinded_hops());
7767		assert_eq!(tail.excess_final_cltv_expiry_delta, 0);
7768		assert_eq!(tail.final_value_msat, 1001);
7769
7770		let final_hop = route.paths[0].hops.last().unwrap();
7771		assert_eq!(
7772			NodeId::from_pubkey(&final_hop.pubkey),
7773			*blinded_path.public_introduction_node_id(&network_graph).unwrap()
7774		);
7775		if tail.hops.len() > 1 {
7776			assert_eq!(final_hop.fee_msat,
7777				blinded_payinfo.fee_base_msat as u64 + blinded_payinfo.fee_proportional_millionths as u64 * tail.final_value_msat / 1000000);
7778			assert_eq!(final_hop.cltv_expiry_delta, blinded_payinfo.cltv_expiry_delta as u32);
7779		} else {
7780			assert_eq!(final_hop.fee_msat, 0);
7781			assert_eq!(final_hop.cltv_expiry_delta, 0);
7782		}
7783	}
7784
7785	#[test]
7786	fn blinded_path_routing_errors() {
7787		// Check that we can generate a route to a blinded path with the expected hops.
7788		let (secp_ctx, network, _, _, logger) = build_graph();
7789		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7790		let network_graph = network.read_only();
7791
7792		let scorer = ln_test_utils::TestScorer::new();
7793		let random_seed_bytes = [42; 32];
7794
7795		let blinded_payinfo = BlindedPayInfo {
7796			fee_base_msat: 100,
7797			fee_proportional_millionths: 500,
7798			htlc_minimum_msat: 1000,
7799			htlc_maximum_msat: 100_000_000,
7800			cltv_expiry_delta: 15,
7801			features: BlindedHopFeatures::empty(),
7802		};
7803
7804		let invalid_blinded_path_2 = dummy_one_hop_blinded_path(nodes[2], blinded_payinfo.clone());
7805		let invalid_blinded_path_3 = dummy_one_hop_blinded_path(nodes[3], blinded_payinfo.clone());
7806		let payment_params = PaymentParameters::blinded(vec![
7807			invalid_blinded_path_2, invalid_blinded_path_3]);
7808		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7809		match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7810			&scorer, &Default::default(), &random_seed_bytes)
7811		{
7812			Err(LightningError { err, .. }) => {
7813				assert_eq!(err, "1-hop blinded paths must all have matching introduction node ids");
7814			},
7815			_ => panic!("Expected error")
7816		}
7817
7818		let invalid_blinded_path = dummy_blinded_path(our_id, blinded_payinfo.clone());
7819		let payment_params = PaymentParameters::blinded(vec![invalid_blinded_path]);
7820		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7821		match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7822			&Default::default(), &random_seed_bytes)
7823		{
7824			Err(LightningError { err, .. }) => {
7825				assert_eq!(err, "Cannot generate a route to blinded paths if we are the introduction node to all of them");
7826			},
7827			_ => panic!("Expected error")
7828		}
7829
7830		let mut invalid_blinded_path = dummy_one_hop_blinded_path(ln_test_utils::pubkey(46), blinded_payinfo);
7831		invalid_blinded_path.clear_blinded_hops();
7832		let payment_params = PaymentParameters::blinded(vec![invalid_blinded_path]);
7833		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1001);
7834		match get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger), &scorer,
7835			&Default::default(), &random_seed_bytes)
7836		{
7837			Err(LightningError { err, .. }) => {
7838				assert_eq!(err, "0-hop blinded path provided");
7839			},
7840			_ => panic!("Expected error")
7841		}
7842	}
7843
7844	#[test]
7845	fn matching_intro_node_paths_provided() {
7846		// Check that if multiple blinded paths with the same intro node are provided in payment
7847		// parameters, we'll return the correct paths in the resulting MPP route.
7848		let (secp_ctx, network, _, _, logger) = build_graph();
7849		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
7850		let network_graph = network.read_only();
7851
7852		let scorer = ln_test_utils::TestScorer::new();
7853		let random_seed_bytes = [42; 32];
7854		let config = UserConfig::default();
7855
7856		let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
7857		let blinded_payinfo_1 = BlindedPayInfo {
7858			fee_base_msat: 0,
7859			fee_proportional_millionths: 0,
7860			htlc_minimum_msat: 0,
7861			htlc_maximum_msat: 30_000,
7862			cltv_expiry_delta: 0,
7863			features: BlindedHopFeatures::empty(),
7864		};
7865		let blinded_path_1 = dummy_blinded_path(nodes[2], blinded_payinfo_1.clone());
7866
7867		let mut blinded_payinfo_2 = blinded_payinfo_1;
7868		blinded_payinfo_2.htlc_maximum_msat = 70_000;
7869		let blinded_path_2 = BlindedPaymentPath::from_raw(nodes[2], ln_test_utils::pubkey(43),
7870			vec![
7871				BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() },
7872				BlindedHop { blinded_node_id: ln_test_utils::pubkey(42 as u8), encrypted_payload: Vec::new() }
7873			],
7874			blinded_payinfo_2
7875		);
7876
7877		let blinded_hints = vec![blinded_path_1.clone(), blinded_path_2.clone()];
7878		let payment_params = PaymentParameters::blinded(blinded_hints.clone())
7879			.with_bolt12_features(bolt12_features).unwrap();
7880
7881		let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, 100_000);
7882		route_params.max_total_routing_fee_msat = Some(100_000);
7883		let route = get_route(&our_id, &route_params, &network_graph, None, Arc::clone(&logger),
7884			&scorer, &Default::default(), &random_seed_bytes).unwrap();
7885		assert_eq!(route.paths.len(), 2);
7886		let mut total_amount_paid_msat = 0;
7887		for path in route.paths.into_iter() {
7888			assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
7889			if let Some(bt) = &path.blinded_tail {
7890				assert_eq!(bt.blinding_point,
7891					blinded_hints.iter().find(|p| p.payinfo.htlc_maximum_msat == path.final_value_msat())
7892						.map(|bp| bp.blinding_point()).unwrap());
7893			} else { panic!(); }
7894			total_amount_paid_msat += path.final_value_msat();
7895		}
7896		assert_eq!(total_amount_paid_msat, 100_000);
7897	}
7898
7899	#[test]
7900	fn direct_to_intro_node() {
7901		// This previously caused a debug panic in the router when asserting
7902		// `used_liquidity_msat <= hop_max_msat`, because when adding first_hop<>blinded_route_hint
7903		// direct channels we failed to account for the fee charged for use of the blinded path.
7904
7905		// Build a graph:
7906		// node0 -1(1)2 - node1
7907		// such that there isn't enough liquidity to reach node1, but the router thinks there is if it
7908		// doesn't account for the blinded path fee.
7909
7910		let secp_ctx = Secp256k1::new();
7911		let logger = Arc::new(ln_test_utils::TestLogger::new());
7912		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
7913		let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
7914		let scorer = ln_test_utils::TestScorer::new();
7915		let random_seed_bytes = [42; 32];
7916
7917		let amt_msat = 10_000_000;
7918		let (_, _, privkeys, nodes) = get_nodes(&secp_ctx);
7919		add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
7920			ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
7921		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
7922			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7923			short_channel_id: 1,
7924			timestamp: 1,
7925			message_flags: 1, // Only must_be_one
7926			channel_flags: 0,
7927			cltv_expiry_delta: 42,
7928			htlc_minimum_msat: 1_000,
7929			htlc_maximum_msat: 10_000_000,
7930			fee_base_msat: 800,
7931			fee_proportional_millionths: 0,
7932			excess_data: Vec::new()
7933		});
7934		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
7935			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
7936			short_channel_id: 1,
7937			timestamp: 1,
7938			message_flags: 1, // Only must_be_one
7939			channel_flags: 1,
7940			cltv_expiry_delta: 42,
7941			htlc_minimum_msat: 1_000,
7942			htlc_maximum_msat: 10_000_000,
7943			fee_base_msat: 800,
7944			fee_proportional_millionths: 0,
7945			excess_data: Vec::new()
7946		});
7947		let first_hops = vec![
7948			get_channel_details(Some(1), nodes[1], InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
7949
7950		let blinded_payinfo = BlindedPayInfo {
7951			fee_base_msat: 1000,
7952			fee_proportional_millionths: 0,
7953			htlc_minimum_msat: 1000,
7954			htlc_maximum_msat: MAX_VALUE_MSAT,
7955			cltv_expiry_delta: 0,
7956			features: BlindedHopFeatures::empty(),
7957		};
7958		let blinded_path = dummy_blinded_path(nodes[1], blinded_payinfo.clone());
7959		let blinded_hints = vec![blinded_path];
7960
7961		let payment_params = PaymentParameters::blinded(blinded_hints.clone());
7962
7963		let netgraph = network_graph.read_only();
7964		let route_params = RouteParameters::from_payment_params_and_value(
7965			payment_params.clone(), amt_msat);
7966		if let Err(LightningError { err, .. }) = get_route(&nodes[0], &route_params, &netgraph,
7967			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7968			&Default::default(), &random_seed_bytes) {
7969				assert_eq!(err, "Failed to find a path to the given destination");
7970		} else { panic!("Expected error") }
7971
7972		// Sending an exact amount accounting for the blinded path fee works.
7973		let amt_minus_blinded_path_fee = amt_msat - blinded_payinfo.fee_base_msat as u64;
7974		let route_params = RouteParameters::from_payment_params_and_value(
7975			payment_params, amt_minus_blinded_path_fee);
7976		let route = get_route(&nodes[0], &route_params, &netgraph,
7977			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
7978			&Default::default(), &random_seed_bytes).unwrap();
7979		assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
7980		assert_eq!(route.get_total_amount(), amt_minus_blinded_path_fee);
7981	}
7982
7983	#[test]
7984	fn direct_to_matching_intro_nodes() {
7985		// This previously caused us to enter `unreachable` code in the following situation:
7986		// 1. We add a route candidate for intro_node contributing a high amount
7987		// 2. We add a first_hop<>intro_node route candidate for the same high amount
7988		// 3. We see a cheaper blinded route hint for the same intro node but a much lower contribution
7989		//    amount, and update our route candidate for intro_node for the lower amount
7990		// 4. We then attempt to update the aforementioned first_hop<>intro_node route candidate for the
7991		//    lower contribution amount, but fail (this was previously caused by failure to account for
7992		//    blinded path fees when adding first_hop<>intro_node candidates)
7993		// 5. We go to construct the path from these route candidates and our first_hop<>intro_node
7994		//    candidate still thinks its path is contributing the original higher amount. This caused us
7995		//    to hit an `unreachable` overflow when calculating the cheaper intro_node fees over the
7996		//    larger amount
7997		let secp_ctx = Secp256k1::new();
7998		let logger = Arc::new(ln_test_utils::TestLogger::new());
7999		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8000		let scorer = ln_test_utils::TestScorer::new();
8001		let random_seed_bytes = [42; 32];
8002		let config = UserConfig::default();
8003
8004		// Values are taken from the fuzz input that uncovered this panic.
8005		let amt_msat = 21_7020_5185_1403_2640;
8006		let (_, _, _, nodes) = get_nodes(&secp_ctx);
8007		let first_hops = vec![
8008			get_channel_details(Some(1), nodes[1], channelmanager::provided_init_features(&config),
8009				18446744073709551615)];
8010
8011		let blinded_payinfo = BlindedPayInfo {
8012			fee_base_msat: 5046_2720,
8013			fee_proportional_millionths: 0,
8014			htlc_minimum_msat: 4503_5996_2737_0496,
8015			htlc_maximum_msat: 45_0359_9627_3704_9600,
8016			cltv_expiry_delta: 0,
8017			features: BlindedHopFeatures::empty(),
8018		};
8019		let blinded_path = dummy_blinded_path(nodes[1], blinded_payinfo.clone());
8020		let mut blinded_hints = vec![blinded_path.clone(), blinded_path.clone()];
8021		blinded_hints[1].payinfo.fee_base_msat = 419_4304;
8022		blinded_hints[1].payinfo.fee_proportional_millionths = 257;
8023		blinded_hints[1].payinfo.htlc_minimum_msat = 280_8908_6115_8400;
8024		blinded_hints[1].payinfo.htlc_maximum_msat = 2_8089_0861_1584_0000;
8025		blinded_hints[1].payinfo.cltv_expiry_delta = 0;
8026
8027		let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8028		let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8029			.with_bolt12_features(bolt12_features).unwrap();
8030
8031		let netgraph = network_graph.read_only();
8032		let route_params = RouteParameters::from_payment_params_and_value(
8033			payment_params, amt_msat);
8034		let route = get_route(&nodes[0], &route_params, &netgraph,
8035			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8036			&Default::default(), &random_seed_bytes).unwrap();
8037		assert_eq!(route.get_total_fees(), blinded_payinfo.fee_base_msat as u64);
8038		assert_eq!(route.get_total_amount(), amt_msat);
8039	}
8040
8041	#[test]
8042	fn we_are_intro_node_candidate_hops() {
8043		// This previously led to a panic in the router because we'd generate a Path with only a
8044		// BlindedTail and 0 unblinded hops, due to the only candidate hops being blinded route hints
8045		// where the origin node is the intro node. We now fully disallow considering candidate hops
8046		// where the origin node is the intro node.
8047		let (secp_ctx, network_graph, _, _, logger) = build_graph();
8048		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8049		let scorer = ln_test_utils::TestScorer::new();
8050		let random_seed_bytes = [42; 32];
8051		let config = UserConfig::default();
8052
8053		// Values are taken from the fuzz input that uncovered this panic.
8054		let amt_msat = 21_7020_5185_1423_0019;
8055
8056		let blinded_payinfo = BlindedPayInfo {
8057			fee_base_msat: 5052_9027,
8058			fee_proportional_millionths: 0,
8059			htlc_minimum_msat: 21_7020_5185_1423_0019,
8060			htlc_maximum_msat: 1844_6744_0737_0955_1615,
8061			cltv_expiry_delta: 0,
8062			features: BlindedHopFeatures::empty(),
8063		};
8064		let blinded_path = dummy_blinded_path(our_id, blinded_payinfo.clone());
8065		let mut blinded_hints = vec![blinded_path.clone(), blinded_path.clone()];
8066		blinded_hints[1] = dummy_blinded_path(nodes[6], blinded_payinfo);
8067
8068		let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8069		let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8070			.with_bolt12_features(bolt12_features.clone()).unwrap();
8071
8072		let netgraph = network_graph.read_only();
8073		let route_params = RouteParameters::from_payment_params_and_value(
8074			payment_params, amt_msat);
8075		if let Err(LightningError { err, .. }) = get_route(
8076			&our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8077		) {
8078			assert_eq!(err, "Failed to find a path to the given destination");
8079		} else { panic!() }
8080	}
8081
8082	#[test]
8083	fn we_are_intro_node_bp_in_final_path_fee_calc() {
8084		// This previously led to a debug panic in the router because we'd find an invalid Path with
8085		// 0 unblinded hops and a blinded tail, leading to the generation of a final
8086		// PaymentPathHop::fee_msat that included both the blinded path fees and the final value of
8087		// the payment, when it was intended to only include the final value of the payment.
8088		let (secp_ctx, network_graph, _, _, logger) = build_graph();
8089		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8090		let scorer = ln_test_utils::TestScorer::new();
8091		let random_seed_bytes = [42; 32];
8092		let config = UserConfig::default();
8093
8094		// Values are taken from the fuzz input that uncovered this panic.
8095		let amt_msat = 21_7020_5185_1423_0019;
8096
8097		let blinded_payinfo = BlindedPayInfo {
8098			fee_base_msat: 10_4425_1395,
8099			fee_proportional_millionths: 0,
8100			htlc_minimum_msat: 21_7301_9934_9094_0931,
8101			htlc_maximum_msat: 1844_6744_0737_0955_1615,
8102			cltv_expiry_delta: 0,
8103			features: BlindedHopFeatures::empty(),
8104		};
8105		let blinded_path = dummy_blinded_path(our_id, blinded_payinfo.clone());
8106		let mut blinded_hints = vec![
8107			blinded_path.clone(), blinded_path.clone(), blinded_path.clone(),
8108		];
8109		blinded_hints[1].payinfo.fee_base_msat = 5052_9027;
8110		blinded_hints[1].payinfo.htlc_minimum_msat = 21_7020_5185_1423_0019;
8111		blinded_hints[1].payinfo.htlc_maximum_msat = 1844_6744_0737_0955_1615;
8112
8113		blinded_hints[2] = dummy_blinded_path(nodes[6], blinded_payinfo);
8114
8115		let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8116		let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8117			.with_bolt12_features(bolt12_features.clone()).unwrap();
8118
8119		let netgraph = network_graph.read_only();
8120		let route_params = RouteParameters::from_payment_params_and_value(
8121			payment_params, amt_msat);
8122		if let Err(LightningError { err, .. }) = get_route(
8123			&our_id, &route_params, &netgraph, None, Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8124		) {
8125			assert_eq!(err, "Failed to find a path to the given destination");
8126		} else { panic!() }
8127	}
8128
8129	#[test]
8130	fn min_htlc_overpay_violates_max_htlc() {
8131		do_min_htlc_overpay_violates_max_htlc(true);
8132		do_min_htlc_overpay_violates_max_htlc(false);
8133	}
8134	fn do_min_htlc_overpay_violates_max_htlc(blinded_payee: bool) {
8135		// Test that if overpaying to meet a later hop's min_htlc and causes us to violate an earlier
8136		// hop's max_htlc, we don't consider that candidate hop valid. Previously we would add this hop
8137		// to `targets` and build an invalid path with it, and subsequently hit a debug panic asserting
8138		// that the used liquidity for a hop was less than its available liquidity limit.
8139		let secp_ctx = Secp256k1::new();
8140		let logger = Arc::new(ln_test_utils::TestLogger::new());
8141		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8142		let scorer = ln_test_utils::TestScorer::new();
8143		let random_seed_bytes = [42; 32];
8144		let config = UserConfig::default();
8145
8146		// Values are taken from the fuzz input that uncovered this panic.
8147		let amt_msat = 7_4009_8048;
8148		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8149		let first_hop_outbound_capacity = 2_7345_2000;
8150		let first_hops = vec![get_channel_details(
8151			Some(200), nodes[0], channelmanager::provided_init_features(&config),
8152			first_hop_outbound_capacity
8153		)];
8154
8155		let base_fee = 1_6778_3453;
8156		let htlc_min = 2_5165_8240;
8157		let payment_params = if blinded_payee {
8158			let blinded_payinfo = BlindedPayInfo {
8159				fee_base_msat: base_fee,
8160				fee_proportional_millionths: 0,
8161				htlc_minimum_msat: htlc_min,
8162				htlc_maximum_msat: htlc_min * 1000,
8163				cltv_expiry_delta: 0,
8164				features: BlindedHopFeatures::empty(),
8165			};
8166			let blinded_path = dummy_blinded_path(nodes[0], blinded_payinfo);
8167			let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8168			PaymentParameters::blinded(vec![blinded_path])
8169				.with_bolt12_features(bolt12_features.clone()).unwrap()
8170		} else {
8171			let route_hint = RouteHint(vec![RouteHintHop {
8172				src_node_id: nodes[0],
8173				short_channel_id: 42,
8174				fees: RoutingFees {
8175					base_msat: base_fee,
8176					proportional_millionths: 0,
8177				},
8178				cltv_expiry_delta: 10,
8179				htlc_minimum_msat: Some(htlc_min),
8180				htlc_maximum_msat: None,
8181			}]);
8182
8183			PaymentParameters::from_node_id(nodes[1], 42)
8184				.with_route_hints(vec![route_hint]).unwrap()
8185				.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8186		};
8187
8188		let netgraph = network_graph.read_only();
8189		let route_params = RouteParameters::from_payment_params_and_value(
8190			payment_params, amt_msat);
8191		if let Err(LightningError { err, .. }) = get_route(
8192			&our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8193			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8194		) {
8195			assert_eq!(err, "Failed to find a path to the given destination");
8196		} else { panic!() }
8197	}
8198
8199	#[test]
8200	fn previously_used_liquidity_violates_max_htlc() {
8201		do_previously_used_liquidity_violates_max_htlc(true);
8202		do_previously_used_liquidity_violates_max_htlc(false);
8203
8204	}
8205	fn do_previously_used_liquidity_violates_max_htlc(blinded_payee: bool) {
8206		// Test that if a candidate first_hop<>route_hint_src_node channel does not have enough
8207		// contribution amount to cover the next hop's min_htlc plus fees, we will not consider that
8208		// candidate. In this case, the candidate does not have enough due to a previous path taking up
8209		// some of its liquidity. Previously we would construct an invalid path and hit a debug panic
8210		// asserting that the used liquidity for a hop was less than its available liquidity limit.
8211		let secp_ctx = Secp256k1::new();
8212		let logger = Arc::new(ln_test_utils::TestLogger::new());
8213		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8214		let scorer = ln_test_utils::TestScorer::new();
8215		let random_seed_bytes = [42; 32];
8216		let config = UserConfig::default();
8217
8218		// Values are taken from the fuzz input that uncovered this panic.
8219		let amt_msat = 52_4288;
8220		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8221		let first_hops = vec![get_channel_details(
8222			Some(161), nodes[0], channelmanager::provided_init_features(&config), 486_4000
8223		), get_channel_details(
8224			Some(122), nodes[0], channelmanager::provided_init_features(&config), 179_5000
8225		)];
8226
8227		let base_fees = [0, 425_9840, 0, 0];
8228		let htlc_mins = [1_4392, 19_7401, 1027, 6_5535];
8229		let payment_params = if blinded_payee {
8230			let mut blinded_hints = Vec::new();
8231			for (base_fee, htlc_min) in base_fees.iter().zip(htlc_mins.iter()) {
8232				let blinded_payinfo = BlindedPayInfo {
8233					fee_base_msat: *base_fee,
8234					fee_proportional_millionths: 0,
8235					htlc_minimum_msat: *htlc_min,
8236					htlc_maximum_msat: htlc_min * 100,
8237					cltv_expiry_delta: 10,
8238					features: BlindedHopFeatures::empty(),
8239				};
8240				blinded_hints.push(dummy_blinded_path(nodes[0], blinded_payinfo));
8241			}
8242			let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8243			PaymentParameters::blinded(blinded_hints.clone())
8244				.with_bolt12_features(bolt12_features.clone()).unwrap()
8245		} else {
8246			let mut route_hints = Vec::new();
8247			for (idx, (base_fee, htlc_min)) in base_fees.iter().zip(htlc_mins.iter()).enumerate() {
8248				route_hints.push(RouteHint(vec![RouteHintHop {
8249					src_node_id: nodes[0],
8250					short_channel_id: 42 + idx as u64,
8251					fees: RoutingFees {
8252						base_msat: *base_fee,
8253						proportional_millionths: 0,
8254					},
8255					cltv_expiry_delta: 10,
8256					htlc_minimum_msat: Some(*htlc_min),
8257					htlc_maximum_msat: Some(htlc_min * 100),
8258				}]));
8259			}
8260			PaymentParameters::from_node_id(nodes[1], 42)
8261				.with_route_hints(route_hints).unwrap()
8262				.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap()
8263		};
8264
8265		let netgraph = network_graph.read_only();
8266		let route_params = RouteParameters::from_payment_params_and_value(
8267			payment_params, amt_msat);
8268
8269		let route = get_route(
8270			&our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8271			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes
8272		).unwrap();
8273		assert_eq!(route.paths.len(), 1);
8274		assert_eq!(route.get_total_amount(), amt_msat);
8275	}
8276
8277	#[test]
8278	fn candidate_path_min() {
8279		// Test that if a candidate first_hop<>network_node channel does not have enough contribution
8280		// amount to cover the next channel's min htlc plus fees, we will not consider that candidate.
8281		// Previously, we were storing RouteGraphNodes with a path_min that did not include fees, and
8282		// would add a connecting first_hop node that did not have enough contribution amount, leading
8283		// to a debug panic upon invalid path construction.
8284		let secp_ctx = Secp256k1::new();
8285		let logger = Arc::new(ln_test_utils::TestLogger::new());
8286		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8287		let gossip_sync = P2PGossipSync::new(network_graph.clone(), None, logger.clone());
8288		let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8289		let random_seed_bytes = [42; 32];
8290		let config = UserConfig::default();
8291
8292		// Values are taken from the fuzz input that uncovered this panic.
8293		let amt_msat = 7_4009_8048;
8294		let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8295		let first_hops = vec![get_channel_details(
8296			Some(200), nodes[0], channelmanager::provided_init_features(&config), 2_7345_2000
8297		)];
8298
8299		add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
8300		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8301			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8302			short_channel_id: 6,
8303			timestamp: 1,
8304			message_flags: 1, // Only must_be_one
8305			channel_flags: 0,
8306			cltv_expiry_delta: (6 << 4) | 0,
8307			htlc_minimum_msat: 0,
8308			htlc_maximum_msat: MAX_VALUE_MSAT,
8309			fee_base_msat: 0,
8310			fee_proportional_millionths: 0,
8311			excess_data: Vec::new()
8312		});
8313		add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
8314
8315		let htlc_min = 2_5165_8240;
8316		let blinded_hints = vec![
8317			dummy_blinded_path(nodes[0], BlindedPayInfo {
8318				fee_base_msat: 1_6778_3453,
8319				fee_proportional_millionths: 0,
8320				htlc_minimum_msat: htlc_min,
8321				htlc_maximum_msat: htlc_min * 100,
8322				cltv_expiry_delta: 10,
8323				features: BlindedHopFeatures::empty(),
8324			})
8325		];
8326		let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8327		let payment_params = PaymentParameters::blinded(blinded_hints.clone())
8328			.with_bolt12_features(bolt12_features.clone()).unwrap();
8329		let route_params = RouteParameters::from_payment_params_and_value(
8330			payment_params, amt_msat);
8331		let netgraph = network_graph.read_only();
8332
8333		if let Err(LightningError { err, .. }) = get_route(
8334			&our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8335			Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8336			&random_seed_bytes
8337		) {
8338			assert_eq!(err, "Failed to find a path to the given destination");
8339		} else { panic!() }
8340	}
8341
8342	#[test]
8343	fn path_contribution_includes_min_htlc_overpay() {
8344		// Previously, the fuzzer hit a debug panic because we wouldn't include the amount overpaid to
8345		// meet a last hop's min_htlc in the total collected paths value. We now include this value and
8346		// also penalize hops along the overpaying path to ensure that it gets deprioritized in path
8347		// selection, both tested here.
8348		let secp_ctx = Secp256k1::new();
8349		let logger = Arc::new(ln_test_utils::TestLogger::new());
8350		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8351		let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), network_graph.clone(), logger.clone());
8352		let random_seed_bytes = [42; 32];
8353		let config = UserConfig::default();
8354
8355		// Values are taken from the fuzz input that uncovered this panic.
8356		let amt_msat = 562_0000;
8357		let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
8358		let first_hops = vec![
8359			get_channel_details(
8360				Some(83), nodes[0], channelmanager::provided_init_features(&config), 2199_0000,
8361			),
8362		];
8363
8364		let htlc_mins = [49_0000, 1125_0000];
8365		let payment_params = {
8366			let mut blinded_hints = Vec::new();
8367			for htlc_min in htlc_mins.iter() {
8368				let payinfo = BlindedPayInfo {
8369					fee_base_msat: 0,
8370					fee_proportional_millionths: 0,
8371					htlc_minimum_msat: *htlc_min,
8372					htlc_maximum_msat: *htlc_min * 100,
8373					cltv_expiry_delta: 10,
8374					features: BlindedHopFeatures::empty(),
8375				};
8376				blinded_hints.push(dummy_blinded_path(nodes[0], payinfo));
8377			}
8378			let bolt12_features = channelmanager::provided_bolt12_invoice_features(&config);
8379			PaymentParameters::blinded(blinded_hints.clone())
8380				.with_bolt12_features(bolt12_features.clone()).unwrap()
8381		};
8382
8383		let netgraph = network_graph.read_only();
8384		let route_params = RouteParameters::from_payment_params_and_value(
8385			payment_params, amt_msat);
8386		let route = get_route(
8387			&our_id, &route_params, &netgraph, Some(&first_hops.iter().collect::<Vec<_>>()),
8388			Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(),
8389			&random_seed_bytes
8390		).unwrap();
8391		assert_eq!(route.paths.len(), 1);
8392		assert_eq!(route.get_total_amount(), amt_msat);
8393	}
8394
8395	#[test]
8396	fn first_hop_preferred_over_hint() {
8397		// Check that if we have a first hop to a peer we'd always prefer that over a route hint
8398		// they gave us, but we'd still consider all subsequent hints if they are more attractive.
8399		let secp_ctx = Secp256k1::new();
8400		let logger = Arc::new(ln_test_utils::TestLogger::new());
8401		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8402		let gossip_sync = P2PGossipSync::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
8403		let scorer = ln_test_utils::TestScorer::new();
8404		let random_seed_bytes = [42; 32];
8405		let config = UserConfig::default();
8406
8407		let amt_msat = 1_000_000;
8408		let (our_privkey, our_node_id, privkeys, nodes) = get_nodes(&secp_ctx);
8409
8410		add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[0],
8411			ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
8412		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8413			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8414			short_channel_id: 1,
8415			timestamp: 1,
8416			message_flags: 1, // Only must_be_one
8417			channel_flags: 0,
8418			cltv_expiry_delta: 42,
8419			htlc_minimum_msat: 1_000,
8420			htlc_maximum_msat: 10_000_000,
8421			fee_base_msat: 800,
8422			fee_proportional_millionths: 0,
8423			excess_data: Vec::new()
8424		});
8425		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8426			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8427			short_channel_id: 1,
8428			timestamp: 1,
8429			message_flags: 1, // Only must_be_one
8430			channel_flags: 1,
8431			cltv_expiry_delta: 42,
8432			htlc_minimum_msat: 1_000,
8433			htlc_maximum_msat: 10_000_000,
8434			fee_base_msat: 800,
8435			fee_proportional_millionths: 0,
8436			excess_data: Vec::new()
8437		});
8438
8439		add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[1],
8440			ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 2);
8441		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8442			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8443			short_channel_id: 2,
8444			timestamp: 2,
8445			message_flags: 1, // Only must_be_one
8446			channel_flags: 0,
8447			cltv_expiry_delta: 42,
8448			htlc_minimum_msat: 1_000,
8449			htlc_maximum_msat: 10_000_000,
8450			fee_base_msat: 800,
8451			fee_proportional_millionths: 0,
8452			excess_data: Vec::new()
8453		});
8454		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
8455			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8456			short_channel_id: 2,
8457			timestamp: 2,
8458			message_flags: 1, // Only must_be_one
8459			channel_flags: 1,
8460			cltv_expiry_delta: 42,
8461			htlc_minimum_msat: 1_000,
8462			htlc_maximum_msat: 10_000_000,
8463			fee_base_msat: 800,
8464			fee_proportional_millionths: 0,
8465			excess_data: Vec::new()
8466		});
8467
8468		let dest_node_id = nodes[2];
8469
8470		let route_hint = RouteHint(vec![RouteHintHop {
8471			src_node_id: our_node_id,
8472			short_channel_id: 44,
8473			fees: RoutingFees {
8474				base_msat: 234,
8475				proportional_millionths: 0,
8476			},
8477			cltv_expiry_delta: 10,
8478			htlc_minimum_msat: None,
8479			htlc_maximum_msat: Some(5_000_000),
8480		},
8481		RouteHintHop {
8482			src_node_id: nodes[0],
8483			short_channel_id: 45,
8484			fees: RoutingFees {
8485				base_msat: 123,
8486				proportional_millionths: 0,
8487			},
8488			cltv_expiry_delta: 10,
8489			htlc_minimum_msat: None,
8490			htlc_maximum_msat: None,
8491		}]);
8492
8493		let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8494			.with_route_hints(vec![route_hint]).unwrap()
8495			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8496		let route_params = RouteParameters::from_payment_params_and_value(
8497			payment_params, amt_msat);
8498
8499		// First create an insufficient first hop for channel with SCID 1 and check we'd use the
8500		// route hint.
8501		let first_hop = get_channel_details(Some(1), nodes[0],
8502			channelmanager::provided_init_features(&config), 999_999);
8503		let first_hops = vec![first_hop];
8504
8505		let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8506			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8507			&Default::default(), &random_seed_bytes).unwrap();
8508		assert_eq!(route.paths.len(), 1);
8509		assert_eq!(route.get_total_amount(), amt_msat);
8510		assert_eq!(route.paths[0].hops.len(), 2);
8511		assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8512		assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8513		assert_eq!(route.get_total_fees(), 123);
8514
8515		// Now check we would trust our first hop info, i.e., fail if we detect the route hint is
8516		// for a first hop channel.
8517		let mut first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 999_999);
8518		first_hop.outbound_scid_alias = Some(44);
8519		let first_hops = vec![first_hop];
8520
8521		let route_res = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8522			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8523			&Default::default(), &random_seed_bytes);
8524		assert!(route_res.is_err());
8525
8526		// Finally check we'd use the first hop if has sufficient outbound capacity. But we'd stil
8527		// use the cheaper second hop of the route hint.
8528		let mut first_hop = get_channel_details(Some(1), nodes[0],
8529			channelmanager::provided_init_features(&config), 10_000_000);
8530		first_hop.outbound_scid_alias = Some(44);
8531		let first_hops = vec![first_hop];
8532
8533		let route = get_route(&our_node_id, &route_params.clone(), &network_graph.read_only(),
8534			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8535			&Default::default(), &random_seed_bytes).unwrap();
8536		assert_eq!(route.paths.len(), 1);
8537		assert_eq!(route.get_total_amount(), amt_msat);
8538		assert_eq!(route.paths[0].hops.len(), 2);
8539		assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8540		assert_eq!(route.paths[0].hops[1].short_channel_id, 45);
8541		assert_eq!(route.get_total_fees(), 123);
8542	}
8543
8544	#[test]
8545	fn test_max_final_contribution() {
8546		// When `compute_max_final_value_contribution` was added, it had a bug where it would
8547		// over-estimate the maximum value contribution of a hop by using `ceil` rather than
8548		// `floor`. This tests that case by attempting to send 1 million sats over a channel where
8549		// the remaining hops have a base fee of zero and a proportional fee of 1 millionth.
8550
8551		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
8552		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8553		let scorer = ln_test_utils::TestScorer::new();
8554		let random_seed_bytes = [42; 32];
8555
8556		// Enable channel 1, setting max HTLC to 1M sats
8557		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8558			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8559			short_channel_id: 1,
8560			timestamp: 2,
8561			message_flags: 1, // Only must_be_one
8562			channel_flags: 0,
8563			cltv_expiry_delta: (1 << 4) | 1,
8564			htlc_minimum_msat: 0,
8565			htlc_maximum_msat: 1_000_000,
8566			fee_base_msat: 0,
8567			fee_proportional_millionths: 0,
8568			excess_data: Vec::new()
8569		});
8570
8571		// Set the fee on channel 3 to zero
8572		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
8573			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8574			short_channel_id: 3,
8575			timestamp: 2,
8576			message_flags: 1, // Only must_be_one
8577			channel_flags: 0,
8578			cltv_expiry_delta: (3 << 4) | 1,
8579			htlc_minimum_msat: 0,
8580			htlc_maximum_msat: 1_000_000_000,
8581			fee_base_msat: 0,
8582			fee_proportional_millionths: 0,
8583			excess_data: Vec::new()
8584		});
8585
8586		// Set the fee on channel 6 to 1 millionth
8587		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
8588			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8589			short_channel_id: 6,
8590			timestamp: 2,
8591			message_flags: 1, // Only must_be_one
8592			channel_flags: 0,
8593			cltv_expiry_delta: (6 << 4) | 1,
8594			htlc_minimum_msat: 0,
8595			htlc_maximum_msat: 1_000_000_000,
8596			fee_base_msat: 0,
8597			fee_proportional_millionths: 1,
8598			excess_data: Vec::new()
8599		});
8600
8601		// Now attempt to pay over the channel 1 -> channel 3 -> channel 6 path
8602		// This should fail as we need to send 1M + 1 sats to cover the fee but channel 1 only
8603		// allows for 1M sats to flow over it.
8604		let config = UserConfig::default();
8605		let payment_params = PaymentParameters::from_node_id(nodes[4], 42)
8606			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
8607			.unwrap();
8608		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 1_000_000);
8609		get_route(&our_id, &route_params, &network_graph.read_only(), None,
8610			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap_err();
8611
8612		// Now set channel 1 max HTLC to 1M + 1 sats
8613		update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
8614			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8615			short_channel_id: 1,
8616			timestamp: 3,
8617			message_flags: 1, // Only must_be_one
8618			channel_flags: 0,
8619			cltv_expiry_delta: (1 << 4) | 1,
8620			htlc_minimum_msat: 0,
8621			htlc_maximum_msat: 1_000_001,
8622			fee_base_msat: 0,
8623			fee_proportional_millionths: 0,
8624			excess_data: Vec::new()
8625		});
8626
8627		// And attempt the same payment again, but this time it should work.
8628		let route = get_route(&our_id, &route_params, &network_graph.read_only(), None,
8629			Arc::clone(&logger), &scorer, &Default::default(), &random_seed_bytes).unwrap();
8630		assert_eq!(route.paths.len(), 1);
8631		assert_eq!(route.paths[0].hops.len(), 3);
8632		assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
8633		assert_eq!(route.paths[0].hops[1].short_channel_id, 3);
8634		assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
8635	}
8636
8637	#[test]
8638	fn allow_us_being_first_hint() {
8639		// Check that we consider a route hint even if we are the src of the first hop.
8640		let secp_ctx = Secp256k1::new();
8641		let logger = Arc::new(ln_test_utils::TestLogger::new());
8642		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
8643		let scorer = ln_test_utils::TestScorer::new();
8644		let random_seed_bytes = [42; 32];
8645		let config = UserConfig::default();
8646
8647		let (_, our_node_id, _, nodes) = get_nodes(&secp_ctx);
8648
8649		let amt_msat = 1_000_000;
8650		let dest_node_id = nodes[1];
8651
8652		let first_hop = get_channel_details(Some(1), nodes[0], channelmanager::provided_init_features(&config), 10_000_000);
8653		let first_hops = vec![first_hop];
8654
8655		let route_hint = RouteHint(vec![RouteHintHop {
8656			src_node_id: our_node_id,
8657			short_channel_id: 44,
8658			fees: RoutingFees {
8659				base_msat: 123,
8660				proportional_millionths: 0,
8661			},
8662			cltv_expiry_delta: 10,
8663			htlc_minimum_msat: None,
8664			htlc_maximum_msat: None,
8665		}]);
8666
8667		let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
8668			.with_route_hints(vec![route_hint]).unwrap()
8669			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config)).unwrap();
8670
8671		let route_params = RouteParameters::from_payment_params_and_value(
8672			payment_params, amt_msat);
8673
8674
8675		let route = get_route(&our_node_id, &route_params, &network_graph.read_only(),
8676			Some(&first_hops.iter().collect::<Vec<_>>()), Arc::clone(&logger), &scorer,
8677			&Default::default(), &random_seed_bytes).unwrap();
8678
8679		assert_eq!(route.paths.len(), 1);
8680		assert_eq!(route.get_total_amount(), amt_msat);
8681		assert_eq!(route.get_total_fees(), 0);
8682		assert_eq!(route.paths[0].hops.len(), 1);
8683
8684		assert_eq!(route.paths[0].hops[0].short_channel_id, 44);
8685	}
8686
8687	#[test]
8688	fn prefers_paths_by_cost_amt_ratio() {
8689		// Previously, we preferred paths during MPP selection based on their absolute cost, rather
8690		// than the cost-per-amount-transferred. This could result in selecting many MPP paths with
8691		// relatively low value contribution, rather than one large path which is ultimately
8692		// cheaper. While this is a tradeoff (and not universally better), in practice the old
8693		// behavior was problematic, so we shifted to a proportional cost.
8694		//
8695		// Here we check that the proportional cost is being used in a somewhat absurd setup where
8696		// we have one good path and several cheaper, but smaller paths.
8697		let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
8698		let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
8699		let scorer = ln_test_utils::TestScorer::new();
8700		let random_seed_bytes = [42; 32];
8701
8702		// Enable channel 1
8703		let update_1 = UnsignedChannelUpdate {
8704			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8705			short_channel_id: 1,
8706			timestamp: 2,
8707			message_flags: 1, // Only must_be_one
8708			channel_flags: 0,
8709			cltv_expiry_delta: (1 << 4) | 1,
8710			htlc_minimum_msat: 0,
8711			htlc_maximum_msat: 10_000_000,
8712			fee_base_msat: 0,
8713			fee_proportional_millionths: 0,
8714			excess_data: Vec::new(),
8715		};
8716		update_channel(&gossip_sync, &secp_ctx, &our_privkey, update_1);
8717
8718		// Set the fee on channel 3 to 1 sat, max HTLC to 1M msat
8719		let update_3 = UnsignedChannelUpdate {
8720			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8721			short_channel_id: 3,
8722			timestamp: 2,
8723			message_flags: 1, // Only must_be_one
8724			channel_flags: 0,
8725			cltv_expiry_delta: (3 << 4) | 1,
8726			htlc_minimum_msat: 0,
8727			htlc_maximum_msat: 1_000_000,
8728			fee_base_msat: 1_000,
8729			fee_proportional_millionths: 0,
8730			excess_data: Vec::new(),
8731		};
8732		update_channel(&gossip_sync, &secp_ctx, &privkeys[0], update_3);
8733
8734		// Set the fee on channel 13 to 1 sat, max HTLC to 1M msat
8735		let update_13 = UnsignedChannelUpdate {
8736			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8737			short_channel_id: 13,
8738			timestamp: 2,
8739			message_flags: 1, // Only must_be_one
8740			channel_flags: 0,
8741			cltv_expiry_delta: (13 << 4) | 1,
8742			htlc_minimum_msat: 0,
8743			htlc_maximum_msat: 1_000_000,
8744			fee_base_msat: 1_000,
8745			fee_proportional_millionths: 0,
8746			excess_data: Vec::new(),
8747		};
8748		update_channel(&gossip_sync, &secp_ctx, &privkeys[7], update_13);
8749
8750		// Set the fee on channel 4 to 1 sat, max HTLC to 1M msat
8751		let update_4 = UnsignedChannelUpdate {
8752			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8753			short_channel_id: 4,
8754			timestamp: 2,
8755			message_flags: 1, // Only must_be_one
8756			channel_flags: 0,
8757			cltv_expiry_delta: (4 << 4) | 1,
8758			htlc_minimum_msat: 0,
8759			htlc_maximum_msat: 1_000_000,
8760			fee_base_msat: 1_000,
8761			fee_proportional_millionths: 0,
8762			excess_data: Vec::new(),
8763		};
8764		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], update_4);
8765
8766		// The router will attempt to gather 3x the requested amount, and if it finds the new path
8767		// through channel 16, added below, it'll always prefer that, even prior to the changes
8768		// which introduced this test.
8769		// Instead, we add 6 additional channels so that the pathfinder always just gathers useless
8770		// paths first.
8771		for i in 0..6 {
8772			// Finally, create a single channel with fee of 2 sat from node 1 to node 2 which allows
8773			// for a larger payment.
8774			let chan_features = ChannelFeatures::from_le_bytes(vec![]);
8775			add_channel(&gossip_sync, &secp_ctx, &privkeys[7], &privkeys[2], chan_features, i + 42);
8776
8777			// Set the fee on channel 16 to 2 sats, max HTLC to 3M msat
8778			let update_a = UnsignedChannelUpdate {
8779				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8780				short_channel_id: i + 42,
8781				timestamp: 2,
8782				message_flags: 1, // Only must_be_one
8783				channel_flags: 0,
8784				cltv_expiry_delta: (42 << 4) | 1,
8785				htlc_minimum_msat: 0,
8786				htlc_maximum_msat: 1_000_000,
8787				fee_base_msat: 1_000,
8788				fee_proportional_millionths: 0,
8789				excess_data: Vec::new(),
8790			};
8791			update_channel(&gossip_sync, &secp_ctx, &privkeys[7], update_a);
8792
8793			// Enable channel 16 by providing an update in both directions
8794			let update_b = UnsignedChannelUpdate {
8795				chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8796				short_channel_id: i + 42,
8797				timestamp: 2,
8798				message_flags: 1, // Only must_be_one
8799				channel_flags: 1,
8800				cltv_expiry_delta: (42 << 4) | 1,
8801				htlc_minimum_msat: 0,
8802				htlc_maximum_msat: 10_000_000,
8803				fee_base_msat: u32::MAX,
8804				fee_proportional_millionths: 0,
8805				excess_data: Vec::new(),
8806			};
8807			update_channel(&gossip_sync, &secp_ctx, &privkeys[2], update_b);
8808		}
8809
8810		// Ensure that we can build a route for 3M msat across the three paths to node 2.
8811		let config = UserConfig::default();
8812		let mut payment_params = PaymentParameters::from_node_id(nodes[2], 42)
8813			.with_bolt11_features(channelmanager::provided_bolt11_invoice_features(&config))
8814			.unwrap();
8815		payment_params.max_channel_saturation_power_of_half = 0;
8816		let route_params =
8817			RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
8818		let route = get_route(
8819			&our_id,
8820			&route_params,
8821			&network_graph.read_only(),
8822			None,
8823			Arc::clone(&logger),
8824			&scorer,
8825			&Default::default(),
8826			&random_seed_bytes,
8827		)
8828		.unwrap();
8829		assert_eq!(route.paths.len(), 3);
8830		for path in route.paths {
8831			assert_eq!(path.hops.len(), 2);
8832		}
8833
8834		// Finally, create a single channel with fee of 2 sat from node 1 to node 2 which allows
8835		// for a larger payment.
8836		let features_16 = ChannelFeatures::from_le_bytes(id_to_feature_flags(16));
8837		add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[2], features_16, 16);
8838
8839		// Set the fee on channel 16 to 2 sats, max HTLC to 3M msat
8840		let update_16_a = UnsignedChannelUpdate {
8841			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8842			short_channel_id: 16,
8843			timestamp: 2,
8844			message_flags: 1, // Only must_be_one
8845			channel_flags: 0,
8846			cltv_expiry_delta: (16 << 4) | 1,
8847			htlc_minimum_msat: 0,
8848			htlc_maximum_msat: 3_000_000,
8849			fee_base_msat: 2_000,
8850			fee_proportional_millionths: 0,
8851			excess_data: Vec::new(),
8852		};
8853		update_channel(&gossip_sync, &secp_ctx, &privkeys[1], update_16_a);
8854
8855		// Enable channel 16 by providing an update in both directions
8856		let update_16_b = UnsignedChannelUpdate {
8857			chain_hash: ChainHash::using_genesis_block(Network::Testnet),
8858			short_channel_id: 16,
8859			timestamp: 2,
8860			message_flags: 1, // Only must_be_one
8861			channel_flags: 1,
8862			cltv_expiry_delta: (16 << 4) | 1,
8863			htlc_minimum_msat: 0,
8864			htlc_maximum_msat: 10_000_000,
8865			fee_base_msat: u32::MAX,
8866			fee_proportional_millionths: 0,
8867			excess_data: Vec::new(),
8868		};
8869		update_channel(&gossip_sync, &secp_ctx, &privkeys[2], update_16_b);
8870
8871		// Ensure that we now build a route for 3M msat across just the new path
8872		let route = get_route(
8873			&our_id,
8874			&route_params,
8875			&network_graph.read_only(),
8876			None,
8877			Arc::clone(&logger),
8878			&scorer,
8879			&Default::default(),
8880			&random_seed_bytes,
8881		)
8882		.unwrap();
8883		assert_eq!(route.paths.len(), 1);
8884		assert_eq!(route.paths[0].hops.len(), 2);
8885		assert_eq!(route.paths[0].hops[1].short_channel_id, 16);
8886	}
8887}
8888
8889#[cfg(any(test, ldk_bench))]
8890pub(crate) mod bench_utils {
8891	use super::*;
8892	use std::fs::File;
8893	use std::io::Read;
8894	use bitcoin::hashes::Hash;
8895	use bitcoin::secp256k1::SecretKey;
8896
8897	use crate::chain::transaction::OutPoint;
8898	use crate::routing::scoring::{ProbabilisticScorer, ScoreUpdate};
8899	use crate::ln::channel_state::{ChannelCounterparty, ChannelShutdownState};
8900	use crate::ln::channelmanager;
8901	use crate::ln::types::ChannelId;
8902	use crate::util::config::UserConfig;
8903	use crate::util::test_utils::TestLogger;
8904	use crate::sync::Arc;
8905
8906	/// Tries to open a network graph file, or panics with a URL to fetch it.
8907	pub(crate) fn get_graph_scorer_file() -> Result<(std::fs::File, std::fs::File), &'static str> {
8908		let load_file = |fname, err_str| {
8909			File::open(fname) // By default we're run in RL/lightning
8910				.or_else(|_| File::open(&format!("lightning/{}", fname))) // We may be run manually in RL/
8911				.or_else(|_| { // Fall back to guessing based on the binary location
8912					// path is likely something like .../rust-lightning/target/debug/deps/lightning-...
8913					let mut path = std::env::current_exe().unwrap();
8914					path.pop(); // lightning-...
8915					path.pop(); // deps
8916					path.pop(); // debug
8917					path.pop(); // target
8918					path.push("lightning");
8919					path.push(fname);
8920					File::open(path)
8921				})
8922				.or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
8923					// path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
8924					let mut path = std::env::current_exe().unwrap();
8925					path.pop(); // bench...
8926					path.pop(); // deps
8927					path.pop(); // debug
8928					path.pop(); // target
8929					path.pop(); // bench
8930					path.push("lightning");
8931					path.push(fname);
8932					File::open(path)
8933				})
8934			.map_err(|_| err_str)
8935		};
8936		let graph_res = load_file(
8937			"net_graph-2023-12-10.bin",
8938			"Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.118-2023-12-10.bin and place it at lightning/net_graph-2023-12-10.bin"
8939		);
8940		let scorer_res = load_file(
8941			"scorer-2023-12-10.bin",
8942			"Please fetch https://bitcoin.ninja/ldk-scorer-v0.0.118-2023-12-10.bin and place it at lightning/scorer-2023-12-10.bin"
8943		);
8944		#[cfg(require_route_graph_test)]
8945		return Ok((graph_res.unwrap(), scorer_res.unwrap()));
8946		#[cfg(not(require_route_graph_test))]
8947		return Ok((graph_res?, scorer_res?));
8948	}
8949
8950	pub(crate) fn read_graph_scorer(logger: &TestLogger)
8951	-> Result<(Arc<NetworkGraph<&TestLogger>>, ProbabilisticScorer<Arc<NetworkGraph<&TestLogger>>, &TestLogger>), &'static str> {
8952		let (mut graph_file, mut scorer_file) = get_graph_scorer_file()?;
8953		let mut graph_buffer = Vec::new();
8954		let mut scorer_buffer = Vec::new();
8955		graph_file.read_to_end(&mut graph_buffer).unwrap();
8956		scorer_file.read_to_end(&mut scorer_buffer).unwrap();
8957		let graph = Arc::new(NetworkGraph::read(&mut &graph_buffer[..], logger).unwrap());
8958		let scorer_args = (Default::default(), Arc::clone(&graph), logger);
8959		let scorer = ProbabilisticScorer::read(&mut &scorer_buffer[..], scorer_args).unwrap();
8960		Ok((graph, scorer))
8961	}
8962
8963	pub(crate) fn payer_pubkey() -> PublicKey {
8964		let secp_ctx = Secp256k1::new();
8965		PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
8966	}
8967
8968	#[inline]
8969	pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
8970		#[allow(deprecated)] // TODO: Remove once balance_msat is removed.
8971		ChannelDetails {
8972			channel_id: ChannelId::new_zero(),
8973			counterparty: ChannelCounterparty {
8974				features: channelmanager::provided_init_features(&UserConfig::default()),
8975				node_id,
8976				unspendable_punishment_reserve: 0,
8977				forwarding_info: None,
8978				outbound_htlc_minimum_msat: None,
8979				outbound_htlc_maximum_msat: None,
8980			},
8981			funding_txo: Some(OutPoint {
8982				txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
8983			}),
8984			channel_type: None,
8985			short_channel_id: Some(1),
8986			inbound_scid_alias: None,
8987			outbound_scid_alias: None,
8988			channel_value_satoshis: 10_000_000_000,
8989			user_channel_id: 0,
8990			outbound_capacity_msat: 10_000_000_000,
8991			next_outbound_htlc_minimum_msat: 0,
8992			next_outbound_htlc_limit_msat: 10_000_000_000,
8993			inbound_capacity_msat: 0,
8994			unspendable_punishment_reserve: None,
8995			confirmations_required: None,
8996			confirmations: None,
8997			force_close_spend_delay: None,
8998			is_outbound: true,
8999			is_channel_ready: true,
9000			is_usable: true,
9001			is_announced: true,
9002			inbound_htlc_minimum_msat: None,
9003			inbound_htlc_maximum_msat: None,
9004			config: None,
9005			feerate_sat_per_1000_weight: None,
9006			channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
9007			pending_inbound_htlcs: Vec::new(),
9008			pending_outbound_htlcs: Vec::new(),
9009		}
9010	}
9011
9012	pub(crate) fn generate_test_routes<S: ScoreLookUp + ScoreUpdate>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
9013		score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, mut seed: u64,
9014		starting_amount: u64, route_count: usize,
9015	) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
9016		let payer = payer_pubkey();
9017		let random_seed_bytes = [42; 32];
9018
9019		let nodes = graph.read_only().nodes().clone();
9020		let mut route_endpoints = Vec::new();
9021		for _ in 0..route_count {
9022			loop {
9023				seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
9024				let src = PublicKey::from_slice(nodes.unordered_keys()
9025					.skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
9026				seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
9027				let dst = PublicKey::from_slice(nodes.unordered_keys()
9028					.skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
9029				let params = PaymentParameters::from_node_id(dst, 42)
9030					.with_bolt11_features(features.clone()).unwrap();
9031				let first_hop = first_hop(src);
9032				let amt_msat = starting_amount + seed % 1_000_000;
9033				let route_params = RouteParameters::from_payment_params_and_value(
9034					params.clone(), amt_msat);
9035				let path_exists =
9036					get_route(&payer, &route_params, &graph.read_only(), Some(&[&first_hop]),
9037						&TestLogger::new(), scorer, score_params, &random_seed_bytes).is_ok();
9038				if path_exists {
9039					route_endpoints.push((first_hop, params, amt_msat));
9040					break;
9041				}
9042			}
9043		}
9044
9045		route_endpoints
9046	}
9047}
9048
9049#[cfg(ldk_bench)]
9050pub mod benches {
9051	use super::*;
9052	use crate::routing::scoring::{ScoreUpdate, ScoreLookUp};
9053	use crate::ln::channelmanager;
9054	use crate::types::features::Bolt11InvoiceFeatures;
9055	use crate::routing::gossip::NetworkGraph;
9056	use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScoringFeeParameters};
9057	use crate::util::config::UserConfig;
9058	use crate::util::logger::{Logger, Record};
9059	use crate::util::test_utils::TestLogger;
9060
9061	use criterion::Criterion;
9062
9063	struct DummyLogger {}
9064	impl Logger for DummyLogger {
9065		fn log(&self, _record: Record) {}
9066	}
9067
9068	pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
9069		let logger = TestLogger::new();
9070		let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
9071		let scorer = FixedPenaltyScorer::with_penalty(0);
9072		generate_routes(bench, &network_graph, scorer, &Default::default(),
9073			Bolt11InvoiceFeatures::empty(), 0, "generate_routes_with_zero_penalty_scorer");
9074	}
9075
9076	pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
9077		let logger = TestLogger::new();
9078		let (network_graph, _) = bench_utils::read_graph_scorer(&logger).unwrap();
9079		let scorer = FixedPenaltyScorer::with_penalty(0);
9080		generate_routes(bench, &network_graph, scorer, &Default::default(),
9081			channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
9082			"generate_mpp_routes_with_zero_penalty_scorer");
9083	}
9084
9085	pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
9086		let logger = TestLogger::new();
9087		let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
9088		let params = ProbabilisticScoringFeeParameters::default();
9089		generate_routes(bench, &network_graph, scorer, &params, Bolt11InvoiceFeatures::empty(), 0,
9090			"generate_routes_with_probabilistic_scorer");
9091	}
9092
9093	pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
9094		let logger = TestLogger::new();
9095		let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
9096		let params = ProbabilisticScoringFeeParameters::default();
9097		generate_routes(bench, &network_graph, scorer, &params,
9098			channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
9099			"generate_mpp_routes_with_probabilistic_scorer");
9100	}
9101
9102	pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
9103		let logger = TestLogger::new();
9104		let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
9105		let params = ProbabilisticScoringFeeParameters::default();
9106		generate_routes(bench, &network_graph, scorer, &params,
9107			channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
9108			"generate_large_mpp_routes_with_probabilistic_scorer");
9109	}
9110
9111	pub fn generate_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
9112		let logger = TestLogger::new();
9113		let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
9114		let mut params = ProbabilisticScoringFeeParameters::default();
9115		params.linear_success_probability = false;
9116		generate_routes(bench, &network_graph, scorer, &params,
9117			channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
9118			"generate_routes_with_nonlinear_probabilistic_scorer");
9119	}
9120
9121	pub fn generate_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
9122		let logger = TestLogger::new();
9123		let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
9124		let mut params = ProbabilisticScoringFeeParameters::default();
9125		params.linear_success_probability = false;
9126		generate_routes(bench, &network_graph, scorer, &params,
9127			channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 0,
9128			"generate_mpp_routes_with_nonlinear_probabilistic_scorer");
9129	}
9130
9131	pub fn generate_large_mpp_routes_with_nonlinear_probabilistic_scorer(bench: &mut Criterion) {
9132		let logger = TestLogger::new();
9133		let (network_graph, scorer) = bench_utils::read_graph_scorer(&logger).unwrap();
9134		let mut params = ProbabilisticScoringFeeParameters::default();
9135		params.linear_success_probability = false;
9136		generate_routes(bench, &network_graph, scorer, &params,
9137			channelmanager::provided_bolt11_invoice_features(&UserConfig::default()), 100_000_000,
9138			"generate_large_mpp_routes_with_nonlinear_probabilistic_scorer");
9139	}
9140
9141	fn generate_routes<S: ScoreLookUp + ScoreUpdate>(
9142		bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
9143		score_params: &S::ScoreParams, features: Bolt11InvoiceFeatures, starting_amount: u64,
9144		bench_name: &'static str,
9145	) {
9146		// First, get 100 (source, destination) pairs for which route-getting actually succeeds...
9147		let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
9148
9149		// ...then benchmark finding paths between the nodes we learned.
9150		do_route_bench(bench, graph, scorer, score_params, bench_name, route_endpoints);
9151	}
9152
9153	#[inline(never)]
9154	fn do_route_bench<S: ScoreLookUp + ScoreUpdate>(
9155		bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, scorer: S,
9156		score_params: &S::ScoreParams, bench_name: &'static str,
9157		route_endpoints: Vec<(ChannelDetails, PaymentParameters, u64)>,
9158	) {
9159		let payer = bench_utils::payer_pubkey();
9160		let random_seed_bytes = [42; 32];
9161
9162		let mut idx = 0;
9163		bench.bench_function(bench_name, |b| b.iter(|| {
9164			let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
9165			let route_params = RouteParameters::from_payment_params_and_value(params.clone(), *amt);
9166			assert!(get_route(&payer, &route_params, &graph.read_only(), Some(&[first_hop]),
9167				&DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());
9168			idx += 1;
9169		}));
9170	}
9171}