Router: clean up Path construction
[rust-lightning] / lightning / src / routing / router.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! The router finds paths within a [`NetworkGraph`] for a payment.
11
12 use bitcoin::secp256k1::PublicKey;
13 use bitcoin::hashes::Hash;
14 use bitcoin::hashes::sha256::Hash as Sha256;
15
16 use crate::blinded_path::{BlindedHop, BlindedPath};
17 use crate::ln::PaymentHash;
18 use crate::ln::channelmanager::{ChannelDetails, PaymentId};
19 use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, InvoiceFeatures, NodeFeatures};
20 use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use crate::offers::invoice::{BlindedPayInfo, Invoice as Bolt12Invoice};
22 use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
23 use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
24 use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
25 use crate::util::logger::{Level, Logger};
26 use crate::util::chacha20::ChaCha20;
27
28 use crate::io;
29 use crate::prelude::*;
30 use crate::sync::{Mutex, MutexGuard};
31 use alloc::collections::BinaryHeap;
32 use core::{cmp, fmt};
33 use core::ops::Deref;
34
35 /// A [`Router`] implemented using [`find_route`].
36 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> where
37         L::Target: Logger,
38         S::Target: for <'a> LockableScore<'a, Locked = MutexGuard<'a, Sc>>,
39 {
40         network_graph: G,
41         logger: L,
42         random_seed_bytes: Mutex<[u8; 32]>,
43         scorer: S,
44         score_params: SP
45 }
46
47 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Score<ScoreParams = SP>> DefaultRouter<G, L, S, SP, Sc> where
48         L::Target: Logger,
49         S::Target: for <'a> LockableScore<'a, Locked = MutexGuard<'a, Sc>>,
50 {
51         /// Creates a new router.
52         pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S, score_params: SP) -> Self {
53                 let random_seed_bytes = Mutex::new(random_seed_bytes);
54                 Self { network_graph, logger, random_seed_bytes, scorer, score_params }
55         }
56 }
57
58 impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref,  SP: Sized, Sc: Score<ScoreParams = SP>> Router for DefaultRouter<G, L, S, SP, Sc> where
59         L::Target: Logger,
60         S::Target: for <'a> LockableScore<'a, Locked = MutexGuard<'a, Sc>>,
61 {
62         fn find_route(
63                 &self,
64                 payer: &PublicKey,
65                 params: &RouteParameters,
66                 first_hops: Option<&[&ChannelDetails]>,
67                 inflight_htlcs: &InFlightHtlcs
68         ) -> Result<Route, LightningError> {
69                 let random_seed_bytes = {
70                         let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
71                         *locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
72                         *locked_random_seed_bytes
73                 };
74                 find_route(
75                         payer, params, &self.network_graph, first_hops, &*self.logger,
76                         &ScorerAccountingForInFlightHtlcs::new(self.scorer.lock(), inflight_htlcs),
77                         &self.score_params,
78                         &random_seed_bytes
79                 )
80         }
81 }
82
83 /// A trait defining behavior for routing a payment.
84 pub trait Router {
85         /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
86         fn find_route(
87                 &self, payer: &PublicKey, route_params: &RouteParameters,
88                 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
89         ) -> Result<Route, LightningError>;
90         /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
91         /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
92         fn find_route_with_id(
93                 &self, payer: &PublicKey, route_params: &RouteParameters,
94                 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
95                 _payment_hash: PaymentHash, _payment_id: PaymentId
96         ) -> Result<Route, LightningError> {
97                 self.find_route(payer, route_params, first_hops, inflight_htlcs)
98         }
99 }
100
101 /// [`Score`] implementation that factors in in-flight HTLC liquidity.
102 ///
103 /// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
104 /// [`find_route`].
105 ///
106 /// [`Score`]: crate::routing::scoring::Score
107 pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
108         scorer: S,
109         // Maps a channel's short channel id and its direction to the liquidity used up.
110         inflight_htlcs: &'a InFlightHtlcs,
111 }
112
113 impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
114         /// Initialize a new `ScorerAccountingForInFlightHtlcs`.
115         pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
116                 ScorerAccountingForInFlightHtlcs {
117                         scorer,
118                         inflight_htlcs
119                 }
120         }
121 }
122
123 #[cfg(c_bindings)]
124 impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
125         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
126 }
127
128 impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
129         type ScoreParams = S::ScoreParams;
130         fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
131                 if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
132                         source, target, short_channel_id
133                 ) {
134                         let usage = ChannelUsage {
135                                 inflight_htlc_msat: usage.inflight_htlc_msat + used_liquidity,
136                                 ..usage
137                         };
138
139                         self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
140                 } else {
141                         self.scorer.channel_penalty_msat(short_channel_id, source, target, usage, score_params)
142                 }
143         }
144
145         fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64) {
146                 self.scorer.payment_path_failed(path, short_channel_id)
147         }
148
149         fn payment_path_successful(&mut self, path: &Path) {
150                 self.scorer.payment_path_successful(path)
151         }
152
153         fn probe_failed(&mut self, path: &Path, short_channel_id: u64) {
154                 self.scorer.probe_failed(path, short_channel_id)
155         }
156
157         fn probe_successful(&mut self, path: &Path) {
158                 self.scorer.probe_successful(path)
159         }
160 }
161
162 /// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
163 /// in-use channel liquidity.
164 #[derive(Clone)]
165 pub struct InFlightHtlcs(
166         // A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
167         // is traveling in. The direction boolean is determined by checking if the HTLC source's public
168         // key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
169         // details.
170         HashMap<(u64, bool), u64>
171 );
172
173 impl InFlightHtlcs {
174         /// Constructs an empty `InFlightHtlcs`.
175         pub fn new() -> Self { InFlightHtlcs(HashMap::new()) }
176
177         /// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
178         pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
179                 if path.hops.is_empty() { return };
180
181                 let mut cumulative_msat = 0;
182                 if let Some(tail) = &path.blinded_tail {
183                         cumulative_msat += tail.final_value_msat;
184                 }
185
186                 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
187                 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
188                 // the router excludes the payer node. In the following lines, the payer's information is
189                 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
190                 // in our sliding window of two.
191                 let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
192                         .map(|hop| hop.pubkey)
193                         .chain(core::iter::once(payer_node_id));
194
195                 // Taking the reversed vector from above, we zip it with just the reversed hops list to
196                 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
197                 // the total amount sent.
198                 for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
199                         cumulative_msat += next_hop.fee_msat;
200                         self.0
201                                 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
202                                 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
203                                 .or_insert(cumulative_msat);
204                 }
205         }
206
207         /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
208         /// id.
209         pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
210                 self.0.get(&(channel_scid, source < target)).map(|v| *v)
211         }
212 }
213
214 impl Writeable for InFlightHtlcs {
215         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
216 }
217
218 impl Readable for InFlightHtlcs {
219         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
220                 let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
221                 Ok(Self(infight_map))
222         }
223 }
224
225 /// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
226 /// that leads to it.
227 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
228 pub struct RouteHop {
229         /// The node_id of the node at this hop.
230         pub pubkey: PublicKey,
231         /// The node_announcement features of the node at this hop. For the last hop, these may be
232         /// amended to match the features present in the invoice this node generated.
233         pub node_features: NodeFeatures,
234         /// The channel that should be used from the previous hop to reach this node.
235         pub short_channel_id: u64,
236         /// The channel_announcement features of the channel that should be used from the previous hop
237         /// to reach this node.
238         pub channel_features: ChannelFeatures,
239         /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
240         /// If this is the last hop in [`Path::hops`]:
241         /// * if we're sending to a [`BlindedPath`], this is the fee paid for use of the entire blinded path
242         /// * otherwise, this is the full value of this [`Path`]'s part of the payment
243         ///
244         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
245         pub fee_msat: u64,
246         /// The CLTV delta added for this hop.
247         /// If this is the last hop in [`Path::hops`]:
248         /// * if we're sending to a [`BlindedPath`], this is the CLTV delta for the entire blinded path
249         /// * otherwise, this is the CLTV delta expected at the destination
250         ///
251         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
252         pub cltv_expiry_delta: u32,
253 }
254
255 impl_writeable_tlv_based!(RouteHop, {
256         (0, pubkey, required),
257         (2, node_features, required),
258         (4, short_channel_id, required),
259         (6, channel_features, required),
260         (8, fee_msat, required),
261         (10, cltv_expiry_delta, required),
262 });
263
264 /// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
265 /// their BOLT12 [`Invoice`].
266 ///
267 /// [`Invoice`]: crate::offers::invoice::Invoice
268 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
269 pub struct BlindedTail {
270         /// The hops of the [`BlindedPath`] provided by the recipient.
271         ///
272         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
273         pub hops: Vec<BlindedHop>,
274         /// The blinding point of the [`BlindedPath`] provided by the recipient.
275         ///
276         /// [`BlindedPath`]: crate::blinded_path::BlindedPath
277         pub blinding_point: PublicKey,
278         /// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
279         /// inferring the destination. May be 0.
280         pub excess_final_cltv_expiry_delta: u32,
281         /// The total amount paid on this [`Path`], excluding the fees.
282         pub final_value_msat: u64,
283 }
284
285 impl_writeable_tlv_based!(BlindedTail, {
286         (0, hops, vec_type),
287         (2, blinding_point, required),
288         (4, excess_final_cltv_expiry_delta, required),
289         (6, final_value_msat, required),
290 });
291
292 /// A path in a [`Route`] to the payment recipient. Must always be at least length one.
293 /// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
294 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
295 pub struct Path {
296         /// The list of unblinded hops in this [`Path`]. Must be at least length one.
297         pub hops: Vec<RouteHop>,
298         /// The blinded path at which this path terminates, if we're sending to one, and its metadata.
299         pub blinded_tail: Option<BlindedTail>,
300 }
301
302 impl Path {
303         /// Gets the fees for a given path, excluding any excess paid to the recipient.
304         pub fn fee_msat(&self) -> u64 {
305                 match &self.blinded_tail {
306                         Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
307                         None => {
308                                 // Do not count last hop of each path since that's the full value of the payment
309                                 self.hops.split_last().map_or(0,
310                                         |(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
311                         }
312                 }
313         }
314
315         /// Gets the total amount paid on this [`Path`], excluding the fees.
316         pub fn final_value_msat(&self) -> u64 {
317                 match &self.blinded_tail {
318                         Some(blinded_tail) => blinded_tail.final_value_msat,
319                         None => self.hops.last().map_or(0, |hop| hop.fee_msat)
320                 }
321         }
322
323         /// Gets the final hop's CLTV expiry delta.
324         pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
325                 match &self.blinded_tail {
326                         Some(_) => None,
327                         None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
328                 }
329         }
330 }
331
332 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
333 /// it can take multiple paths. Each path is composed of one or more hops through the network.
334 #[derive(Clone, Hash, PartialEq, Eq)]
335 pub struct Route {
336         /// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
337         /// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
338         /// the same.
339         pub paths: Vec<Path>,
340         /// The `payment_params` parameter passed to [`find_route`].
341         /// This is used by `ChannelManager` to track information which may be required for retries,
342         /// provided back to you via [`Event::PaymentPathFailed`].
343         ///
344         /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
345         pub payment_params: Option<PaymentParameters>,
346 }
347
348 impl Route {
349         /// Returns the total amount of fees paid on this [`Route`].
350         ///
351         /// This doesn't include any extra payment made to the recipient, which can happen in excess of
352         /// the amount passed to [`find_route`]'s `params.final_value_msat`.
353         pub fn get_total_fees(&self) -> u64 {
354                 self.paths.iter().map(|path| path.fee_msat()).sum()
355         }
356
357         /// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
358         /// requested if we had to reach htlc_minimum_msat.
359         pub fn get_total_amount(&self) -> u64 {
360                 self.paths.iter().map(|path| path.final_value_msat()).sum()
361         }
362 }
363
364 const SERIALIZATION_VERSION: u8 = 1;
365 const MIN_SERIALIZATION_VERSION: u8 = 1;
366
367 impl Writeable for Route {
368         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
369                 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
370                 (self.paths.len() as u64).write(writer)?;
371                 let mut blinded_tails = Vec::new();
372                 for path in self.paths.iter() {
373                         (path.hops.len() as u8).write(writer)?;
374                         for (idx, hop) in path.hops.iter().enumerate() {
375                                 hop.write(writer)?;
376                                 if let Some(blinded_tail) = &path.blinded_tail {
377                                         if blinded_tails.is_empty() {
378                                                 blinded_tails = Vec::with_capacity(path.hops.len());
379                                                 for _ in 0..idx {
380                                                         blinded_tails.push(None);
381                                                 }
382                                         }
383                                         blinded_tails.push(Some(blinded_tail));
384                                 } else if !blinded_tails.is_empty() { blinded_tails.push(None); }
385                         }
386                 }
387                 write_tlv_fields!(writer, {
388                         (1, self.payment_params, option),
389                         (2, blinded_tails, optional_vec),
390                 });
391                 Ok(())
392         }
393 }
394
395 impl Readable for Route {
396         fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
397                 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
398                 let path_count: u64 = Readable::read(reader)?;
399                 if path_count == 0 { return Err(DecodeError::InvalidValue); }
400                 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
401                 let mut min_final_cltv_expiry_delta = u32::max_value();
402                 for _ in 0..path_count {
403                         let hop_count: u8 = Readable::read(reader)?;
404                         let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
405                         for _ in 0..hop_count {
406                                 hops.push(Readable::read(reader)?);
407                         }
408                         if hops.is_empty() { return Err(DecodeError::InvalidValue); }
409                         min_final_cltv_expiry_delta =
410                                 cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
411                         paths.push(Path { hops, blinded_tail: None });
412                 }
413                 _init_and_read_tlv_fields!(reader, {
414                         (1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
415                         (2, blinded_tails, optional_vec),
416                 });
417                 let blinded_tails = blinded_tails.unwrap_or(Vec::new());
418                 if blinded_tails.len() != 0 {
419                         if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
420                         for (mut path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
421                                 path.blinded_tail = blinded_tail_opt;
422                         }
423                 }
424                 Ok(Route { paths, payment_params })
425         }
426 }
427
428 /// Parameters needed to find a [`Route`].
429 ///
430 /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
431 /// [`Event::PaymentPathFailed`].
432 ///
433 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
434 #[derive(Clone, Debug, PartialEq, Eq)]
435 pub struct RouteParameters {
436         /// The parameters of the failed payment path.
437         pub payment_params: PaymentParameters,
438
439         /// The amount in msats sent on the failed payment path.
440         pub final_value_msat: u64,
441 }
442
443 impl Writeable for RouteParameters {
444         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
445                 write_tlv_fields!(writer, {
446                         (0, self.payment_params, required),
447                         (2, self.final_value_msat, required),
448                         // LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
449                         // `RouteParameters` directly. For compatibility, we write it here.
450                         (4, self.payment_params.payee.final_cltv_expiry_delta(), option),
451                 });
452                 Ok(())
453         }
454 }
455
456 impl Readable for RouteParameters {
457         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
458                 _init_and_read_tlv_fields!(reader, {
459                         (0, payment_params, (required: ReadableArgs, 0)),
460                         (2, final_value_msat, required),
461                         (4, final_cltv_delta, option),
462                 });
463                 let mut payment_params: PaymentParameters = payment_params.0.unwrap();
464                 if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
465                         if final_cltv_expiry_delta == &0 {
466                                 *final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
467                         }
468                 }
469                 Ok(Self {
470                         payment_params,
471                         final_value_msat: final_value_msat.0.unwrap(),
472                 })
473         }
474 }
475
476 /// Maximum total CTLV difference we allow for a full payment path.
477 pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
478
479 /// Maximum number of paths we allow an (MPP) payment to have.
480 // The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
481 // limits, but for now more than 10 paths likely carries too much one-path failure.
482 pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
483
484 const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
485
486 // The median hop CLTV expiry delta currently seen in the network.
487 const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
488
489 // During routing, we only consider paths shorter than our maximum length estimate.
490 // In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
491 // field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
492 // estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
493 //
494 // We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
495 // 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
496 // (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
497 // (payment_secret and total_msat) = 93 bytes for the final hop.
498 // Since the length of the potentially included `payment_metadata` is unknown to us, we round
499 // down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
500 const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
501
502 /// Information used to route a payment.
503 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
504 pub struct PaymentParameters {
505         /// Information about the payee, such as their features and route hints for their channels.
506         pub payee: Payee,
507
508         /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
509         pub expiry_time: Option<u64>,
510
511         /// The maximum total CLTV delta we accept for the route.
512         /// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
513         pub max_total_cltv_expiry_delta: u32,
514
515         /// The maximum number of paths that may be used by (MPP) payments.
516         /// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
517         pub max_path_count: u8,
518
519         /// Selects the maximum share of a channel's total capacity which will be sent over a channel,
520         /// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
521         /// a lower value prefers to send larger MPP parts, potentially saturating channels and
522         /// increasing failure probability for those paths.
523         ///
524         /// Note that this restriction will be relaxed during pathfinding after paths which meet this
525         /// restriction have been found. While paths which meet this criteria will be searched for, it
526         /// is ultimately up to the scorer to select them over other paths.
527         ///
528         /// A value of 0 will allow payments up to and including a channel's total announced usable
529         /// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
530         ///
531         /// Default value: 2
532         pub max_channel_saturation_power_of_half: u8,
533
534         /// A list of SCIDs which this payment was previously attempted over and which caused the
535         /// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
536         /// these SCIDs.
537         pub previously_failed_channels: Vec<u64>,
538 }
539
540 impl Writeable for PaymentParameters {
541         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
542                 let mut clear_hints = &vec![];
543                 let mut blinded_hints = &vec![];
544                 match &self.payee {
545                         Payee::Clear { route_hints, .. } => clear_hints = route_hints,
546                         Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
547                 }
548                 write_tlv_fields!(writer, {
549                         (0, self.payee.node_id(), option),
550                         (1, self.max_total_cltv_expiry_delta, required),
551                         (2, self.payee.features(), option),
552                         (3, self.max_path_count, required),
553                         (4, *clear_hints, vec_type),
554                         (5, self.max_channel_saturation_power_of_half, required),
555                         (6, self.expiry_time, option),
556                         (7, self.previously_failed_channels, vec_type),
557                         (8, *blinded_hints, optional_vec),
558                         (9, self.payee.final_cltv_expiry_delta(), option),
559                 });
560                 Ok(())
561         }
562 }
563
564 impl ReadableArgs<u32> for PaymentParameters {
565         fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
566                 _init_and_read_tlv_fields!(reader, {
567                         (0, payee_pubkey, option),
568                         (1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
569                         (2, features, (option: ReadableArgs, payee_pubkey.is_some())),
570                         (3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
571                         (4, route_hints, vec_type),
572                         (5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
573                         (6, expiry_time, option),
574                         (7, previously_failed_channels, vec_type),
575                         (8, blinded_route_hints, optional_vec),
576                         (9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
577                 });
578                 let clear_route_hints = route_hints.unwrap_or(vec![]);
579                 let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
580                 let payee = if blinded_route_hints.len() != 0 {
581                         if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
582                         Payee::Blinded {
583                                 route_hints: blinded_route_hints,
584                                 features: features.and_then(|f: Features| f.bolt12()),
585                         }
586                 } else {
587                         Payee::Clear {
588                                 route_hints: clear_route_hints,
589                                 node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
590                                 features: features.and_then(|f| f.bolt11()),
591                                 final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
592                         }
593                 };
594                 Ok(Self {
595                         max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
596                         max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
597                         payee,
598                         max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
599                         expiry_time,
600                         previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
601                 })
602         }
603 }
604
605
606 impl PaymentParameters {
607         /// Creates a payee with the node id of the given `pubkey`.
608         ///
609         /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
610         /// provided.
611         pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
612                 Self {
613                         payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
614                         expiry_time: None,
615                         max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
616                         max_path_count: DEFAULT_MAX_PATH_COUNT,
617                         max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
618                         previously_failed_channels: Vec::new(),
619                 }
620         }
621
622         /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
623         ///
624         /// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
625         /// provided.
626         ///
627         /// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
628         /// whether your router will be allowed to find a multi-part route for this payment. If you
629         /// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
630         /// [`RecipientOnionFields::secret_only`].
631         ///
632         /// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
633         pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
634                 Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
635                         .with_bolt11_features(InvoiceFeatures::for_keysend(allow_mpp))
636                         .expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
637         }
638
639         /// Creates parameters for paying to a blinded payee from the provided invoice. Sets
640         /// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
641         /// [`PaymentParameters::expiry_time`].
642         pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
643                 Self::blinded(invoice.payment_paths().to_vec())
644                         .with_bolt12_features(invoice.features().clone()).unwrap()
645                         .with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
646         }
647
648         fn blinded(blinded_route_hints: Vec<(BlindedPayInfo, BlindedPath)>) -> Self {
649                 Self {
650                         payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
651                         expiry_time: None,
652                         max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
653                         max_path_count: DEFAULT_MAX_PATH_COUNT,
654                         max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
655                         previously_failed_channels: Vec::new(),
656                 }
657         }
658
659         /// Includes the payee's features. Errors if the parameters were not initialized with
660         /// [`PaymentParameters::from_bolt12_invoice`].
661         ///
662         /// This is not exported to bindings users since bindings don't support move semantics
663         pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
664                 match self.payee {
665                         Payee::Clear { .. } => Err(()),
666                         Payee::Blinded { route_hints, .. } =>
667                                 Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
668                 }
669         }
670
671         /// Includes the payee's features. Errors if the parameters were initialized with
672         /// [`PaymentParameters::from_bolt12_invoice`].
673         ///
674         /// This is not exported to bindings users since bindings don't support move semantics
675         pub fn with_bolt11_features(self, features: InvoiceFeatures) -> Result<Self, ()> {
676                 match self.payee {
677                         Payee::Blinded { .. } => Err(()),
678                         Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
679                                 Ok(Self {
680                                         payee: Payee::Clear {
681                                                 route_hints, node_id, features: Some(features), final_cltv_expiry_delta
682                                         }, ..self
683                                 })
684                 }
685         }
686
687         /// Includes hints for routing to the payee. Errors if the parameters were initialized with
688         /// [`PaymentParameters::from_bolt12_invoice`].
689         ///
690         /// This is not exported to bindings users since bindings don't support move semantics
691         pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
692                 match self.payee {
693                         Payee::Blinded { .. } => Err(()),
694                         Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
695                                 Ok(Self {
696                                         payee: Payee::Clear {
697                                                 route_hints, node_id, features, final_cltv_expiry_delta,
698                                         }, ..self
699                                 })
700                 }
701         }
702
703         /// Includes a payment expiration in seconds relative to the UNIX epoch.
704         ///
705         /// This is not exported to bindings users since bindings don't support move semantics
706         pub fn with_expiry_time(self, expiry_time: u64) -> Self {
707                 Self { expiry_time: Some(expiry_time), ..self }
708         }
709
710         /// Includes a limit for the total CLTV expiry delta which is considered during routing
711         ///
712         /// This is not exported to bindings users since bindings don't support move semantics
713         pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
714                 Self { max_total_cltv_expiry_delta, ..self }
715         }
716
717         /// Includes a limit for the maximum number of payment paths that may be used.
718         ///
719         /// This is not exported to bindings users since bindings don't support move semantics
720         pub fn with_max_path_count(self, max_path_count: u8) -> Self {
721                 Self { max_path_count, ..self }
722         }
723
724         /// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
725         /// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
726         ///
727         /// This is not exported to bindings users since bindings don't support move semantics
728         pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
729                 Self { max_channel_saturation_power_of_half, ..self }
730         }
731 }
732
733 /// The recipient of a payment, differing based on whether they've hidden their identity with route
734 /// blinding.
735 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
736 pub enum Payee {
737         /// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
738         /// will be included in the final [`Route`].
739         Blinded {
740                 /// Aggregated routing info and blinded paths, for routing to the payee without knowing their
741                 /// node id.
742                 route_hints: Vec<(BlindedPayInfo, BlindedPath)>,
743                 /// Features supported by the payee.
744                 ///
745                 /// May be set from the payee's invoice. May be `None` if the invoice does not contain any
746                 /// features.
747                 features: Option<Bolt12InvoiceFeatures>,
748         },
749         /// The recipient included these route hints in their BOLT11 invoice.
750         Clear {
751                 /// The node id of the payee.
752                 node_id: PublicKey,
753                 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
754                 route_hints: Vec<RouteHint>,
755                 /// Features supported by the payee.
756                 ///
757                 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
758                 /// does not contain any features.
759                 ///
760                 /// [`for_keysend`]: PaymentParameters::for_keysend
761                 features: Option<InvoiceFeatures>,
762                 /// The minimum CLTV delta at the end of the route. This value must not be zero.
763                 final_cltv_expiry_delta: u32,
764         },
765 }
766
767 impl Payee {
768         fn node_id(&self) -> Option<PublicKey> {
769                 match self {
770                         Self::Clear { node_id, .. } => Some(*node_id),
771                         _ => None,
772                 }
773         }
774         fn node_features(&self) -> Option<NodeFeatures> {
775                 match self {
776                         Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
777                         Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
778                 }
779         }
780         fn supports_basic_mpp(&self) -> bool {
781                 match self {
782                         Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
783                         Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
784                 }
785         }
786         fn features(&self) -> Option<FeaturesRef> {
787                 match self {
788                         Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
789                         Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
790                 }
791         }
792         fn final_cltv_expiry_delta(&self) -> Option<u32> {
793                 match self {
794                         Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
795                         _ => None,
796                 }
797         }
798 }
799
800 enum FeaturesRef<'a> {
801         Bolt11(&'a InvoiceFeatures),
802         Bolt12(&'a Bolt12InvoiceFeatures),
803 }
804 enum Features {
805         Bolt11(InvoiceFeatures),
806         Bolt12(Bolt12InvoiceFeatures),
807 }
808
809 impl Features {
810         fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
811                 match self {
812                         Self::Bolt12(f) => Some(f),
813                         _ => None,
814                 }
815         }
816         fn bolt11(self) -> Option<InvoiceFeatures> {
817                 match self {
818                         Self::Bolt11(f) => Some(f),
819                         _ => None,
820                 }
821         }
822 }
823
824 impl<'a> Writeable for FeaturesRef<'a> {
825         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
826                 match self {
827                         Self::Bolt11(f) => Ok(f.write(w)?),
828                         Self::Bolt12(f) => Ok(f.write(w)?),
829                 }
830         }
831 }
832
833 impl ReadableArgs<bool> for Features {
834         fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
835                 if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
836                 Ok(Self::Bolt12(Readable::read(reader)?))
837         }
838 }
839
840 /// A list of hops along a payment path terminating with a channel to the recipient.
841 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
842 pub struct RouteHint(pub Vec<RouteHintHop>);
843
844 impl Writeable for RouteHint {
845         fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
846                 (self.0.len() as u64).write(writer)?;
847                 for hop in self.0.iter() {
848                         hop.write(writer)?;
849                 }
850                 Ok(())
851         }
852 }
853
854 impl Readable for RouteHint {
855         fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
856                 let hop_count: u64 = Readable::read(reader)?;
857                 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
858                 for _ in 0..hop_count {
859                         hops.push(Readable::read(reader)?);
860                 }
861                 Ok(Self(hops))
862         }
863 }
864
865 /// A channel descriptor for a hop along a payment path.
866 #[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
867 pub struct RouteHintHop {
868         /// The node_id of the non-target end of the route
869         pub src_node_id: PublicKey,
870         /// The short_channel_id of this channel
871         pub short_channel_id: u64,
872         /// The fees which must be paid to use this channel
873         pub fees: RoutingFees,
874         /// The difference in CLTV values between this node and the next node.
875         pub cltv_expiry_delta: u16,
876         /// The minimum value, in msat, which must be relayed to the next hop.
877         pub htlc_minimum_msat: Option<u64>,
878         /// The maximum value in msat available for routing with a single HTLC.
879         pub htlc_maximum_msat: Option<u64>,
880 }
881
882 impl_writeable_tlv_based!(RouteHintHop, {
883         (0, src_node_id, required),
884         (1, htlc_minimum_msat, option),
885         (2, short_channel_id, required),
886         (3, htlc_maximum_msat, option),
887         (4, fees, required),
888         (6, cltv_expiry_delta, required),
889 });
890
891 #[derive(Eq, PartialEq)]
892 struct RouteGraphNode {
893         node_id: NodeId,
894         lowest_fee_to_node: u64,
895         total_cltv_delta: u32,
896         // The maximum value a yet-to-be-constructed payment path might flow through this node.
897         // This value is upper-bounded by us by:
898         // - how much is needed for a path being constructed
899         // - how much value can channels following this node (up to the destination) can contribute,
900         //   considering their capacity and fees
901         value_contribution_msat: u64,
902         /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
903         /// minimum, we use it, plus the fees required at each earlier hop to meet it.
904         path_htlc_minimum_msat: u64,
905         /// All penalties incurred from this hop on the way to the destination, as calculated using
906         /// channel scoring.
907         path_penalty_msat: u64,
908         /// The number of hops walked up to this node.
909         path_length_to_node: u8,
910 }
911
912 impl cmp::Ord for RouteGraphNode {
913         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
914                 let other_score = cmp::max(other.lowest_fee_to_node, other.path_htlc_minimum_msat)
915                         .saturating_add(other.path_penalty_msat);
916                 let self_score = cmp::max(self.lowest_fee_to_node, self.path_htlc_minimum_msat)
917                         .saturating_add(self.path_penalty_msat);
918                 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
919         }
920 }
921
922 impl cmp::PartialOrd for RouteGraphNode {
923         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
924                 Some(self.cmp(other))
925         }
926 }
927
928 /// A wrapper around the various hop representations.
929 ///
930 /// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
931 #[derive(Clone, Debug)]
932 enum CandidateRouteHop<'a> {
933         /// A hop from the payer, where the outbound liquidity is known.
934         FirstHop {
935                 details: &'a ChannelDetails,
936         },
937         /// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
938         PublicHop {
939                 info: DirectedChannelInfo<'a>,
940                 short_channel_id: u64,
941         },
942         /// A hop to the payee found in the BOLT 11 payment invoice, though not necessarily a direct
943         /// channel.
944         PrivateHop {
945                 hint: &'a RouteHintHop,
946         },
947         /// The payee's identity is concealed behind blinded paths provided in a BOLT 12 invoice.
948         Blinded {
949                 hint: &'a (BlindedPayInfo, BlindedPath),
950                 hint_idx: usize,
951         },
952         /// Similar to [`Self::Blinded`], but the path here has 1 blinded hop. `BlindedPayInfo` provided
953         /// for 1-hop blinded paths is ignored because it is meant to apply to the hops *between* the
954         /// introduction node and the destination. Useful for tracking that we need to include a blinded
955         /// path at the end of our [`Route`].
956         OneHopBlinded {
957                 hint: &'a (BlindedPayInfo, BlindedPath),
958                 hint_idx: usize,
959         },
960 }
961
962 impl<'a> CandidateRouteHop<'a> {
963         fn short_channel_id(&self) -> Option<u64> {
964                 match self {
965                         CandidateRouteHop::FirstHop { details } => Some(details.get_outbound_payment_scid().unwrap()),
966                         CandidateRouteHop::PublicHop { short_channel_id, .. } => Some(*short_channel_id),
967                         CandidateRouteHop::PrivateHop { hint } => Some(hint.short_channel_id),
968                         CandidateRouteHop::Blinded { .. } => None,
969                         CandidateRouteHop::OneHopBlinded { .. } => None,
970                 }
971         }
972
973         // NOTE: This may alloc memory so avoid calling it in a hot code path.
974         fn features(&self) -> ChannelFeatures {
975                 match self {
976                         CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
977                         CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
978                         CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
979                         CandidateRouteHop::Blinded { .. } => ChannelFeatures::empty(),
980                         CandidateRouteHop::OneHopBlinded { .. } => ChannelFeatures::empty(),
981                 }
982         }
983
984         fn cltv_expiry_delta(&self) -> u32 {
985                 match self {
986                         CandidateRouteHop::FirstHop { .. } => 0,
987                         CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
988                         CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
989                         CandidateRouteHop::Blinded { hint, .. } => hint.0.cltv_expiry_delta as u32,
990                         CandidateRouteHop::OneHopBlinded { .. } => 0,
991                 }
992         }
993
994         fn htlc_minimum_msat(&self) -> u64 {
995                 match self {
996                         CandidateRouteHop::FirstHop { details } => details.next_outbound_htlc_minimum_msat,
997                         CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
998                         CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
999                         CandidateRouteHop::Blinded { hint, .. } => hint.0.htlc_minimum_msat,
1000                         CandidateRouteHop::OneHopBlinded { .. } => 0,
1001                 }
1002         }
1003
1004         fn fees(&self) -> RoutingFees {
1005                 match self {
1006                         CandidateRouteHop::FirstHop { .. } => RoutingFees {
1007                                 base_msat: 0, proportional_millionths: 0,
1008                         },
1009                         CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
1010                         CandidateRouteHop::PrivateHop { hint } => hint.fees,
1011                         CandidateRouteHop::Blinded { hint, .. } => {
1012                                 RoutingFees {
1013                                         base_msat: hint.0.fee_base_msat,
1014                                         proportional_millionths: hint.0.fee_proportional_millionths
1015                                 }
1016                         },
1017                         CandidateRouteHop::OneHopBlinded { .. } =>
1018                                 RoutingFees { base_msat: 0, proportional_millionths: 0 },
1019                 }
1020         }
1021
1022         fn effective_capacity(&self) -> EffectiveCapacity {
1023                 match self {
1024                         CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
1025                                 liquidity_msat: details.next_outbound_htlc_limit_msat,
1026                         },
1027                         CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
1028                         CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: Some(max), .. }} =>
1029                                 EffectiveCapacity::HintMaxHTLC { amount_msat: *max },
1030                         CandidateRouteHop::PrivateHop { hint: RouteHintHop { htlc_maximum_msat: None, .. }} =>
1031                                 EffectiveCapacity::Infinite,
1032                         CandidateRouteHop::Blinded { hint, .. } =>
1033                                 EffectiveCapacity::HintMaxHTLC { amount_msat: hint.0.htlc_maximum_msat },
1034                         CandidateRouteHop::OneHopBlinded { .. } => EffectiveCapacity::Infinite,
1035                 }
1036         }
1037
1038         fn id(&self, channel_direction: bool /* src_node_id < target_node_id */) -> CandidateHopId {
1039                 match self {
1040                         CandidateRouteHop::Blinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1041                         CandidateRouteHop::OneHopBlinded { hint_idx, .. } => CandidateHopId::Blinded(*hint_idx),
1042                         _ => CandidateHopId::Clear((self.short_channel_id().unwrap(), channel_direction)),
1043                 }
1044         }
1045 }
1046
1047 #[derive(Clone, Copy, Eq, Hash, Ord, PartialOrd, PartialEq)]
1048 enum CandidateHopId {
1049         /// Contains (scid, src_node_id < target_node_id)
1050         Clear((u64, bool)),
1051         /// Index of the blinded route hint in [`Payee::Blinded::route_hints`].
1052         Blinded(usize),
1053 }
1054
1055 #[inline]
1056 fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
1057         let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
1058         match capacity {
1059                 EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
1060                 EffectiveCapacity::Infinite => u64::max_value(),
1061                 EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
1062                 EffectiveCapacity::AdvertisedMaxHTLC { amount_msat } =>
1063                         amount_msat.checked_shr(saturation_shift).unwrap_or(0),
1064                 // Treat htlc_maximum_msat from a route hint as an exact liquidity amount, since the invoice is
1065                 // expected to have been generated from up-to-date capacity information.
1066                 EffectiveCapacity::HintMaxHTLC { amount_msat } => amount_msat,
1067                 EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
1068                         cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
1069         }
1070 }
1071
1072 fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
1073 -> bool where I1::Item: PartialEq<I2::Item> {
1074         loop {
1075                 let a = iter_a.next();
1076                 let b = iter_b.next();
1077                 if a.is_none() && b.is_none() { return true; }
1078                 if a.is_none() || b.is_none() { return false; }
1079                 if a.unwrap().ne(&b.unwrap()) { return false; }
1080         }
1081 }
1082
1083 /// It's useful to keep track of the hops associated with the fees required to use them,
1084 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
1085 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
1086 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
1087 #[derive(Clone)]
1088 struct PathBuildingHop<'a> {
1089         // Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
1090         // is a larger refactor and will require careful performance analysis.
1091         node_id: NodeId,
1092         candidate: CandidateRouteHop<'a>,
1093         fee_msat: u64,
1094
1095         /// All the fees paid *after* this channel on the way to the destination
1096         next_hops_fee_msat: u64,
1097         /// Fee paid for the use of the current channel (see candidate.fees()).
1098         /// The value will be actually deducted from the counterparty balance on the previous link.
1099         hop_use_fee_msat: u64,
1100         /// Used to compare channels when choosing the for routing.
1101         /// Includes paying for the use of a hop and the following hops, as well as
1102         /// an estimated cost of reaching this hop.
1103         /// Might get stale when fees are recomputed. Primarily for internal use.
1104         total_fee_msat: u64,
1105         /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
1106         /// walk and may be invalid thereafter.
1107         path_htlc_minimum_msat: u64,
1108         /// All penalties incurred from this channel on the way to the destination, as calculated using
1109         /// channel scoring.
1110         path_penalty_msat: u64,
1111         /// If we've already processed a node as the best node, we shouldn't process it again. Normally
1112         /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
1113         /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
1114         /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
1115         /// avoid processing them again.
1116         was_processed: bool,
1117         #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1118         // In tests, we apply further sanity checks on cases where we skip nodes we already processed
1119         // to ensure it is specifically in cases where the fee has gone down because of a decrease in
1120         // value_contribution_msat, which requires tracking it here. See comments below where it is
1121         // used for more info.
1122         value_contribution_msat: u64,
1123 }
1124
1125 impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
1126         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
1127                 let mut debug_struct = f.debug_struct("PathBuildingHop");
1128                 debug_struct
1129                         .field("node_id", &self.node_id)
1130                         .field("short_channel_id", &self.candidate.short_channel_id())
1131                         .field("total_fee_msat", &self.total_fee_msat)
1132                         .field("next_hops_fee_msat", &self.next_hops_fee_msat)
1133                         .field("hop_use_fee_msat", &self.hop_use_fee_msat)
1134                         .field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
1135                         .field("path_penalty_msat", &self.path_penalty_msat)
1136                         .field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
1137                         .field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
1138                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1139                 let debug_struct = debug_struct
1140                         .field("value_contribution_msat", &self.value_contribution_msat);
1141                 debug_struct.finish()
1142         }
1143 }
1144
1145 // Instantiated with a list of hops with correct data in them collected during path finding,
1146 // an instance of this struct should be further modified only via given methods.
1147 #[derive(Clone)]
1148 struct PaymentPath<'a> {
1149         hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
1150 }
1151
1152 impl<'a> PaymentPath<'a> {
1153         // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
1154         fn get_value_msat(&self) -> u64 {
1155                 self.hops.last().unwrap().0.fee_msat
1156         }
1157
1158         fn get_path_penalty_msat(&self) -> u64 {
1159                 self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
1160         }
1161
1162         fn get_total_fee_paid_msat(&self) -> u64 {
1163                 if self.hops.len() < 1 {
1164                         return 0;
1165                 }
1166                 let mut result = 0;
1167                 // Can't use next_hops_fee_msat because it gets outdated.
1168                 for (i, (hop, _)) in self.hops.iter().enumerate() {
1169                         if i != self.hops.len() - 1 {
1170                                 result += hop.fee_msat;
1171                         }
1172                 }
1173                 return result;
1174         }
1175
1176         fn get_cost_msat(&self) -> u64 {
1177                 self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
1178         }
1179
1180         // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
1181         // to change fees may result in an inconsistency.
1182         //
1183         // Sometimes we call this function right after constructing a path which is inconsistent in
1184         // that it the value being transferred has decreased while we were doing path finding, leading
1185         // to the fees being paid not lining up with the actual limits.
1186         //
1187         // Note that this function is not aware of the available_liquidity limit, and thus does not
1188         // support increasing the value being transferred beyond what was selected during the initial
1189         // routing passes.
1190         fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
1191                 let mut total_fee_paid_msat = 0 as u64;
1192                 for i in (0..self.hops.len()).rev() {
1193                         let last_hop = i == self.hops.len() - 1;
1194
1195                         // For non-last-hop, this value will represent the fees paid on the current hop. It
1196                         // will consist of the fees for the use of the next hop, and extra fees to match
1197                         // htlc_minimum_msat of the current channel. Last hop is handled separately.
1198                         let mut cur_hop_fees_msat = 0;
1199                         if !last_hop {
1200                                 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
1201                         }
1202
1203                         let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
1204                         cur_hop.next_hops_fee_msat = total_fee_paid_msat;
1205                         // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
1206                         // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
1207                         // set it too high just to maliciously take more fees by exploiting this
1208                         // match htlc_minimum_msat logic.
1209                         let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
1210                         if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
1211                                 // Note that there is a risk that *previous hops* (those closer to us, as we go
1212                                 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
1213                                 //
1214                                 // This might make us end up with a broken route, although this should be super-rare
1215                                 // in practice, both because of how healthy channels look like, and how we pick
1216                                 // channels in add_entry.
1217                                 // Also, this can't be exploited more heavily than *announce a free path and fail
1218                                 // all payments*.
1219                                 cur_hop_transferred_amount_msat += extra_fees_msat;
1220                                 total_fee_paid_msat += extra_fees_msat;
1221                                 cur_hop_fees_msat += extra_fees_msat;
1222                         }
1223
1224                         if last_hop {
1225                                 // Final hop is a special case: it usually has just value_msat (by design), but also
1226                                 // it still could overpay for the htlc_minimum_msat.
1227                                 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
1228                         } else {
1229                                 // Propagate updated fees for the use of the channels to one hop back, where they
1230                                 // will be actually paid (fee_msat). The last hop is handled above separately.
1231                                 cur_hop.fee_msat = cur_hop_fees_msat;
1232                         }
1233
1234                         // Fee for the use of the current hop which will be deducted on the previous hop.
1235                         // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
1236                         // this channel is free for us.
1237                         if i != 0 {
1238                                 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
1239                                         cur_hop.hop_use_fee_msat = new_fee;
1240                                         total_fee_paid_msat += new_fee;
1241                                 } else {
1242                                         // It should not be possible because this function is called only to reduce the
1243                                         // value. In that case, compute_fee was already called with the same fees for
1244                                         // larger amount and there was no overflow.
1245                                         unreachable!();
1246                                 }
1247                         }
1248                 }
1249         }
1250 }
1251
1252 #[inline(always)]
1253 /// Calculate the fees required to route the given amount over a channel with the given fees.
1254 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
1255         amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1256                 .and_then(|part| (channel_fees.base_msat as u64).checked_add(part / 1_000_000))
1257 }
1258
1259 #[inline(always)]
1260 /// Calculate the fees required to route the given amount over a channel with the given fees,
1261 /// saturating to [`u64::max_value`].
1262 fn compute_fees_saturating(amount_msat: u64, channel_fees: RoutingFees) -> u64 {
1263         amount_msat.checked_mul(channel_fees.proportional_millionths as u64)
1264                 .map(|prop| prop / 1_000_000).unwrap_or(u64::max_value())
1265                 .saturating_add(channel_fees.base_msat as u64)
1266 }
1267
1268 /// The default `features` we assume for a node in a route, when no `features` are known about that
1269 /// specific node.
1270 ///
1271 /// Default features are:
1272 /// * variable_length_onion_optional
1273 fn default_node_features() -> NodeFeatures {
1274         let mut features = NodeFeatures::empty();
1275         features.set_variable_length_onion_optional();
1276         features
1277 }
1278
1279 struct LoggedPayeePubkey(Option<PublicKey>);
1280 impl fmt::Display for LoggedPayeePubkey {
1281         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1282                 match self.0 {
1283                         Some(pk) => {
1284                                 "payee node id ".fmt(f)?;
1285                                 pk.fmt(f)
1286                         },
1287                         None => {
1288                                 "blinded payee".fmt(f)
1289                         },
1290                 }
1291         }
1292 }
1293
1294 struct LoggedCandidateHop<'a>(&'a CandidateRouteHop<'a>);
1295 impl<'a> fmt::Display for LoggedCandidateHop<'a> {
1296         fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1297                 match self.0 {
1298                         CandidateRouteHop::Blinded { hint, .. } | CandidateRouteHop::OneHopBlinded { hint, .. } => {
1299                                 "blinded route hint with introduction node id ".fmt(f)?;
1300                                 hint.1.introduction_node_id.fmt(f)?;
1301                                 " and blinding point ".fmt(f)?;
1302                                 hint.1.blinding_point.fmt(f)
1303                         },
1304                         _ => {
1305                                 "SCID ".fmt(f)?;
1306                                 self.0.short_channel_id().unwrap().fmt(f)
1307                         },
1308                 }
1309         }
1310 }
1311
1312 #[inline]
1313 fn sort_first_hop_channels(
1314         channels: &mut Vec<&ChannelDetails>, used_liquidities: &HashMap<CandidateHopId, u64>,
1315         recommended_value_msat: u64, our_node_pubkey: &PublicKey
1316 ) {
1317         // Sort the first_hops channels to the same node(s) in priority order of which channel we'd
1318         // most like to use.
1319         //
1320         // First, if channels are below `recommended_value_msat`, sort them in descending order,
1321         // preferring larger channels to avoid splitting the payment into more MPP parts than is
1322         // required.
1323         //
1324         // Second, because simply always sorting in descending order would always use our largest
1325         // available outbound capacity, needlessly fragmenting our available channel capacities,
1326         // sort channels above `recommended_value_msat` in ascending order, preferring channels
1327         // which have enough, but not too much, capacity for the payment.
1328         //
1329         // Available outbound balances factor in liquidity already reserved for previously found paths.
1330         channels.sort_unstable_by(|chan_a, chan_b| {
1331                 let chan_a_outbound_limit_msat = chan_a.next_outbound_htlc_limit_msat
1332                         .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_a.get_outbound_payment_scid().unwrap(),
1333                         our_node_pubkey < &chan_a.counterparty.node_id))).unwrap_or(&0));
1334                 let chan_b_outbound_limit_msat = chan_b.next_outbound_htlc_limit_msat
1335                         .saturating_sub(*used_liquidities.get(&CandidateHopId::Clear((chan_b.get_outbound_payment_scid().unwrap(),
1336                         our_node_pubkey < &chan_b.counterparty.node_id))).unwrap_or(&0));
1337                 if chan_b_outbound_limit_msat < recommended_value_msat || chan_a_outbound_limit_msat < recommended_value_msat {
1338                         // Sort in descending order
1339                         chan_b_outbound_limit_msat.cmp(&chan_a_outbound_limit_msat)
1340                 } else {
1341                         // Sort in ascending order
1342                         chan_a_outbound_limit_msat.cmp(&chan_b_outbound_limit_msat)
1343                 }
1344         });
1345 }
1346
1347 /// Finds a route from us (payer) to the given target node (payee).
1348 ///
1349 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
1350 /// Without this, MPP will only be used if the payee's features are available in the network graph.
1351 ///
1352 /// Private routing paths between a public node and the target may be included in `params.payee`.
1353 ///
1354 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
1355 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
1356 /// from `network_graph` will be ignored, and only those in `first_hops` will be used.
1357 ///
1358 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
1359 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
1360 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
1361 ///
1362 /// # Note
1363 ///
1364 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
1365 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
1366 /// function.
1367 ///
1368 /// # Panics
1369 ///
1370 /// Panics if first_hops contains channels without short_channel_ids;
1371 /// [`ChannelManager::list_usable_channels`] will never include such channels.
1372 ///
1373 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
1374 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1375 /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
1376 pub fn find_route<L: Deref, GL: Deref, S: Score>(
1377         our_node_pubkey: &PublicKey, route_params: &RouteParameters,
1378         network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
1379         scorer: &S, score_params: &S::ScoreParams, random_seed_bytes: &[u8; 32]
1380 ) -> Result<Route, LightningError>
1381 where L::Target: Logger, GL::Target: Logger {
1382         let graph_lock = network_graph.read_only();
1383         let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
1384                 route_params.final_value_msat, logger, scorer, score_params,
1385                 random_seed_bytes)?;
1386         add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
1387         Ok(route)
1388 }
1389
1390 pub(crate) fn get_route<L: Deref, S: Score>(
1391         our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
1392         first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, logger: L, scorer: &S, score_params: &S::ScoreParams,
1393         _random_seed_bytes: &[u8; 32]
1394 ) -> Result<Route, LightningError>
1395 where L::Target: Logger {
1396         // If we're routing to a blinded recipient, we won't have their node id. Therefore, keep the
1397         // unblinded payee id as an option. We also need a non-optional "payee id" for path construction,
1398         // so use a dummy id for this in the blinded case.
1399         let payee_node_id_opt = payment_params.payee.node_id().map(|pk| NodeId::from_pubkey(&pk));
1400         const DUMMY_BLINDED_PAYEE_ID: [u8; 33] = [2; 33];
1401         let maybe_dummy_payee_pk = payment_params.payee.node_id().unwrap_or_else(|| PublicKey::from_slice(&DUMMY_BLINDED_PAYEE_ID).unwrap());
1402         let maybe_dummy_payee_node_id = NodeId::from_pubkey(&maybe_dummy_payee_pk);
1403         let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
1404
1405         if payee_node_id_opt.map_or(false, |payee| payee == our_node_id) {
1406                 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
1407         }
1408
1409         if final_value_msat > MAX_VALUE_MSAT {
1410                 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
1411         }
1412
1413         if final_value_msat == 0 {
1414                 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
1415         }
1416
1417         match &payment_params.payee {
1418                 Payee::Clear { route_hints, node_id, .. } => {
1419                         for route in route_hints.iter() {
1420                                 for hop in &route.0 {
1421                                         if hop.src_node_id == *node_id {
1422                                                 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
1423                                         }
1424                                 }
1425                         }
1426                 },
1427                 _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1428
1429         }
1430         let final_cltv_expiry_delta = payment_params.payee.final_cltv_expiry_delta().unwrap_or(0);
1431         if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
1432                 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});
1433         }
1434
1435         // The general routing idea is the following:
1436         // 1. Fill first/last hops communicated by the caller.
1437         // 2. Attempt to construct a path from payer to payee for transferring
1438         //    any ~sufficient (described later) value.
1439         //    If succeed, remember which channels were used and how much liquidity they have available,
1440         //    so that future paths don't rely on the same liquidity.
1441         // 3. Proceed to the next step if:
1442         //    - we hit the recommended target value;
1443         //    - OR if we could not construct a new path. Any next attempt will fail too.
1444         //    Otherwise, repeat step 2.
1445         // 4. See if we managed to collect paths which aggregately are able to transfer target value
1446         //    (not recommended value).
1447         // 5. If yes, proceed. If not, fail routing.
1448         // 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
1449         //    transferred up to the transfer target value.
1450         // 7. Reduce the value of the last path until we are sending only the target value.
1451         // 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
1452         //    them so that we're not sending two HTLCs along the same path.
1453
1454         // As for the actual search algorithm, we do a payee-to-payer Dijkstra's sorting by each node's
1455         // distance from the payee
1456         //
1457         // We are not a faithful Dijkstra's implementation because we can change values which impact
1458         // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
1459         // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
1460         // the value we are currently attempting to send over a path, we simply reduce the value being
1461         // sent along the path for any hops after that channel. This may imply that later fees (which
1462         // we've already tabulated) are lower because a smaller value is passing through the channels
1463         // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
1464         // channels which were selected earlier (and which may still be used for other paths without a
1465         // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
1466         // de-preferenced.
1467         //
1468         // One potentially problematic case for this algorithm would be if there are many
1469         // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
1470         // graph walking), we may never find a path which is not liquidity-limited and has lower
1471         // proportional fee (and only lower absolute fee when considering the ultimate value sent).
1472         // Because we only consider paths with at least 5% of the total value being sent, the damage
1473         // from such a case should be limited, however this could be further reduced in the future by
1474         // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
1475         // limits for the purposes of fee calculation.
1476         //
1477         // Alternatively, we could store more detailed path information in the heap (targets, below)
1478         // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
1479         // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
1480         // and practically (as we would need to store dynamically-allocated path information in heap
1481         // objects, increasing malloc traffic and indirect memory access significantly). Further, the
1482         // results of such an algorithm would likely be biased towards lower-value paths.
1483         //
1484         // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
1485         // outside of our current search value, running a path search more times to gather candidate
1486         // paths at different values. While this may be acceptable, further path searches may increase
1487         // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
1488         // graph for candidate paths, calculating the maximum value which can realistically be sent at
1489         // the same time, remaining generic across different payment values.
1490
1491         let network_channels = network_graph.channels();
1492         let network_nodes = network_graph.nodes();
1493
1494         if payment_params.max_path_count == 0 {
1495                 return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
1496         }
1497
1498         // Allow MPP only if we have a features set from somewhere that indicates the payee supports
1499         // it. If the payee supports it they're supposed to include it in the invoice, so that should
1500         // work reliably.
1501         let allow_mpp = if payment_params.max_path_count == 1 {
1502                 false
1503         } else if payment_params.payee.supports_basic_mpp() {
1504                 true
1505         } else if let Some(payee) = payee_node_id_opt {
1506                 network_nodes.get(&payee).map_or(false, |node| node.announcement_info.as_ref().map_or(false,
1507                         |info| info.features.supports_basic_mpp()))
1508         } else { false };
1509
1510         log_trace!(logger, "Searching for a route from payer {} to {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
1511                 LoggedPayeePubkey(payment_params.payee.node_id()), if allow_mpp { "with" } else { "without" },
1512                 first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
1513
1514         // Step (1).
1515         // Prepare the data we'll use for payee-to-payer search by
1516         // inserting first hops suggested by the caller as targets.
1517         // Our search will then attempt to reach them while traversing from the payee node.
1518         let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
1519                 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
1520         if let Some(hops) = first_hops {
1521                 for chan in hops {
1522                         if chan.get_outbound_payment_scid().is_none() {
1523                                 panic!("first_hops should be filled in with usable channels, not pending ones");
1524                         }
1525                         if chan.counterparty.node_id == *our_node_pubkey {
1526                                 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
1527                         }
1528                         first_hop_targets
1529                                 .entry(NodeId::from_pubkey(&chan.counterparty.node_id))
1530                                 .or_insert(Vec::new())
1531                                 .push(chan);
1532                 }
1533                 if first_hop_targets.is_empty() {
1534                         return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
1535                 }
1536         }
1537
1538         // The main heap containing all candidate next-hops sorted by their score (max(fee,
1539         // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
1540         // adding duplicate entries when we find a better path to a given node.
1541         let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
1542
1543         // Map from node_id to information about the best current path to that node, including feerate
1544         // information.
1545         let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
1546
1547         // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
1548         // indicating that we may wish to try again with a higher value, potentially paying to meet an
1549         // htlc_minimum with extra fees while still finding a cheaper path.
1550         let mut hit_minimum_limit;
1551
1552         // When arranging a route, we select multiple paths so that we can make a multi-path payment.
1553         // We start with a path_value of the exact amount we want, and if that generates a route we may
1554         // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
1555         // amount we want in total across paths, selecting the best subset at the end.
1556         const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
1557         let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
1558         let mut path_value_msat = final_value_msat;
1559
1560         // Routing Fragmentation Mitigation heuristic:
1561         //
1562         // Routing fragmentation across many payment paths increases the overall routing
1563         // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
1564         // Taking too many smaller paths also increases the chance of payment failure.
1565         // Thus to avoid this effect, we require from our collected links to provide
1566         // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
1567         // This requirement is currently set to be 1/max_path_count of the payment
1568         // value to ensure we only ever return routes that do not violate this limit.
1569         let minimal_value_contribution_msat: u64 = if allow_mpp {
1570                 (final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
1571         } else {
1572                 final_value_msat
1573         };
1574
1575         // When we start collecting routes we enforce the max_channel_saturation_power_of_half
1576         // requirement strictly. After we've collected enough (or if we fail to find new routes) we
1577         // drop the requirement by setting this to 0.
1578         let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
1579
1580         // Keep track of how much liquidity has been used in selected channels or blinded paths. Used to
1581         // determine if the channel can be used by additional MPP paths or to inform path finding
1582         // decisions. It is aware of direction *only* to ensure that the correct htlc_maximum_msat value
1583         // is used. Hence, liquidity used in one direction will not offset any used in the opposite
1584         // direction.
1585         let mut used_liquidities: HashMap<CandidateHopId, u64> =
1586                 HashMap::with_capacity(network_nodes.len());
1587
1588         // Keeping track of how much value we already collected across other paths. Helps to decide
1589         // when we want to stop looking for new paths.
1590         let mut already_collected_value_msat = 0;
1591
1592         for (_, channels) in first_hop_targets.iter_mut() {
1593                 sort_first_hop_channels(channels, &used_liquidities, recommended_value_msat,
1594                         our_node_pubkey);
1595         }
1596
1597         log_trace!(logger, "Building path from {} to payer {} for value {} msat.",
1598                 LoggedPayeePubkey(payment_params.payee.node_id()), our_node_pubkey, final_value_msat);
1599
1600         macro_rules! add_entry {
1601                 // Adds entry which goes from $src_node_id to $dest_node_id over the $candidate hop.
1602                 // $next_hops_fee_msat represents the fees paid for using all the channels *after* this one,
1603                 // since that value has to be transferred over this channel.
1604                 // Returns whether this channel caused an update to `targets`.
1605                 ( $candidate: expr, $src_node_id: expr, $dest_node_id: expr, $next_hops_fee_msat: expr,
1606                         $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr,
1607                         $next_hops_path_penalty_msat: expr, $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => { {
1608                         // We "return" whether we updated the path at the end, and how much we can route via
1609                         // this channel, via this:
1610                         let mut did_add_update_path_to_src_node = None;
1611                         // Channels to self should not be used. This is more of belt-and-suspenders, because in
1612                         // practice these cases should be caught earlier:
1613                         // - for regular channels at channel announcement (TODO)
1614                         // - for first and last hops early in get_route
1615                         if $src_node_id != $dest_node_id {
1616                                 let scid_opt = $candidate.short_channel_id();
1617                                 let effective_capacity = $candidate.effective_capacity();
1618                                 let htlc_maximum_msat = max_htlc_from_capacity(effective_capacity, channel_saturation_pow_half);
1619
1620                                 // It is tricky to subtract $next_hops_fee_msat from available liquidity here.
1621                                 // It may be misleading because we might later choose to reduce the value transferred
1622                                 // over these channels, and the channel which was insufficient might become sufficient.
1623                                 // Worst case: we drop a good channel here because it can't cover the high following
1624                                 // fees caused by one expensive channel, but then this channel could have been used
1625                                 // if the amount being transferred over this path is lower.
1626                                 // We do this for now, but this is a subject for removal.
1627                                 if let Some(mut available_value_contribution_msat) = htlc_maximum_msat.checked_sub($next_hops_fee_msat) {
1628                                         let used_liquidity_msat = used_liquidities
1629                                                 .get(&$candidate.id($src_node_id < $dest_node_id))
1630                                                 .map_or(0, |used_liquidity_msat| {
1631                                                         available_value_contribution_msat = available_value_contribution_msat
1632                                                                 .saturating_sub(*used_liquidity_msat);
1633                                                         *used_liquidity_msat
1634                                                 });
1635
1636                                         // Verify the liquidity offered by this channel complies to the minimal contribution.
1637                                         let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
1638                                         // Do not consider candidate hops that would exceed the maximum path length.
1639                                         let path_length_to_node = $next_hops_path_length + 1;
1640                                         let exceeds_max_path_length = path_length_to_node > MAX_PATH_LENGTH_ESTIMATE;
1641
1642                                         // Do not consider candidates that exceed the maximum total cltv expiry limit.
1643                                         // In order to already account for some of the privacy enhancing random CLTV
1644                                         // expiry delta offset we add on top later, we subtract a rough estimate
1645                                         // (2*MEDIAN_HOP_CLTV_EXPIRY_DELTA) here.
1646                                         let max_total_cltv_expiry_delta = (payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta)
1647                                                 .checked_sub(2*MEDIAN_HOP_CLTV_EXPIRY_DELTA)
1648                                                 .unwrap_or(payment_params.max_total_cltv_expiry_delta - final_cltv_expiry_delta);
1649                                         let hop_total_cltv_delta = ($next_hops_cltv_delta as u32)
1650                                                 .saturating_add($candidate.cltv_expiry_delta());
1651                                         let exceeds_cltv_delta_limit = hop_total_cltv_delta > max_total_cltv_expiry_delta;
1652
1653                                         let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
1654                                         // Includes paying fees for the use of the following channels.
1655                                         let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
1656                                                 Some(result) => result,
1657                                                 // Can't overflow due to how the values were computed right above.
1658                                                 None => unreachable!(),
1659                                         };
1660                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1661                                         let over_path_minimum_msat = amount_to_transfer_over_msat >= $candidate.htlc_minimum_msat() &&
1662                                                 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
1663
1664                                         #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
1665                                         let may_overpay_to_meet_path_minimum_msat =
1666                                                 ((amount_to_transfer_over_msat < $candidate.htlc_minimum_msat() &&
1667                                                   recommended_value_msat > $candidate.htlc_minimum_msat()) ||
1668                                                  (amount_to_transfer_over_msat < $next_hops_path_htlc_minimum_msat &&
1669                                                   recommended_value_msat > $next_hops_path_htlc_minimum_msat));
1670
1671                                         let payment_failed_on_this_channel = scid_opt.map_or(false,
1672                                                 |scid| payment_params.previously_failed_channels.contains(&scid));
1673
1674                                         // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
1675                                         // bother considering this channel. If retrying with recommended_value_msat may
1676                                         // allow us to hit the HTLC minimum limit, set htlc_minimum_limit so that we go
1677                                         // around again with a higher amount.
1678                                         if !contributes_sufficient_value || exceeds_max_path_length ||
1679                                                 exceeds_cltv_delta_limit || payment_failed_on_this_channel {
1680                                                 // Path isn't useful, ignore it and move on.
1681                                         } else if may_overpay_to_meet_path_minimum_msat {
1682                                                 hit_minimum_limit = true;
1683                                         } else if over_path_minimum_msat {
1684                                                 // Note that low contribution here (limited by available_liquidity_msat)
1685                                                 // might violate htlc_minimum_msat on the hops which are next along the
1686                                                 // payment path (upstream to the payee). To avoid that, we recompute
1687                                                 // path fees knowing the final path contribution after constructing it.
1688                                                 let path_htlc_minimum_msat = cmp::max(
1689                                                         compute_fees_saturating($next_hops_path_htlc_minimum_msat, $candidate.fees())
1690                                                                 .saturating_add($next_hops_path_htlc_minimum_msat),
1691                                                         $candidate.htlc_minimum_msat());
1692                                                 let hm_entry = dist.entry($src_node_id);
1693                                                 let old_entry = hm_entry.or_insert_with(|| {
1694                                                         // If there was previously no known way to access the source node
1695                                                         // (recall it goes payee-to-payer) of short_channel_id, first add a
1696                                                         // semi-dummy record just to compute the fees to reach the source node.
1697                                                         // This will affect our decision on selecting short_channel_id
1698                                                         // as a way to reach the $dest_node_id.
1699                                                         PathBuildingHop {
1700                                                                 node_id: $dest_node_id.clone(),
1701                                                                 candidate: $candidate.clone(),
1702                                                                 fee_msat: 0,
1703                                                                 next_hops_fee_msat: u64::max_value(),
1704                                                                 hop_use_fee_msat: u64::max_value(),
1705                                                                 total_fee_msat: u64::max_value(),
1706                                                                 path_htlc_minimum_msat,
1707                                                                 path_penalty_msat: u64::max_value(),
1708                                                                 was_processed: false,
1709                                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1710                                                                 value_contribution_msat,
1711                                                         }
1712                                                 });
1713
1714                                                 #[allow(unused_mut)] // We only use the mut in cfg(test)
1715                                                 let mut should_process = !old_entry.was_processed;
1716                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1717                                                 {
1718                                                         // In test/fuzzing builds, we do extra checks to make sure the skipping
1719                                                         // of already-seen nodes only happens in cases we expect (see below).
1720                                                         if !should_process { should_process = true; }
1721                                                 }
1722
1723                                                 if should_process {
1724                                                         let mut hop_use_fee_msat = 0;
1725                                                         let mut total_fee_msat: u64 = $next_hops_fee_msat;
1726
1727                                                         // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
1728                                                         // will have the same effective-fee
1729                                                         if $src_node_id != our_node_id {
1730                                                                 // Note that `u64::max_value` means we'll always fail the
1731                                                                 // `old_entry.total_fee_msat > total_fee_msat` check below
1732                                                                 hop_use_fee_msat = compute_fees_saturating(amount_to_transfer_over_msat, $candidate.fees());
1733                                                                 total_fee_msat = total_fee_msat.saturating_add(hop_use_fee_msat);
1734                                                         }
1735
1736                                                         let channel_usage = ChannelUsage {
1737                                                                 amount_msat: amount_to_transfer_over_msat,
1738                                                                 inflight_htlc_msat: used_liquidity_msat,
1739                                                                 effective_capacity,
1740                                                         };
1741                                                         let channel_penalty_msat = scid_opt.map_or(0,
1742                                                                 |scid| scorer.channel_penalty_msat(scid, &$src_node_id, &$dest_node_id,
1743                                                                         channel_usage, score_params));
1744                                                         let path_penalty_msat = $next_hops_path_penalty_msat
1745                                                                 .saturating_add(channel_penalty_msat);
1746                                                         let new_graph_node = RouteGraphNode {
1747                                                                 node_id: $src_node_id,
1748                                                                 lowest_fee_to_node: total_fee_msat,
1749                                                                 total_cltv_delta: hop_total_cltv_delta,
1750                                                                 value_contribution_msat,
1751                                                                 path_htlc_minimum_msat,
1752                                                                 path_penalty_msat,
1753                                                                 path_length_to_node,
1754                                                         };
1755
1756                                                         // Update the way of reaching $src_node_id with the given short_channel_id (from $dest_node_id),
1757                                                         // if this way is cheaper than the already known
1758                                                         // (considering the cost to "reach" this channel from the route destination,
1759                                                         // the cost of using this channel,
1760                                                         // and the cost of routing to the source node of this channel).
1761                                                         // Also, consider that htlc_minimum_msat_difference, because we might end up
1762                                                         // paying it. Consider the following exploit:
1763                                                         // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
1764                                                         // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
1765                                                         // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
1766                                                         // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
1767                                                         // to this channel.
1768                                                         // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
1769                                                         // but it may require additional tracking - we don't want to double-count
1770                                                         // the fees included in $next_hops_path_htlc_minimum_msat, but also
1771                                                         // can't use something that may decrease on future hops.
1772                                                         let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
1773                                                                 .saturating_add(old_entry.path_penalty_msat);
1774                                                         let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
1775                                                                 .saturating_add(path_penalty_msat);
1776
1777                                                         if !old_entry.was_processed && new_cost < old_cost {
1778                                                                 targets.push(new_graph_node);
1779                                                                 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
1780                                                                 old_entry.hop_use_fee_msat = hop_use_fee_msat;
1781                                                                 old_entry.total_fee_msat = total_fee_msat;
1782                                                                 old_entry.node_id = $dest_node_id.clone();
1783                                                                 old_entry.candidate = $candidate.clone();
1784                                                                 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
1785                                                                 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
1786                                                                 old_entry.path_penalty_msat = path_penalty_msat;
1787                                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1788                                                                 {
1789                                                                         old_entry.value_contribution_msat = value_contribution_msat;
1790                                                                 }
1791                                                                 did_add_update_path_to_src_node = Some(value_contribution_msat);
1792                                                         } else if old_entry.was_processed && new_cost < old_cost {
1793                                                                 #[cfg(all(not(ldk_bench), any(test, fuzzing)))]
1794                                                                 {
1795                                                                         // If we're skipping processing a node which was previously
1796                                                                         // processed even though we found another path to it with a
1797                                                                         // cheaper fee, check that it was because the second path we
1798                                                                         // found (which we are processing now) has a lower value
1799                                                                         // contribution due to an HTLC minimum limit.
1800                                                                         //
1801                                                                         // e.g. take a graph with two paths from node 1 to node 2, one
1802                                                                         // through channel A, and one through channel B. Channel A and
1803                                                                         // B are both in the to-process heap, with their scores set by
1804                                                                         // a higher htlc_minimum than fee.
1805                                                                         // Channel A is processed first, and the channels onwards from
1806                                                                         // node 1 are added to the to-process heap. Thereafter, we pop
1807                                                                         // Channel B off of the heap, note that it has a much more
1808                                                                         // restrictive htlc_maximum_msat, and recalculate the fees for
1809                                                                         // all of node 1's channels using the new, reduced, amount.
1810                                                                         //
1811                                                                         // This would be bogus - we'd be selecting a higher-fee path
1812                                                                         // with a lower htlc_maximum_msat instead of the one we'd
1813                                                                         // already decided to use.
1814                                                                         debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
1815                                                                         debug_assert!(
1816                                                                                 value_contribution_msat + path_penalty_msat <
1817                                                                                 old_entry.value_contribution_msat + old_entry.path_penalty_msat
1818                                                                         );
1819                                                                 }
1820                                                         }
1821                                                 }
1822                                         }
1823                                 }
1824                         }
1825                         did_add_update_path_to_src_node
1826                 } }
1827         }
1828
1829         let default_node_features = default_node_features();
1830
1831         // Find ways (channels with destination) to reach a given node and store them
1832         // in the corresponding data structures (routing graph etc).
1833         // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
1834         // meaning how much will be paid in fees after this node (to the best of our knowledge).
1835         // This data can later be helpful to optimize routing (pay lower fees).
1836         macro_rules! add_entries_to_cheapest_to_target_node {
1837                 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr,
1838                   $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr,
1839                   $next_hops_cltv_delta: expr, $next_hops_path_length: expr ) => {
1840                         let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
1841                                 let was_processed = elem.was_processed;
1842                                 elem.was_processed = true;
1843                                 was_processed
1844                         } else {
1845                                 // Entries are added to dist in add_entry!() when there is a channel from a node.
1846                                 // Because there are no channels from payee, it will not have a dist entry at this point.
1847                                 // If we're processing any other node, it is always be the result of a channel from it.
1848                                 debug_assert_eq!($node_id, maybe_dummy_payee_node_id);
1849                                 false
1850                         };
1851
1852                         if !skip_node {
1853                                 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1854                                         for details in first_channels {
1855                                                 let candidate = CandidateRouteHop::FirstHop { details };
1856                                                 add_entry!(candidate, our_node_id, $node_id, $fee_to_target_msat,
1857                                                         $next_hops_value_contribution,
1858                                                         $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat,
1859                                                         $next_hops_cltv_delta, $next_hops_path_length);
1860                                         }
1861                                 }
1862
1863                                 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1864                                         &node_info.features
1865                                 } else {
1866                                         &default_node_features
1867                                 };
1868
1869                                 if !features.requires_unknown_bits() {
1870                                         for chan_id in $node.channels.iter() {
1871                                                 let chan = network_channels.get(chan_id).unwrap();
1872                                                 if !chan.features.requires_unknown_bits() {
1873                                                         if let Some((directed_channel, source)) = chan.as_directed_to(&$node_id) {
1874                                                                 if first_hops.is_none() || *source != our_node_id {
1875                                                                         if directed_channel.direction().enabled {
1876                                                                                 let candidate = CandidateRouteHop::PublicHop {
1877                                                                                         info: directed_channel,
1878                                                                                         short_channel_id: *chan_id,
1879                                                                                 };
1880                                                                                 add_entry!(candidate, *source, $node_id,
1881                                                                                         $fee_to_target_msat,
1882                                                                                         $next_hops_value_contribution,
1883                                                                                         $next_hops_path_htlc_minimum_msat,
1884                                                                                         $next_hops_path_penalty_msat,
1885                                                                                         $next_hops_cltv_delta, $next_hops_path_length);
1886                                                                         }
1887                                                                 }
1888                                                         }
1889                                                 }
1890                                         }
1891                                 }
1892                         }
1893                 };
1894         }
1895
1896         let mut payment_paths = Vec::<PaymentPath>::new();
1897
1898         // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1899         'paths_collection: loop {
1900                 // For every new path, start from scratch, except for used_liquidities, which
1901                 // helps to avoid reusing previously selected paths in future iterations.
1902                 targets.clear();
1903                 dist.clear();
1904                 hit_minimum_limit = false;
1905
1906                 // If first hop is a private channel and the only way to reach the payee, this is the only
1907                 // place where it could be added.
1908                 payee_node_id_opt.map(|payee| first_hop_targets.get(&payee).map(|first_channels| {
1909                         for details in first_channels {
1910                                 let candidate = CandidateRouteHop::FirstHop { details };
1911                                 let added = add_entry!(candidate, our_node_id, payee, 0, path_value_msat,
1912                                                                         0, 0u64, 0, 0).is_some();
1913                                 log_trace!(logger, "{} direct route to payee via {}",
1914                                                 if added { "Added" } else { "Skipped" }, LoggedCandidateHop(&candidate));
1915                         }
1916                 }));
1917
1918                 // Add the payee as a target, so that the payee-to-payer
1919                 // search algorithm knows what to start with.
1920                 payee_node_id_opt.map(|payee| match network_nodes.get(&payee) {
1921                         // The payee is not in our network graph, so nothing to add here.
1922                         // There is still a chance of reaching them via last_hops though,
1923                         // so don't yet fail the payment here.
1924                         // If not, targets.pop() will not even let us enter the loop in step 2.
1925                         None => {},
1926                         Some(node) => {
1927                                 add_entries_to_cheapest_to_target_node!(node, payee, 0, path_value_msat, 0, 0u64, 0, 0);
1928                         },
1929                 });
1930
1931                 // Step (2).
1932                 // If a caller provided us with last hops, add them to routing targets. Since this happens
1933                 // earlier than general path finding, they will be somewhat prioritized, although currently
1934                 // it matters only if the fees are exactly the same.
1935                 let route_hints = match &payment_params.payee {
1936                         Payee::Clear { route_hints, .. } => route_hints,
1937                         _ => return Err(LightningError{err: "Routing to blinded paths isn't supported yet".to_owned(), action: ErrorAction::IgnoreError}),
1938                 };
1939                 for route in route_hints.iter().filter(|route| !route.0.is_empty()) {
1940                         let first_hop_in_route = &(route.0)[0];
1941                         let have_hop_src_in_graph =
1942                                 // Only add the hops in this route to our candidate set if either
1943                                 // we have a direct channel to the first hop or the first hop is
1944                                 // in the regular network graph.
1945                                 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1946                                 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1947                         if have_hop_src_in_graph {
1948                                 // We start building the path from reverse, i.e., from payee
1949                                 // to the first RouteHintHop in the path.
1950                                 let hop_iter = route.0.iter().rev();
1951                                 let prev_hop_iter = core::iter::once(&maybe_dummy_payee_pk).chain(
1952                                         route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1953                                 let mut hop_used = true;
1954                                 let mut aggregate_next_hops_fee_msat: u64 = 0;
1955                                 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1956                                 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1957                                 let mut aggregate_next_hops_cltv_delta: u32 = 0;
1958                                 let mut aggregate_next_hops_path_length: u8 = 0;
1959                                 let mut aggregate_path_contribution_msat = path_value_msat;
1960
1961                                 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1962                                         let source = NodeId::from_pubkey(&hop.src_node_id);
1963                                         let target = NodeId::from_pubkey(&prev_hop_id);
1964                                         let candidate = network_channels
1965                                                 .get(&hop.short_channel_id)
1966                                                 .and_then(|channel| channel.as_directed_to(&target))
1967                                                 .map(|(info, _)| CandidateRouteHop::PublicHop {
1968                                                         info,
1969                                                         short_channel_id: hop.short_channel_id,
1970                                                 })
1971                                                 .unwrap_or_else(|| CandidateRouteHop::PrivateHop { hint: hop });
1972
1973                                         if let Some(hop_used_msat) = add_entry!(candidate, source, target,
1974                                                 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
1975                                                 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
1976                                                 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length)
1977                                         {
1978                                                 aggregate_path_contribution_msat = hop_used_msat;
1979                                         } else {
1980                                                 // If this hop was not used then there is no use checking the preceding
1981                                                 // hops in the RouteHint. We can break by just searching for a direct
1982                                                 // channel between last checked hop and first_hop_targets.
1983                                                 hop_used = false;
1984                                         }
1985
1986                                         let used_liquidity_msat = used_liquidities
1987                                                 .get(&candidate.id(source < target)).copied()
1988                                                 .unwrap_or(0);
1989                                         let channel_usage = ChannelUsage {
1990                                                 amount_msat: final_value_msat + aggregate_next_hops_fee_msat,
1991                                                 inflight_htlc_msat: used_liquidity_msat,
1992                                                 effective_capacity: candidate.effective_capacity(),
1993                                         };
1994                                         let channel_penalty_msat = scorer.channel_penalty_msat(
1995                                                 hop.short_channel_id, &source, &target, channel_usage, score_params
1996                                         );
1997                                         aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1998                                                 .saturating_add(channel_penalty_msat);
1999
2000                                         aggregate_next_hops_cltv_delta = aggregate_next_hops_cltv_delta
2001                                                 .saturating_add(hop.cltv_expiry_delta as u32);
2002
2003                                         aggregate_next_hops_path_length = aggregate_next_hops_path_length
2004                                                 .saturating_add(1);
2005
2006                                         // Searching for a direct channel between last checked hop and first_hop_targets
2007                                         if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&prev_hop_id)) {
2008                                                 sort_first_hop_channels(first_channels, &used_liquidities,
2009                                                         recommended_value_msat, our_node_pubkey);
2010                                                 for details in first_channels {
2011                                                         let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2012                                                         add_entry!(first_hop_candidate, our_node_id, NodeId::from_pubkey(&prev_hop_id),
2013                                                                 aggregate_next_hops_fee_msat, aggregate_path_contribution_msat,
2014                                                                 aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat,
2015                                                                 aggregate_next_hops_cltv_delta, aggregate_next_hops_path_length);
2016                                                 }
2017                                         }
2018
2019                                         if !hop_used {
2020                                                 break;
2021                                         }
2022
2023                                         // In the next values of the iterator, the aggregate fees already reflects
2024                                         // the sum of value sent from payer (final_value_msat) and routing fees
2025                                         // for the last node in the RouteHint. We need to just add the fees to
2026                                         // route through the current node so that the preceding node (next iteration)
2027                                         // can use it.
2028                                         let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
2029                                                 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
2030                                         aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
2031
2032                                         let hop_htlc_minimum_msat = candidate.htlc_minimum_msat();
2033                                         let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
2034                                         let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
2035                                                 .checked_add(hop_htlc_minimum_msat_inc);
2036                                         aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
2037
2038                                         if idx == route.0.len() - 1 {
2039                                                 // The last hop in this iterator is the first hop in
2040                                                 // overall RouteHint.
2041                                                 // If this hop connects to a node with which we have a direct channel,
2042                                                 // ignore the network graph and, if the last hop was added, add our
2043                                                 // direct channel to the candidate set.
2044                                                 //
2045                                                 // Note that we *must* check if the last hop was added as `add_entry`
2046                                                 // always assumes that the third argument is a node to which we have a
2047                                                 // path.
2048                                                 if let Some(first_channels) = first_hop_targets.get_mut(&NodeId::from_pubkey(&hop.src_node_id)) {
2049                                                         sort_first_hop_channels(first_channels, &used_liquidities,
2050                                                                 recommended_value_msat, our_node_pubkey);
2051                                                         for details in first_channels {
2052                                                                 let first_hop_candidate = CandidateRouteHop::FirstHop { details };
2053                                                                 add_entry!(first_hop_candidate, our_node_id,
2054                                                                         NodeId::from_pubkey(&hop.src_node_id),
2055                                                                         aggregate_next_hops_fee_msat,
2056                                                                         aggregate_path_contribution_msat,
2057                                                                         aggregate_next_hops_path_htlc_minimum_msat,
2058                                                                         aggregate_next_hops_path_penalty_msat,
2059                                                                         aggregate_next_hops_cltv_delta,
2060                                                                         aggregate_next_hops_path_length);
2061                                                         }
2062                                                 }
2063                                         }
2064                                 }
2065                         }
2066                 }
2067
2068                 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
2069
2070                 // At this point, targets are filled with the data from first and
2071                 // last hops communicated by the caller, and the payment receiver.
2072                 let mut found_new_path = false;
2073
2074                 // Step (3).
2075                 // If this loop terminates due the exhaustion of targets, two situations are possible:
2076                 // - not enough outgoing liquidity:
2077                 //   0 < already_collected_value_msat < final_value_msat
2078                 // - enough outgoing liquidity:
2079                 //   final_value_msat <= already_collected_value_msat < recommended_value_msat
2080                 // Both these cases (and other cases except reaching recommended_value_msat) mean that
2081                 // paths_collection will be stopped because found_new_path==false.
2082                 // This is not necessarily a routing failure.
2083                 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, total_cltv_delta, mut value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, path_length_to_node, .. }) = targets.pop() {
2084
2085                         // Since we're going payee-to-payer, hitting our node as a target means we should stop
2086                         // traversing the graph and arrange the path out of what we found.
2087                         if node_id == our_node_id {
2088                                 let mut new_entry = dist.remove(&our_node_id).unwrap();
2089                                 let mut ordered_hops: Vec<(PathBuildingHop, NodeFeatures)> = vec!((new_entry.clone(), default_node_features.clone()));
2090
2091                                 'path_walk: loop {
2092                                         let mut features_set = false;
2093                                         if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
2094                                                 for details in first_channels {
2095                                                         if let Some(scid) = ordered_hops.last().unwrap().0.candidate.short_channel_id() {
2096                                                                 if details.get_outbound_payment_scid().unwrap() == scid {
2097                                                                         ordered_hops.last_mut().unwrap().1 = details.counterparty.features.to_context();
2098                                                                         features_set = true;
2099                                                                         break;
2100                                                                 }
2101                                                         }
2102                                                 }
2103                                         }
2104                                         if !features_set {
2105                                                 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
2106                                                         if let Some(node_info) = node.announcement_info.as_ref() {
2107                                                                 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
2108                                                         } else {
2109                                                                 ordered_hops.last_mut().unwrap().1 = default_node_features.clone();
2110                                                         }
2111                                                 } else {
2112                                                         // We can fill in features for everything except hops which were
2113                                                         // provided via the invoice we're paying. We could guess based on the
2114                                                         // recipient's features but for now we simply avoid guessing at all.
2115                                                 }
2116                                         }
2117
2118                                         // Means we succesfully traversed from the payer to the payee, now
2119                                         // save this path for the payment route. Also, update the liquidity
2120                                         // remaining on the used hops, so that we take them into account
2121                                         // while looking for more paths.
2122                                         if ordered_hops.last().unwrap().0.node_id == maybe_dummy_payee_node_id {
2123                                                 break 'path_walk;
2124                                         }
2125
2126                                         new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
2127                                                 Some(payment_hop) => payment_hop,
2128                                                 // We can't arrive at None because, if we ever add an entry to targets,
2129                                                 // we also fill in the entry in dist (see add_entry!).
2130                                                 None => unreachable!(),
2131                                         };
2132                                         // We "propagate" the fees one hop backward (topologically) here,
2133                                         // so that fees paid for a HTLC forwarding on the current channel are
2134                                         // associated with the previous channel (where they will be subtracted).
2135                                         ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
2136                                         ordered_hops.push((new_entry.clone(), default_node_features.clone()));
2137                                 }
2138                                 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
2139                                 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
2140
2141                                 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: \n {:#?}",
2142                                         ordered_hops.len(), value_contribution_msat, ordered_hops.iter().map(|h| &(h.0)).collect::<Vec<&PathBuildingHop>>());
2143
2144                                 let mut payment_path = PaymentPath {hops: ordered_hops};
2145
2146                                 // We could have possibly constructed a slightly inconsistent path: since we reduce
2147                                 // value being transferred along the way, we could have violated htlc_minimum_msat
2148                                 // on some channels we already passed (assuming dest->source direction). Here, we
2149                                 // recompute the fees again, so that if that's the case, we match the currently
2150                                 // underpaid htlc_minimum_msat with fees.
2151                                 debug_assert_eq!(payment_path.get_value_msat(), value_contribution_msat);
2152                                 value_contribution_msat = cmp::min(value_contribution_msat, final_value_msat);
2153                                 payment_path.update_value_and_recompute_fees(value_contribution_msat);
2154
2155                                 // Since a path allows to transfer as much value as
2156                                 // the smallest channel it has ("bottleneck"), we should recompute
2157                                 // the fees so sender HTLC don't overpay fees when traversing
2158                                 // larger channels than the bottleneck. This may happen because
2159                                 // when we were selecting those channels we were not aware how much value
2160                                 // this path will transfer, and the relative fee for them
2161                                 // might have been computed considering a larger value.
2162                                 // Remember that we used these channels so that we don't rely
2163                                 // on the same liquidity in future paths.
2164                                 let mut prevented_redundant_path_selection = false;
2165                                 let prev_hop_iter = core::iter::once(&our_node_id)
2166                                         .chain(payment_path.hops.iter().map(|(hop, _)| &hop.node_id));
2167                                 for (prev_hop, (hop, _)) in prev_hop_iter.zip(payment_path.hops.iter()) {
2168                                         let spent_on_hop_msat = value_contribution_msat + hop.next_hops_fee_msat;
2169                                         let used_liquidity_msat = used_liquidities
2170                                                 .entry(hop.candidate.id(*prev_hop < hop.node_id))
2171                                                 .and_modify(|used_liquidity_msat| *used_liquidity_msat += spent_on_hop_msat)
2172                                                 .or_insert(spent_on_hop_msat);
2173                                         let hop_capacity = hop.candidate.effective_capacity();
2174                                         let hop_max_msat = max_htlc_from_capacity(hop_capacity, channel_saturation_pow_half);
2175                                         if *used_liquidity_msat == hop_max_msat {
2176                                                 // If this path used all of this channel's available liquidity, we know
2177                                                 // this path will not be selected again in the next loop iteration.
2178                                                 prevented_redundant_path_selection = true;
2179                                         }
2180                                         debug_assert!(*used_liquidity_msat <= hop_max_msat);
2181                                 }
2182                                 if !prevented_redundant_path_selection {
2183                                         // If we weren't capped by hitting a liquidity limit on a channel in the path,
2184                                         // we'll probably end up picking the same path again on the next iteration.
2185                                         // Decrease the available liquidity of a hop in the middle of the path.
2186                                         let victim_candidate = &payment_path.hops[(payment_path.hops.len()) / 2].0.candidate;
2187                                         let exhausted = u64::max_value();
2188                                         log_trace!(logger, "Disabling route candidate {} for future path building iterations to
2189                                                 avoid duplicates.", LoggedCandidateHop(victim_candidate));
2190                                         *used_liquidities.entry(victim_candidate.id(false)).or_default() = exhausted;
2191                                         *used_liquidities.entry(victim_candidate.id(true)).or_default() = exhausted;
2192                                 }
2193
2194                                 // Track the total amount all our collected paths allow to send so that we know
2195                                 // when to stop looking for more paths
2196                                 already_collected_value_msat += value_contribution_msat;
2197
2198                                 payment_paths.push(payment_path);
2199                                 found_new_path = true;
2200                                 break 'path_construction;
2201                         }
2202
2203                         // If we found a path back to the payee, we shouldn't try to process it again. This is
2204                         // the equivalent of the `elem.was_processed` check in
2205                         // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
2206                         if node_id == maybe_dummy_payee_node_id { continue 'path_construction; }
2207
2208                         // Otherwise, since the current target node is not us,
2209                         // keep "unrolling" the payment graph from payee to payer by
2210                         // finding a way to reach the current target from the payer side.
2211                         match network_nodes.get(&node_id) {
2212                                 None => {},
2213                                 Some(node) => {
2214                                         add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node,
2215                                                 value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat,
2216                                                 total_cltv_delta, path_length_to_node);
2217                                 },
2218                         }
2219                 }
2220
2221                 if !allow_mpp {
2222                         if !found_new_path && channel_saturation_pow_half != 0 {
2223                                 channel_saturation_pow_half = 0;
2224                                 continue 'paths_collection;
2225                         }
2226                         // If we don't support MPP, no use trying to gather more value ever.
2227                         break 'paths_collection;
2228                 }
2229
2230                 // Step (4).
2231                 // Stop either when the recommended value is reached or if no new path was found in this
2232                 // iteration.
2233                 // In the latter case, making another path finding attempt won't help,
2234                 // because we deterministically terminated the search due to low liquidity.
2235                 if !found_new_path && channel_saturation_pow_half != 0 {
2236                         channel_saturation_pow_half = 0;
2237                 } else if already_collected_value_msat >= recommended_value_msat || !found_new_path {
2238                         log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
2239                                 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
2240                         break 'paths_collection;
2241                 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
2242                         // Further, if this was our first walk of the graph, and we weren't limited by an
2243                         // htlc_minimum_msat, return immediately because this path should suffice. If we were
2244                         // limited by an htlc_minimum_msat value, find another path with a higher value,
2245                         // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
2246                         // still keeping a lower total fee than this path.
2247                         if !hit_minimum_limit {
2248                                 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
2249                                 break 'paths_collection;
2250                         }
2251                         log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
2252                         path_value_msat = recommended_value_msat;
2253                 }
2254         }
2255
2256         // Step (5).
2257         if payment_paths.len() == 0 {
2258                 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2259         }
2260
2261         if already_collected_value_msat < final_value_msat {
2262                 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
2263         }
2264
2265         // Step (6).
2266         let mut selected_route = payment_paths;
2267
2268         debug_assert_eq!(selected_route.iter().map(|p| p.get_value_msat()).sum::<u64>(), already_collected_value_msat);
2269         let mut overpaid_value_msat = already_collected_value_msat - final_value_msat;
2270
2271         // First, sort by the cost-per-value of the path, dropping the paths that cost the most for
2272         // the value they contribute towards the payment amount.
2273         // We sort in descending order as we will remove from the front in `retain`, next.
2274         selected_route.sort_unstable_by(|a, b|
2275                 (((b.get_cost_msat() as u128) << 64) / (b.get_value_msat() as u128))
2276                         .cmp(&(((a.get_cost_msat() as u128) << 64) / (a.get_value_msat() as u128)))
2277         );
2278
2279         // We should make sure that at least 1 path left.
2280         let mut paths_left = selected_route.len();
2281         selected_route.retain(|path| {
2282                 if paths_left == 1 {
2283                         return true
2284                 }
2285                 let path_value_msat = path.get_value_msat();
2286                 if path_value_msat <= overpaid_value_msat {
2287                         overpaid_value_msat -= path_value_msat;
2288                         paths_left -= 1;
2289                         return false;
2290                 }
2291                 true
2292         });
2293         debug_assert!(selected_route.len() > 0);
2294
2295         if overpaid_value_msat != 0 {
2296                 // Step (7).
2297                 // Now, subtract the remaining overpaid value from the most-expensive path.
2298                 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
2299                 // so that the sender pays less fees overall. And also htlc_minimum_msat.
2300                 selected_route.sort_unstable_by(|a, b| {
2301                         let a_f = a.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2302                         let b_f = b.hops.iter().map(|hop| hop.0.candidate.fees().proportional_millionths as u64).sum::<u64>();
2303                         a_f.cmp(&b_f).then_with(|| b.get_cost_msat().cmp(&a.get_cost_msat()))
2304                 });
2305                 let expensive_payment_path = selected_route.first_mut().unwrap();
2306
2307                 // We already dropped all the paths with value below `overpaid_value_msat` above, thus this
2308                 // can't go negative.
2309                 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
2310                 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
2311         }
2312
2313         // Step (8).
2314         // Sort by the path itself and combine redundant paths.
2315         // Note that we sort by SCIDs alone as its simpler but when combining we have to ensure we
2316         // compare both SCIDs and NodeIds as individual nodes may use random aliases causing collisions
2317         // across nodes.
2318         selected_route.sort_unstable_by_key(|path| {
2319                 let mut key = [CandidateHopId::Clear((42, true)) ; MAX_PATH_LENGTH_ESTIMATE as usize];
2320                 debug_assert!(path.hops.len() <= key.len());
2321                 for (scid, key) in path.hops.iter() .map(|h| h.0.candidate.id(true)).zip(key.iter_mut()) {
2322                         *key = scid;
2323                 }
2324                 key
2325         });
2326         for idx in 0..(selected_route.len() - 1) {
2327                 if idx + 1 >= selected_route.len() { break; }
2328                 if iter_equal(selected_route[idx    ].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id)),
2329                               selected_route[idx + 1].hops.iter().map(|h| (h.0.candidate.short_channel_id(), h.0.node_id))) {
2330                         let new_value = selected_route[idx].get_value_msat() + selected_route[idx + 1].get_value_msat();
2331                         selected_route[idx].update_value_and_recompute_fees(new_value);
2332                         selected_route.remove(idx + 1);
2333                 }
2334         }
2335
2336         let mut paths = Vec::new();
2337         for payment_path in selected_route {
2338                 let mut hops = Vec::with_capacity(payment_path.hops.len());
2339                 for (hop, node_features) in payment_path.hops.iter()
2340                         .filter(|(h, _)| h.candidate.short_channel_id().is_some())
2341                 {
2342                         hops.push(RouteHop {
2343                                 pubkey: PublicKey::from_slice(hop.node_id.as_slice()).map_err(|_| LightningError{err: format!("Public key {:?} is invalid", &hop.node_id), action: ErrorAction::IgnoreAndLog(Level::Trace)})?,
2344                                 node_features: node_features.clone(),
2345                                 short_channel_id: hop.candidate.short_channel_id().unwrap(),
2346                                 channel_features: hop.candidate.features(),
2347                                 fee_msat: hop.fee_msat,
2348                                 cltv_expiry_delta: hop.candidate.cltv_expiry_delta(),
2349                         });
2350                 }
2351                 // Propagate the cltv_expiry_delta one hop backwards since the delta from the current hop is
2352                 // applicable for the previous hop.
2353                 hops.iter_mut().rev().fold(final_cltv_expiry_delta, |prev_cltv_expiry_delta, hop| {
2354                         core::mem::replace(&mut hop.cltv_expiry_delta, prev_cltv_expiry_delta)
2355                 });
2356                 paths.push(Path { hops, blinded_tail: None });
2357         }
2358         // Make sure we would never create a route with more paths than we allow.
2359         debug_assert!(paths.len() <= payment_params.max_path_count.into());
2360
2361         if let Some(node_features) = payment_params.payee.node_features() {
2362                 for path in paths.iter_mut() {
2363                         path.hops.last_mut().unwrap().node_features = node_features.clone();
2364                 }
2365         }
2366
2367         let route = Route { paths, payment_params: Some(payment_params.clone()) };
2368         log_info!(logger, "Got route: {}", log_route!(route));
2369         Ok(route)
2370 }
2371
2372 // When an adversarial intermediary node observes a payment, it may be able to infer its
2373 // destination, if the remaining CLTV expiry delta exactly matches a feasible path in the network
2374 // graph. In order to improve privacy, this method obfuscates the CLTV expiry deltas along the
2375 // payment path by adding a randomized 'shadow route' offset to the final hop.
2376 fn add_random_cltv_offset(route: &mut Route, payment_params: &PaymentParameters,
2377         network_graph: &ReadOnlyNetworkGraph, random_seed_bytes: &[u8; 32]
2378 ) {
2379         let network_channels = network_graph.channels();
2380         let network_nodes = network_graph.nodes();
2381
2382         for path in route.paths.iter_mut() {
2383                 let mut shadow_ctlv_expiry_delta_offset: u32 = 0;
2384
2385                 // Remember the last three nodes of the random walk and avoid looping back on them.
2386                 // Init with the last three nodes from the actual path, if possible.
2387                 let mut nodes_to_avoid: [NodeId; 3] = [NodeId::from_pubkey(&path.hops.last().unwrap().pubkey),
2388                         NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(2)).unwrap().pubkey),
2389                         NodeId::from_pubkey(&path.hops.get(path.hops.len().saturating_sub(3)).unwrap().pubkey)];
2390
2391                 // Choose the last publicly known node as the starting point for the random walk.
2392                 let mut cur_hop: Option<NodeId> = None;
2393                 let mut path_nonce = [0u8; 12];
2394                 if let Some(starting_hop) = path.hops.iter().rev()
2395                         .find(|h| network_nodes.contains_key(&NodeId::from_pubkey(&h.pubkey))) {
2396                                 cur_hop = Some(NodeId::from_pubkey(&starting_hop.pubkey));
2397                                 path_nonce.copy_from_slice(&cur_hop.unwrap().as_slice()[..12]);
2398                 }
2399
2400                 // Init PRNG with the path-dependant nonce, which is static for private paths.
2401                 let mut prng = ChaCha20::new(random_seed_bytes, &path_nonce);
2402                 let mut random_path_bytes = [0u8; ::core::mem::size_of::<usize>()];
2403
2404                 // Pick a random path length in [1 .. 3]
2405                 prng.process_in_place(&mut random_path_bytes);
2406                 let random_walk_length = usize::from_be_bytes(random_path_bytes).wrapping_rem(3).wrapping_add(1);
2407
2408                 for random_hop in 0..random_walk_length {
2409                         // If we don't find a suitable offset in the public network graph, we default to
2410                         // MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2411                         let mut random_hop_offset = MEDIAN_HOP_CLTV_EXPIRY_DELTA;
2412
2413                         if let Some(cur_node_id) = cur_hop {
2414                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
2415                                         // Randomly choose the next unvisited hop.
2416                                         prng.process_in_place(&mut random_path_bytes);
2417                                         if let Some(random_channel) = usize::from_be_bytes(random_path_bytes)
2418                                                 .checked_rem(cur_node.channels.len())
2419                                                 .and_then(|index| cur_node.channels.get(index))
2420                                                 .and_then(|id| network_channels.get(id)) {
2421                                                         random_channel.as_directed_from(&cur_node_id).map(|(dir_info, next_id)| {
2422                                                                 if !nodes_to_avoid.iter().any(|x| x == next_id) {
2423                                                                         nodes_to_avoid[random_hop] = *next_id;
2424                                                                         random_hop_offset = dir_info.direction().cltv_expiry_delta.into();
2425                                                                         cur_hop = Some(*next_id);
2426                                                                 }
2427                                                         });
2428                                                 }
2429                                 }
2430                         }
2431
2432                         shadow_ctlv_expiry_delta_offset = shadow_ctlv_expiry_delta_offset
2433                                 .checked_add(random_hop_offset)
2434                                 .unwrap_or(shadow_ctlv_expiry_delta_offset);
2435                 }
2436
2437                 // Limit the total offset to reduce the worst-case locked liquidity timevalue
2438                 const MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET: u32 = 3*144;
2439                 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, MAX_SHADOW_CLTV_EXPIRY_DELTA_OFFSET);
2440
2441                 // Limit the offset so we never exceed the max_total_cltv_expiry_delta. To improve plausibility,
2442                 // we choose the limit to be the largest possible multiple of MEDIAN_HOP_CLTV_EXPIRY_DELTA.
2443                 let path_total_cltv_expiry_delta: u32 = path.hops.iter().map(|h| h.cltv_expiry_delta).sum();
2444                 let mut max_path_offset = payment_params.max_total_cltv_expiry_delta - path_total_cltv_expiry_delta;
2445                 max_path_offset = cmp::max(
2446                         max_path_offset - (max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA),
2447                         max_path_offset % MEDIAN_HOP_CLTV_EXPIRY_DELTA);
2448                 shadow_ctlv_expiry_delta_offset = cmp::min(shadow_ctlv_expiry_delta_offset, max_path_offset);
2449
2450                 // Add 'shadow' CLTV offset to the final hop
2451                 if let Some(tail) = path.blinded_tail.as_mut() {
2452                         tail.excess_final_cltv_expiry_delta = tail.excess_final_cltv_expiry_delta
2453                                 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(tail.excess_final_cltv_expiry_delta);
2454                 }
2455                 if let Some(last_hop) = path.hops.last_mut() {
2456                         last_hop.cltv_expiry_delta = last_hop.cltv_expiry_delta
2457                                 .checked_add(shadow_ctlv_expiry_delta_offset).unwrap_or(last_hop.cltv_expiry_delta);
2458                 }
2459         }
2460 }
2461
2462 /// Construct a route from us (payer) to the target node (payee) via the given hops (which should
2463 /// exclude the payer, but include the payee). This may be useful, e.g., for probing the chosen path.
2464 ///
2465 /// Re-uses logic from `find_route`, so the restrictions described there also apply here.
2466 pub fn build_route_from_hops<L: Deref, GL: Deref>(
2467         our_node_pubkey: &PublicKey, hops: &[PublicKey], route_params: &RouteParameters,
2468         network_graph: &NetworkGraph<GL>, logger: L, random_seed_bytes: &[u8; 32]
2469 ) -> Result<Route, LightningError>
2470 where L::Target: Logger, GL::Target: Logger {
2471         let graph_lock = network_graph.read_only();
2472         let mut route = build_route_from_hops_internal(
2473                 our_node_pubkey, hops, &route_params.payment_params, &graph_lock,
2474                 route_params.final_value_msat, logger, random_seed_bytes)?;
2475         add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
2476         Ok(route)
2477 }
2478
2479 fn build_route_from_hops_internal<L: Deref>(
2480         our_node_pubkey: &PublicKey, hops: &[PublicKey], payment_params: &PaymentParameters,
2481         network_graph: &ReadOnlyNetworkGraph, final_value_msat: u64, logger: L,
2482         random_seed_bytes: &[u8; 32]
2483 ) -> Result<Route, LightningError> where L::Target: Logger {
2484
2485         struct HopScorer {
2486                 our_node_id: NodeId,
2487                 hop_ids: [Option<NodeId>; MAX_PATH_LENGTH_ESTIMATE as usize],
2488         }
2489
2490         impl Score for HopScorer {
2491                 type ScoreParams = ();
2492                 fn channel_penalty_msat(&self, _short_channel_id: u64, source: &NodeId, target: &NodeId,
2493                         _usage: ChannelUsage, _score_params: &Self::ScoreParams) -> u64
2494                 {
2495                         let mut cur_id = self.our_node_id;
2496                         for i in 0..self.hop_ids.len() {
2497                                 if let Some(next_id) = self.hop_ids[i] {
2498                                         if cur_id == *source && next_id == *target {
2499                                                 return 0;
2500                                         }
2501                                         cur_id = next_id;
2502                                 } else {
2503                                         break;
2504                                 }
2505                         }
2506                         u64::max_value()
2507                 }
2508
2509                 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2510
2511                 fn payment_path_successful(&mut self, _path: &Path) {}
2512
2513                 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
2514
2515                 fn probe_successful(&mut self, _path: &Path) {}
2516         }
2517
2518         impl<'a> Writeable for HopScorer {
2519                 #[inline]
2520                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), io::Error> {
2521                         unreachable!();
2522                 }
2523         }
2524
2525         if hops.len() > MAX_PATH_LENGTH_ESTIMATE.into() {
2526                 return Err(LightningError{err: "Cannot build a route exceeding the maximum path length.".to_owned(), action: ErrorAction::IgnoreError});
2527         }
2528
2529         let our_node_id = NodeId::from_pubkey(our_node_pubkey);
2530         let mut hop_ids = [None; MAX_PATH_LENGTH_ESTIMATE as usize];
2531         for i in 0..hops.len() {
2532                 hop_ids[i] = Some(NodeId::from_pubkey(&hops[i]));
2533         }
2534
2535         let scorer = HopScorer { our_node_id, hop_ids };
2536
2537         get_route(our_node_pubkey, payment_params, network_graph, None, final_value_msat,
2538                 logger, &scorer, &(), random_seed_bytes)
2539 }
2540
2541 #[cfg(test)]
2542 mod tests {
2543         use crate::blinded_path::{BlindedHop, BlindedPath};
2544         use crate::routing::gossip::{NetworkGraph, P2PGossipSync, NodeId, EffectiveCapacity};
2545         use crate::routing::utxo::UtxoResult;
2546         use crate::routing::router::{get_route, build_route_from_hops_internal, add_random_cltv_offset, default_node_features,
2547                 BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees,
2548                 DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA, MAX_PATH_LENGTH_ESTIMATE};
2549         use crate::routing::scoring::{ChannelUsage, FixedPenaltyScorer, Score, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
2550         use crate::routing::test_utils::{add_channel, add_or_update_node, build_graph, build_line_graph, id_to_feature_flags, get_nodes, update_channel};
2551         use crate::chain::transaction::OutPoint;
2552         use crate::sign::EntropySource;
2553         use crate::ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
2554         use crate::ln::msgs::{ErrorAction, LightningError, UnsignedChannelUpdate, MAX_VALUE_MSAT};
2555         use crate::ln::channelmanager;
2556         use crate::util::config::UserConfig;
2557         use crate::util::test_utils as ln_test_utils;
2558         use crate::util::chacha20::ChaCha20;
2559         use crate::util::ser::{Readable, Writeable};
2560         #[cfg(c_bindings)]
2561         use crate::util::ser::Writer;
2562
2563         use bitcoin::hashes::Hash;
2564         use bitcoin::network::constants::Network;
2565         use bitcoin::blockdata::constants::genesis_block;
2566         use bitcoin::blockdata::script::Builder;
2567         use bitcoin::blockdata::opcodes;
2568         use bitcoin::blockdata::transaction::TxOut;
2569
2570         use hex;
2571
2572         use bitcoin::secp256k1::{PublicKey,SecretKey};
2573         use bitcoin::secp256k1::Secp256k1;
2574
2575         use crate::io::Cursor;
2576         use crate::prelude::*;
2577         use crate::sync::Arc;
2578
2579         use core::convert::TryInto;
2580
2581         fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
2582                         features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
2583                 channelmanager::ChannelDetails {
2584                         channel_id: [0; 32],
2585                         counterparty: channelmanager::ChannelCounterparty {
2586                                 features,
2587                                 node_id,
2588                                 unspendable_punishment_reserve: 0,
2589                                 forwarding_info: None,
2590                                 outbound_htlc_minimum_msat: None,
2591                                 outbound_htlc_maximum_msat: None,
2592                         },
2593                         funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
2594                         channel_type: None,
2595                         short_channel_id,
2596                         outbound_scid_alias: None,
2597                         inbound_scid_alias: None,
2598                         channel_value_satoshis: 0,
2599                         user_channel_id: 0,
2600                         balance_msat: 0,
2601                         outbound_capacity_msat,
2602                         next_outbound_htlc_limit_msat: outbound_capacity_msat,
2603                         next_outbound_htlc_minimum_msat: 0,
2604                         inbound_capacity_msat: 42,
2605                         unspendable_punishment_reserve: None,
2606                         confirmations_required: None,
2607                         confirmations: None,
2608                         force_close_spend_delay: None,
2609                         is_outbound: true, is_channel_ready: true,
2610                         is_usable: true, is_public: true,
2611                         inbound_htlc_minimum_msat: None,
2612                         inbound_htlc_maximum_msat: None,
2613                         config: None,
2614                         feerate_sat_per_1000_weight: None
2615                 }
2616         }
2617
2618         #[test]
2619         fn simple_route_test() {
2620                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2621                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2622                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2623                 let scorer = ln_test_utils::TestScorer::new();
2624                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2625                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2626
2627                 // Simple route to 2 via 1
2628
2629                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 0, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2630                         assert_eq!(err, "Cannot send a payment of 0 msat");
2631                 } else { panic!(); }
2632
2633                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2634                 assert_eq!(route.paths[0].hops.len(), 2);
2635
2636                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
2637                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2638                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
2639                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
2640                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
2641                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
2642
2643                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2644                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
2645                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2646                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2647                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2648                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
2649         }
2650
2651         #[test]
2652         fn invalid_first_hop_test() {
2653                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2654                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2655                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2656                 let scorer = ln_test_utils::TestScorer::new();
2657                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2658                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2659
2660                 // Simple route to 2 via 1
2661
2662                 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
2663
2664                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) =
2665                         get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2666                         assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
2667                 } else { panic!(); }
2668
2669                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2670                 assert_eq!(route.paths[0].hops.len(), 2);
2671         }
2672
2673         #[test]
2674         fn htlc_minimum_test() {
2675                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2676                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2677                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2678                 let scorer = ln_test_utils::TestScorer::new();
2679                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2680                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2681
2682                 // Simple route to 2 via 1
2683
2684                 // Disable other paths
2685                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2686                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2687                         short_channel_id: 12,
2688                         timestamp: 2,
2689                         flags: 2, // to disable
2690                         cltv_expiry_delta: 0,
2691                         htlc_minimum_msat: 0,
2692                         htlc_maximum_msat: MAX_VALUE_MSAT,
2693                         fee_base_msat: 0,
2694                         fee_proportional_millionths: 0,
2695                         excess_data: Vec::new()
2696                 });
2697                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2698                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2699                         short_channel_id: 3,
2700                         timestamp: 2,
2701                         flags: 2, // to disable
2702                         cltv_expiry_delta: 0,
2703                         htlc_minimum_msat: 0,
2704                         htlc_maximum_msat: MAX_VALUE_MSAT,
2705                         fee_base_msat: 0,
2706                         fee_proportional_millionths: 0,
2707                         excess_data: Vec::new()
2708                 });
2709                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2710                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2711                         short_channel_id: 13,
2712                         timestamp: 2,
2713                         flags: 2, // to disable
2714                         cltv_expiry_delta: 0,
2715                         htlc_minimum_msat: 0,
2716                         htlc_maximum_msat: MAX_VALUE_MSAT,
2717                         fee_base_msat: 0,
2718                         fee_proportional_millionths: 0,
2719                         excess_data: Vec::new()
2720                 });
2721                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2722                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2723                         short_channel_id: 6,
2724                         timestamp: 2,
2725                         flags: 2, // to disable
2726                         cltv_expiry_delta: 0,
2727                         htlc_minimum_msat: 0,
2728                         htlc_maximum_msat: MAX_VALUE_MSAT,
2729                         fee_base_msat: 0,
2730                         fee_proportional_millionths: 0,
2731                         excess_data: Vec::new()
2732                 });
2733                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2734                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2735                         short_channel_id: 7,
2736                         timestamp: 2,
2737                         flags: 2, // to disable
2738                         cltv_expiry_delta: 0,
2739                         htlc_minimum_msat: 0,
2740                         htlc_maximum_msat: MAX_VALUE_MSAT,
2741                         fee_base_msat: 0,
2742                         fee_proportional_millionths: 0,
2743                         excess_data: Vec::new()
2744                 });
2745
2746                 // Check against amount_to_transfer_over_msat.
2747                 // Set minimal HTLC of 200_000_000 msat.
2748                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2749                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2750                         short_channel_id: 2,
2751                         timestamp: 3,
2752                         flags: 0,
2753                         cltv_expiry_delta: 0,
2754                         htlc_minimum_msat: 200_000_000,
2755                         htlc_maximum_msat: MAX_VALUE_MSAT,
2756                         fee_base_msat: 0,
2757                         fee_proportional_millionths: 0,
2758                         excess_data: Vec::new()
2759                 });
2760
2761                 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2762                 // be used.
2763                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2764                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2765                         short_channel_id: 4,
2766                         timestamp: 3,
2767                         flags: 0,
2768                         cltv_expiry_delta: 0,
2769                         htlc_minimum_msat: 0,
2770                         htlc_maximum_msat: 199_999_999,
2771                         fee_base_msat: 0,
2772                         fee_proportional_millionths: 0,
2773                         excess_data: Vec::new()
2774                 });
2775
2776                 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2777                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2778                         assert_eq!(err, "Failed to find a path to the given destination");
2779                 } else { panic!(); }
2780
2781                 // Lift the restriction on the first hop.
2782                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2783                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2784                         short_channel_id: 2,
2785                         timestamp: 4,
2786                         flags: 0,
2787                         cltv_expiry_delta: 0,
2788                         htlc_minimum_msat: 0,
2789                         htlc_maximum_msat: MAX_VALUE_MSAT,
2790                         fee_base_msat: 0,
2791                         fee_proportional_millionths: 0,
2792                         excess_data: Vec::new()
2793                 });
2794
2795                 // A payment above the minimum should pass
2796                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 199_999_999, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2797                 assert_eq!(route.paths[0].hops.len(), 2);
2798         }
2799
2800         #[test]
2801         fn htlc_minimum_overpay_test() {
2802                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2803                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2804                 let config = UserConfig::default();
2805                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
2806                 let scorer = ln_test_utils::TestScorer::new();
2807                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2808                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2809
2810                 // A route to node#2 via two paths.
2811                 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2812                 // Thus, they can't send 60 without overpaying.
2813                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2814                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2815                         short_channel_id: 2,
2816                         timestamp: 2,
2817                         flags: 0,
2818                         cltv_expiry_delta: 0,
2819                         htlc_minimum_msat: 35_000,
2820                         htlc_maximum_msat: 40_000,
2821                         fee_base_msat: 0,
2822                         fee_proportional_millionths: 0,
2823                         excess_data: Vec::new()
2824                 });
2825                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2826                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2827                         short_channel_id: 12,
2828                         timestamp: 3,
2829                         flags: 0,
2830                         cltv_expiry_delta: 0,
2831                         htlc_minimum_msat: 35_000,
2832                         htlc_maximum_msat: 40_000,
2833                         fee_base_msat: 0,
2834                         fee_proportional_millionths: 0,
2835                         excess_data: Vec::new()
2836                 });
2837
2838                 // Make 0 fee.
2839                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2840                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2841                         short_channel_id: 13,
2842                         timestamp: 2,
2843                         flags: 0,
2844                         cltv_expiry_delta: 0,
2845                         htlc_minimum_msat: 0,
2846                         htlc_maximum_msat: MAX_VALUE_MSAT,
2847                         fee_base_msat: 0,
2848                         fee_proportional_millionths: 0,
2849                         excess_data: Vec::new()
2850                 });
2851                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2852                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2853                         short_channel_id: 4,
2854                         timestamp: 2,
2855                         flags: 0,
2856                         cltv_expiry_delta: 0,
2857                         htlc_minimum_msat: 0,
2858                         htlc_maximum_msat: MAX_VALUE_MSAT,
2859                         fee_base_msat: 0,
2860                         fee_proportional_millionths: 0,
2861                         excess_data: Vec::new()
2862                 });
2863
2864                 // Disable other paths
2865                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2866                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2867                         short_channel_id: 1,
2868                         timestamp: 3,
2869                         flags: 2, // to disable
2870                         cltv_expiry_delta: 0,
2871                         htlc_minimum_msat: 0,
2872                         htlc_maximum_msat: MAX_VALUE_MSAT,
2873                         fee_base_msat: 0,
2874                         fee_proportional_millionths: 0,
2875                         excess_data: Vec::new()
2876                 });
2877
2878                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2879                 // Overpay fees to hit htlc_minimum_msat.
2880                 let overpaid_fees = route.paths[0].hops[0].fee_msat + route.paths[1].hops[0].fee_msat;
2881                 // TODO: this could be better balanced to overpay 10k and not 15k.
2882                 assert_eq!(overpaid_fees, 15_000);
2883
2884                 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2885                 // while taking even more fee to match htlc_minimum_msat.
2886                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2887                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2888                         short_channel_id: 12,
2889                         timestamp: 4,
2890                         flags: 0,
2891                         cltv_expiry_delta: 0,
2892                         htlc_minimum_msat: 65_000,
2893                         htlc_maximum_msat: 80_000,
2894                         fee_base_msat: 0,
2895                         fee_proportional_millionths: 0,
2896                         excess_data: Vec::new()
2897                 });
2898                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2899                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2900                         short_channel_id: 2,
2901                         timestamp: 3,
2902                         flags: 0,
2903                         cltv_expiry_delta: 0,
2904                         htlc_minimum_msat: 0,
2905                         htlc_maximum_msat: MAX_VALUE_MSAT,
2906                         fee_base_msat: 0,
2907                         fee_proportional_millionths: 0,
2908                         excess_data: Vec::new()
2909                 });
2910                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2911                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2912                         short_channel_id: 4,
2913                         timestamp: 4,
2914                         flags: 0,
2915                         cltv_expiry_delta: 0,
2916                         htlc_minimum_msat: 0,
2917                         htlc_maximum_msat: MAX_VALUE_MSAT,
2918                         fee_base_msat: 0,
2919                         fee_proportional_millionths: 100_000,
2920                         excess_data: Vec::new()
2921                 });
2922
2923                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2924                 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2925                 assert_eq!(route.paths.len(), 1);
2926                 assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
2927                 let fees = route.paths[0].hops[0].fee_msat;
2928                 assert_eq!(fees, 5_000);
2929
2930                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2931                 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2932                 // the other channel.
2933                 assert_eq!(route.paths.len(), 1);
2934                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
2935                 let fees = route.paths[0].hops[0].fee_msat;
2936                 assert_eq!(fees, 5_000);
2937         }
2938
2939         #[test]
2940         fn disable_channels_test() {
2941                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
2942                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2943                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
2944                 let scorer = ln_test_utils::TestScorer::new();
2945                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
2946                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2947
2948                 // // Disable channels 4 and 12 by flags=2
2949                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2950                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2951                         short_channel_id: 4,
2952                         timestamp: 2,
2953                         flags: 2, // to disable
2954                         cltv_expiry_delta: 0,
2955                         htlc_minimum_msat: 0,
2956                         htlc_maximum_msat: MAX_VALUE_MSAT,
2957                         fee_base_msat: 0,
2958                         fee_proportional_millionths: 0,
2959                         excess_data: Vec::new()
2960                 });
2961                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2962                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2963                         short_channel_id: 12,
2964                         timestamp: 2,
2965                         flags: 2, // to disable
2966                         cltv_expiry_delta: 0,
2967                         htlc_minimum_msat: 0,
2968                         htlc_maximum_msat: MAX_VALUE_MSAT,
2969                         fee_base_msat: 0,
2970                         fee_proportional_millionths: 0,
2971                         excess_data: Vec::new()
2972                 });
2973
2974                 // If all the channels require some features we don't understand, route should fail
2975                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
2976                         assert_eq!(err, "Failed to find a path to the given destination");
2977                 } else { panic!(); }
2978
2979                 // If we specify a channel to node7, that overrides our local channel view and that gets used
2980                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2981                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
2982                 assert_eq!(route.paths[0].hops.len(), 2);
2983
2984                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
2985                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
2986                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
2987                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
2988                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2989                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2990
2991                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
2992                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
2993                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
2994                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
2995                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
2996                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
2997         }
2998
2999         #[test]
3000         fn disable_node_test() {
3001                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3002                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3003                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3004                 let scorer = ln_test_utils::TestScorer::new();
3005                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3006                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3007
3008                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
3009                 let mut unknown_features = NodeFeatures::empty();
3010                 unknown_features.set_unknown_feature_required();
3011                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
3012                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
3013                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
3014
3015                 // If all nodes require some features we don't understand, route should fail
3016                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3017                         assert_eq!(err, "Failed to find a path to the given destination");
3018                 } else { panic!(); }
3019
3020                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3021                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3022                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3023                 assert_eq!(route.paths[0].hops.len(), 2);
3024
3025                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3026                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3027                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3028                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3029                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
3030                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3031
3032                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3033                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3034                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3035                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3036                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3037                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3038
3039                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
3040                 // naively) assume that the user checked the feature bits on the invoice, which override
3041                 // the node_announcement.
3042         }
3043
3044         #[test]
3045         fn our_chans_test() {
3046                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3047                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3048                 let scorer = ln_test_utils::TestScorer::new();
3049                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3050                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3051
3052                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
3053                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42);
3054                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3055                 assert_eq!(route.paths[0].hops.len(), 3);
3056
3057                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3058                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3059                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3060                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3061                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3062                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3063
3064                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3065                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3066                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3067                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (3 << 4) | 2);
3068                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3069                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3070
3071                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[0]);
3072                 assert_eq!(route.paths[0].hops[2].short_channel_id, 3);
3073                 assert_eq!(route.paths[0].hops[2].fee_msat, 100);
3074                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
3075                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(1));
3076                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(3));
3077
3078                 // If we specify a channel to node7, that overrides our local channel view and that gets used
3079                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
3080                 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3081                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3082                 assert_eq!(route.paths[0].hops.len(), 2);
3083
3084                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
3085                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3086                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3087                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
3088                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3089                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3090
3091                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3092                 assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
3093                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3094                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3095                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3096                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
3097         }
3098
3099         fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3100                 let zero_fees = RoutingFees {
3101                         base_msat: 0,
3102                         proportional_millionths: 0,
3103                 };
3104                 vec![RouteHint(vec![RouteHintHop {
3105                         src_node_id: nodes[3],
3106                         short_channel_id: 8,
3107                         fees: zero_fees,
3108                         cltv_expiry_delta: (8 << 4) | 1,
3109                         htlc_minimum_msat: None,
3110                         htlc_maximum_msat: None,
3111                 }
3112                 ]), RouteHint(vec![RouteHintHop {
3113                         src_node_id: nodes[4],
3114                         short_channel_id: 9,
3115                         fees: RoutingFees {
3116                                 base_msat: 1001,
3117                                 proportional_millionths: 0,
3118                         },
3119                         cltv_expiry_delta: (9 << 4) | 1,
3120                         htlc_minimum_msat: None,
3121                         htlc_maximum_msat: None,
3122                 }]), RouteHint(vec![RouteHintHop {
3123                         src_node_id: nodes[5],
3124                         short_channel_id: 10,
3125                         fees: zero_fees,
3126                         cltv_expiry_delta: (10 << 4) | 1,
3127                         htlc_minimum_msat: None,
3128                         htlc_maximum_msat: None,
3129                 }])]
3130         }
3131
3132         fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3133                 let zero_fees = RoutingFees {
3134                         base_msat: 0,
3135                         proportional_millionths: 0,
3136                 };
3137                 vec![RouteHint(vec![RouteHintHop {
3138                         src_node_id: nodes[2],
3139                         short_channel_id: 5,
3140                         fees: RoutingFees {
3141                                 base_msat: 100,
3142                                 proportional_millionths: 0,
3143                         },
3144                         cltv_expiry_delta: (5 << 4) | 1,
3145                         htlc_minimum_msat: None,
3146                         htlc_maximum_msat: None,
3147                 }, RouteHintHop {
3148                         src_node_id: nodes[3],
3149                         short_channel_id: 8,
3150                         fees: zero_fees,
3151                         cltv_expiry_delta: (8 << 4) | 1,
3152                         htlc_minimum_msat: None,
3153                         htlc_maximum_msat: None,
3154                 }
3155                 ]), RouteHint(vec![RouteHintHop {
3156                         src_node_id: nodes[4],
3157                         short_channel_id: 9,
3158                         fees: RoutingFees {
3159                                 base_msat: 1001,
3160                                 proportional_millionths: 0,
3161                         },
3162                         cltv_expiry_delta: (9 << 4) | 1,
3163                         htlc_minimum_msat: None,
3164                         htlc_maximum_msat: None,
3165                 }]), RouteHint(vec![RouteHintHop {
3166                         src_node_id: nodes[5],
3167                         short_channel_id: 10,
3168                         fees: zero_fees,
3169                         cltv_expiry_delta: (10 << 4) | 1,
3170                         htlc_minimum_msat: None,
3171                         htlc_maximum_msat: None,
3172                 }])]
3173         }
3174
3175         #[test]
3176         fn partial_route_hint_test() {
3177                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3178                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3179                 let scorer = ln_test_utils::TestScorer::new();
3180                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3181                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3182
3183                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
3184                 // Tests the behaviour when the RouteHint contains a suboptimal hop.
3185                 // RouteHint may be partially used by the algo to build the best path.
3186
3187                 // First check that last hop can't have its source as the payee.
3188                 let invalid_last_hop = RouteHint(vec![RouteHintHop {
3189                         src_node_id: nodes[6],
3190                         short_channel_id: 8,
3191                         fees: RoutingFees {
3192                                 base_msat: 1000,
3193                                 proportional_millionths: 0,
3194                         },
3195                         cltv_expiry_delta: (8 << 4) | 1,
3196                         htlc_minimum_msat: None,
3197                         htlc_maximum_msat: None,
3198                 }]);
3199
3200                 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
3201                 invalid_last_hops.push(invalid_last_hop);
3202                 {
3203                         let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(invalid_last_hops).unwrap();
3204                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3205                                 assert_eq!(err, "Route hint cannot have the payee as the source.");
3206                         } else { panic!(); }
3207                 }
3208
3209                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_multi_private_channels(&nodes)).unwrap();
3210                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3211                 assert_eq!(route.paths[0].hops.len(), 5);
3212
3213                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3214                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3215                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3216                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3217                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3218                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3219
3220                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3221                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3222                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3223                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3224                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3225                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3226
3227                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3228                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3229                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3230                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3231                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3232                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3233
3234                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3235                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3236                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3237                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3238                 // If we have a peer in the node map, we'll use their features here since we don't have
3239                 // a way of figuring out their features from the invoice:
3240                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3241                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3242
3243                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3244                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3245                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3246                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3247                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3248                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3249         }
3250
3251         fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3252                 let zero_fees = RoutingFees {
3253                         base_msat: 0,
3254                         proportional_millionths: 0,
3255                 };
3256                 vec![RouteHint(vec![RouteHintHop {
3257                         src_node_id: nodes[3],
3258                         short_channel_id: 8,
3259                         fees: zero_fees,
3260                         cltv_expiry_delta: (8 << 4) | 1,
3261                         htlc_minimum_msat: None,
3262                         htlc_maximum_msat: None,
3263                 }]), RouteHint(vec![
3264
3265                 ]), RouteHint(vec![RouteHintHop {
3266                         src_node_id: nodes[5],
3267                         short_channel_id: 10,
3268                         fees: zero_fees,
3269                         cltv_expiry_delta: (10 << 4) | 1,
3270                         htlc_minimum_msat: None,
3271                         htlc_maximum_msat: None,
3272                 }])]
3273         }
3274
3275         #[test]
3276         fn ignores_empty_last_hops_test() {
3277                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3278                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3279                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(empty_last_hop(&nodes)).unwrap();
3280                 let scorer = ln_test_utils::TestScorer::new();
3281                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3282                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3283
3284                 // Test handling of an empty RouteHint passed in Invoice.
3285
3286                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3287                 assert_eq!(route.paths[0].hops.len(), 5);
3288
3289                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3290                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3291                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3292                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3293                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3294                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3295
3296                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3297                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3298                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3299                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3300                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3301                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3302
3303                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3304                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3305                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3306                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3307                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3308                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3309
3310                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3311                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3312                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3313                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3314                 // If we have a peer in the node map, we'll use their features here since we don't have
3315                 // a way of figuring out their features from the invoice:
3316                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3317                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3318
3319                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3320                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3321                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3322                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3323                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3324                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3325         }
3326
3327         /// Builds a trivial last-hop hint that passes through the two nodes given, with channel 0xff00
3328         /// and 0xff01.
3329         fn multi_hop_last_hops_hint(hint_hops: [PublicKey; 2]) -> Vec<RouteHint> {
3330                 let zero_fees = RoutingFees {
3331                         base_msat: 0,
3332                         proportional_millionths: 0,
3333                 };
3334                 vec![RouteHint(vec![RouteHintHop {
3335                         src_node_id: hint_hops[0],
3336                         short_channel_id: 0xff00,
3337                         fees: RoutingFees {
3338                                 base_msat: 100,
3339                                 proportional_millionths: 0,
3340                         },
3341                         cltv_expiry_delta: (5 << 4) | 1,
3342                         htlc_minimum_msat: None,
3343                         htlc_maximum_msat: None,
3344                 }, RouteHintHop {
3345                         src_node_id: hint_hops[1],
3346                         short_channel_id: 0xff01,
3347                         fees: zero_fees,
3348                         cltv_expiry_delta: (8 << 4) | 1,
3349                         htlc_minimum_msat: None,
3350                         htlc_maximum_msat: None,
3351                 }])]
3352         }
3353
3354         #[test]
3355         fn multi_hint_last_hops_test() {
3356                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3357                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3358                 let last_hops = multi_hop_last_hops_hint([nodes[2], nodes[3]]);
3359                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3360                 let scorer = ln_test_utils::TestScorer::new();
3361                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3362                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3363                 // Test through channels 2, 3, 0xff00, 0xff01.
3364                 // Test shows that multiple hop hints are considered.
3365
3366                 // Disabling channels 6 & 7 by flags=2
3367                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3368                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3369                         short_channel_id: 6,
3370                         timestamp: 2,
3371                         flags: 2, // to disable
3372                         cltv_expiry_delta: 0,
3373                         htlc_minimum_msat: 0,
3374                         htlc_maximum_msat: MAX_VALUE_MSAT,
3375                         fee_base_msat: 0,
3376                         fee_proportional_millionths: 0,
3377                         excess_data: Vec::new()
3378                 });
3379                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3380                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3381                         short_channel_id: 7,
3382                         timestamp: 2,
3383                         flags: 2, // to disable
3384                         cltv_expiry_delta: 0,
3385                         htlc_minimum_msat: 0,
3386                         htlc_maximum_msat: MAX_VALUE_MSAT,
3387                         fee_base_msat: 0,
3388                         fee_proportional_millionths: 0,
3389                         excess_data: Vec::new()
3390                 });
3391
3392                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3393                 assert_eq!(route.paths[0].hops.len(), 4);
3394
3395                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3396                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3397                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3398                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3399                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3400                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3401
3402                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3403                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3404                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3405                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3406                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3407                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3408
3409                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[3]);
3410                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3411                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3412                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3413                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(4));
3414                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3415
3416                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3417                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3418                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3419                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3420                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3421                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3422         }
3423
3424         #[test]
3425         fn private_multi_hint_last_hops_test() {
3426                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
3427                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3428
3429                 let non_announced_privkey = SecretKey::from_slice(&hex::decode(format!("{:02x}", 0xf0).repeat(32)).unwrap()[..]).unwrap();
3430                 let non_announced_pubkey = PublicKey::from_secret_key(&secp_ctx, &non_announced_privkey);
3431
3432                 let last_hops = multi_hop_last_hops_hint([nodes[2], non_announced_pubkey]);
3433                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3434                 let scorer = ln_test_utils::TestScorer::new();
3435                 // Test through channels 2, 3, 0xff00, 0xff01.
3436                 // Test shows that multiple hop hints are considered.
3437
3438                 // Disabling channels 6 & 7 by flags=2
3439                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3440                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3441                         short_channel_id: 6,
3442                         timestamp: 2,
3443                         flags: 2, // to disable
3444                         cltv_expiry_delta: 0,
3445                         htlc_minimum_msat: 0,
3446                         htlc_maximum_msat: MAX_VALUE_MSAT,
3447                         fee_base_msat: 0,
3448                         fee_proportional_millionths: 0,
3449                         excess_data: Vec::new()
3450                 });
3451                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3452                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3453                         short_channel_id: 7,
3454                         timestamp: 2,
3455                         flags: 2, // to disable
3456                         cltv_expiry_delta: 0,
3457                         htlc_minimum_msat: 0,
3458                         htlc_maximum_msat: MAX_VALUE_MSAT,
3459                         fee_base_msat: 0,
3460                         fee_proportional_millionths: 0,
3461                         excess_data: Vec::new()
3462                 });
3463
3464                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &[42u8; 32]).unwrap();
3465                 assert_eq!(route.paths[0].hops.len(), 4);
3466
3467                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3468                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3469                 assert_eq!(route.paths[0].hops[0].fee_msat, 200);
3470                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, 65);
3471                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3472                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3473
3474                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3475                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3476                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3477                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 81);
3478                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3479                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3480
3481                 assert_eq!(route.paths[0].hops[2].pubkey, non_announced_pubkey);
3482                 assert_eq!(route.paths[0].hops[2].short_channel_id, last_hops[0].0[0].short_channel_id);
3483                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3484                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 129);
3485                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3486                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3487
3488                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3489                 assert_eq!(route.paths[0].hops[3].short_channel_id, last_hops[0].0[1].short_channel_id);
3490                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3491                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3492                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3493                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3494         }
3495
3496         fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
3497                 let zero_fees = RoutingFees {
3498                         base_msat: 0,
3499                         proportional_millionths: 0,
3500                 };
3501                 vec![RouteHint(vec![RouteHintHop {
3502                         src_node_id: nodes[4],
3503                         short_channel_id: 11,
3504                         fees: zero_fees,
3505                         cltv_expiry_delta: (11 << 4) | 1,
3506                         htlc_minimum_msat: None,
3507                         htlc_maximum_msat: None,
3508                 }, RouteHintHop {
3509                         src_node_id: nodes[3],
3510                         short_channel_id: 8,
3511                         fees: zero_fees,
3512                         cltv_expiry_delta: (8 << 4) | 1,
3513                         htlc_minimum_msat: None,
3514                         htlc_maximum_msat: None,
3515                 }]), RouteHint(vec![RouteHintHop {
3516                         src_node_id: nodes[4],
3517                         short_channel_id: 9,
3518                         fees: RoutingFees {
3519                                 base_msat: 1001,
3520                                 proportional_millionths: 0,
3521                         },
3522                         cltv_expiry_delta: (9 << 4) | 1,
3523                         htlc_minimum_msat: None,
3524                         htlc_maximum_msat: None,
3525                 }]), RouteHint(vec![RouteHintHop {
3526                         src_node_id: nodes[5],
3527                         short_channel_id: 10,
3528                         fees: zero_fees,
3529                         cltv_expiry_delta: (10 << 4) | 1,
3530                         htlc_minimum_msat: None,
3531                         htlc_maximum_msat: None,
3532                 }])]
3533         }
3534
3535         #[test]
3536         fn last_hops_with_public_channel_test() {
3537                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3538                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3539                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops_with_public_channel(&nodes)).unwrap();
3540                 let scorer = ln_test_utils::TestScorer::new();
3541                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3542                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3543                 // This test shows that public routes can be present in the invoice
3544                 // which would be handled in the same manner.
3545
3546                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3547                 assert_eq!(route.paths[0].hops.len(), 5);
3548
3549                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3550                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3551                 assert_eq!(route.paths[0].hops[0].fee_msat, 100);
3552                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3553                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3554                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3555
3556                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3557                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3558                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3559                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3560                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3561                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3562
3563                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3564                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3565                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3566                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3567                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3568                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3569
3570                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3571                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3572                 assert_eq!(route.paths[0].hops[3].fee_msat, 0);
3573                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3574                 // If we have a peer in the node map, we'll use their features here since we don't have
3575                 // a way of figuring out their features from the invoice:
3576                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3577                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3578
3579                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3580                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3581                 assert_eq!(route.paths[0].hops[4].fee_msat, 100);
3582                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3583                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3584                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3585         }
3586
3587         #[test]
3588         fn our_chans_last_hop_connect_test() {
3589                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
3590                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
3591                 let scorer = ln_test_utils::TestScorer::new();
3592                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3593                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3594
3595                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
3596                 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
3597                 let mut last_hops = last_hops(&nodes);
3598                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops.clone()).unwrap();
3599                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3600                 assert_eq!(route.paths[0].hops.len(), 2);
3601
3602                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[3]);
3603                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3604                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
3605                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3606                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &vec![0b11]);
3607                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
3608
3609                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[6]);
3610                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3611                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3612                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3613                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3614                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3615
3616                 last_hops[0].0[0].fees.base_msat = 1000;
3617
3618                 // Revert to via 6 as the fee on 8 goes up
3619                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops).unwrap();
3620                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3621                 assert_eq!(route.paths[0].hops.len(), 4);
3622
3623                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3624                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3625                 assert_eq!(route.paths[0].hops[0].fee_msat, 200); // fee increased as its % of value transferred across node
3626                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3627                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3628                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3629
3630                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3631                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3632                 assert_eq!(route.paths[0].hops[1].fee_msat, 100);
3633                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (7 << 4) | 1);
3634                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3635                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3636
3637                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[5]);
3638                 assert_eq!(route.paths[0].hops[2].short_channel_id, 7);
3639                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3640                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (10 << 4) | 1);
3641                 // If we have a peer in the node map, we'll use their features here since we don't have
3642                 // a way of figuring out their features from the invoice:
3643                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
3644                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(7));
3645
3646                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[6]);
3647                 assert_eq!(route.paths[0].hops[3].short_channel_id, 10);
3648                 assert_eq!(route.paths[0].hops[3].fee_msat, 100);
3649                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, 42);
3650                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3651                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3652
3653                 // ...but still use 8 for larger payments as 6 has a variable feerate
3654                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 2000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3655                 assert_eq!(route.paths[0].hops.len(), 5);
3656
3657                 assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
3658                 assert_eq!(route.paths[0].hops[0].short_channel_id, 2);
3659                 assert_eq!(route.paths[0].hops[0].fee_msat, 3000);
3660                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (4 << 4) | 1);
3661                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(2));
3662                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(2));
3663
3664                 assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
3665                 assert_eq!(route.paths[0].hops[1].short_channel_id, 4);
3666                 assert_eq!(route.paths[0].hops[1].fee_msat, 0);
3667                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (6 << 4) | 1);
3668                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
3669                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(4));
3670
3671                 assert_eq!(route.paths[0].hops[2].pubkey, nodes[4]);
3672                 assert_eq!(route.paths[0].hops[2].short_channel_id, 6);
3673                 assert_eq!(route.paths[0].hops[2].fee_msat, 0);
3674                 assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, (11 << 4) | 1);
3675                 assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(5));
3676                 assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(6));
3677
3678                 assert_eq!(route.paths[0].hops[3].pubkey, nodes[3]);
3679                 assert_eq!(route.paths[0].hops[3].short_channel_id, 11);
3680                 assert_eq!(route.paths[0].hops[3].fee_msat, 1000);
3681                 assert_eq!(route.paths[0].hops[3].cltv_expiry_delta, (8 << 4) | 1);
3682                 // If we have a peer in the node map, we'll use their features here since we don't have
3683                 // a way of figuring out their features from the invoice:
3684                 assert_eq!(route.paths[0].hops[3].node_features.le_flags(), &id_to_feature_flags(4));
3685                 assert_eq!(route.paths[0].hops[3].channel_features.le_flags(), &id_to_feature_flags(11));
3686
3687                 assert_eq!(route.paths[0].hops[4].pubkey, nodes[6]);
3688                 assert_eq!(route.paths[0].hops[4].short_channel_id, 8);
3689                 assert_eq!(route.paths[0].hops[4].fee_msat, 2000);
3690                 assert_eq!(route.paths[0].hops[4].cltv_expiry_delta, 42);
3691                 assert_eq!(route.paths[0].hops[4].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3692                 assert_eq!(route.paths[0].hops[4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
3693         }
3694
3695         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> {
3696                 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
3697                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3698                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3699
3700                 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
3701                 let last_hops = RouteHint(vec![RouteHintHop {
3702                         src_node_id: middle_node_id,
3703                         short_channel_id: 8,
3704                         fees: RoutingFees {
3705                                 base_msat: 1000,
3706                                 proportional_millionths: last_hop_fee_prop,
3707                         },
3708                         cltv_expiry_delta: (8 << 4) | 1,
3709                         htlc_minimum_msat: None,
3710                         htlc_maximum_msat: last_hop_htlc_max,
3711                 }]);
3712                 let payment_params = PaymentParameters::from_node_id(target_node_id, 42).with_route_hints(vec![last_hops]).unwrap();
3713                 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
3714                 let scorer = ln_test_utils::TestScorer::new();
3715                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3716                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3717                 let logger = ln_test_utils::TestLogger::new();
3718                 let network_graph = NetworkGraph::new(Network::Testnet, &logger);
3719                 let route = get_route(&source_node_id, &payment_params, &network_graph.read_only(),
3720                                 Some(&our_chans.iter().collect::<Vec<_>>()), route_val, &logger, &scorer, &(), &random_seed_bytes);
3721                 route
3722         }
3723
3724         #[test]
3725         fn unannounced_path_test() {
3726                 // We should be able to send a payment to a destination without any help of a routing graph
3727                 // if we have a channel with a common counterparty that appears in the first and last hop
3728                 // hints.
3729                 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
3730
3731                 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
3732                 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
3733                 assert_eq!(route.paths[0].hops.len(), 2);
3734
3735                 assert_eq!(route.paths[0].hops[0].pubkey, middle_node_id);
3736                 assert_eq!(route.paths[0].hops[0].short_channel_id, 42);
3737                 assert_eq!(route.paths[0].hops[0].fee_msat, 1001);
3738                 assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (8 << 4) | 1);
3739                 assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &[0b11]);
3740                 assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3741
3742                 assert_eq!(route.paths[0].hops[1].pubkey, target_node_id);
3743                 assert_eq!(route.paths[0].hops[1].short_channel_id, 8);
3744                 assert_eq!(route.paths[0].hops[1].fee_msat, 1000000);
3745                 assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
3746                 assert_eq!(route.paths[0].hops[1].node_features.le_flags(), default_node_features().le_flags()); // We dont pass flags in from invoices yet
3747                 assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
3748         }
3749
3750         #[test]
3751         fn overflow_unannounced_path_test_liquidity_underflow() {
3752                 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
3753                 // the last-hop had a fee which overflowed a u64, we'd panic.
3754                 // This was due to us adding the first-hop from us unconditionally, causing us to think
3755                 // we'd built a path (as our node is in the "best candidate" set), when we had not.
3756                 // In this test, we previously hit a subtraction underflow due to having less available
3757                 // liquidity at the last hop than 0.
3758                 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());
3759         }
3760
3761         #[test]
3762         fn overflow_unannounced_path_test_feerate_overflow() {
3763                 // This tests for the same case as above, except instead of hitting a subtraction
3764                 // underflow, we hit a case where the fee charged at a hop overflowed.
3765                 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());
3766         }
3767
3768         #[test]
3769         fn available_amount_while_routing_test() {
3770                 // Tests whether we choose the correct available channel amount while routing.
3771
3772                 let (secp_ctx, network_graph, mut gossip_sync, chain_monitor, logger) = build_graph();
3773                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3774                 let scorer = ln_test_utils::TestScorer::new();
3775                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
3776                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
3777                 let config = UserConfig::default();
3778                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
3779
3780                 // We will use a simple single-path route from
3781                 // our node to node2 via node0: channels {1, 3}.
3782
3783                 // First disable all other paths.
3784                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3785                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3786                         short_channel_id: 2,
3787                         timestamp: 2,
3788                         flags: 2,
3789                         cltv_expiry_delta: 0,
3790                         htlc_minimum_msat: 0,
3791                         htlc_maximum_msat: 100_000,
3792                         fee_base_msat: 0,
3793                         fee_proportional_millionths: 0,
3794                         excess_data: Vec::new()
3795                 });
3796                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3797                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3798                         short_channel_id: 12,
3799                         timestamp: 2,
3800                         flags: 2,
3801                         cltv_expiry_delta: 0,
3802                         htlc_minimum_msat: 0,
3803                         htlc_maximum_msat: 100_000,
3804                         fee_base_msat: 0,
3805                         fee_proportional_millionths: 0,
3806                         excess_data: Vec::new()
3807                 });
3808
3809                 // Make the first channel (#1) very permissive,
3810                 // and we will be testing all limits on the second channel.
3811                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3812                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3813                         short_channel_id: 1,
3814                         timestamp: 2,
3815                         flags: 0,
3816                         cltv_expiry_delta: 0,
3817                         htlc_minimum_msat: 0,
3818                         htlc_maximum_msat: 1_000_000_000,
3819                         fee_base_msat: 0,
3820                         fee_proportional_millionths: 0,
3821                         excess_data: Vec::new()
3822                 });
3823
3824                 // First, let's see if routing works if we have absolutely no idea about the available amount.
3825                 // In this case, it should be set to 250_000 sats.
3826                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3827                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3828                         short_channel_id: 3,
3829                         timestamp: 2,
3830                         flags: 0,
3831                         cltv_expiry_delta: 0,
3832                         htlc_minimum_msat: 0,
3833                         htlc_maximum_msat: 250_000_000,
3834                         fee_base_msat: 0,
3835                         fee_proportional_millionths: 0,
3836                         excess_data: Vec::new()
3837                 });
3838
3839                 {
3840                         // Attempt to route more than available results in a failure.
3841                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3842                                         &our_id, &payment_params, &network_graph.read_only(), None, 250_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3843                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3844                         } else { panic!(); }
3845                 }
3846
3847                 {
3848                         // Now, attempt to route an exact amount we have should be fine.
3849                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 250_000_000, Arc::clone(&logger), &scorer, &(),&random_seed_bytes).unwrap();
3850                         assert_eq!(route.paths.len(), 1);
3851                         let path = route.paths.last().unwrap();
3852                         assert_eq!(path.hops.len(), 2);
3853                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3854                         assert_eq!(path.final_value_msat(), 250_000_000);
3855                 }
3856
3857                 // Check that setting next_outbound_htlc_limit_msat in first_hops limits the channels.
3858                 // Disable channel #1 and use another first hop.
3859                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3860                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3861                         short_channel_id: 1,
3862                         timestamp: 3,
3863                         flags: 2,
3864                         cltv_expiry_delta: 0,
3865                         htlc_minimum_msat: 0,
3866                         htlc_maximum_msat: 1_000_000_000,
3867                         fee_base_msat: 0,
3868                         fee_proportional_millionths: 0,
3869                         excess_data: Vec::new()
3870                 });
3871
3872                 // Now, limit the first_hop by the next_outbound_htlc_limit_msat of 200_000 sats.
3873                 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3874
3875                 {
3876                         // Attempt to route more than available results in a failure.
3877                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3878                                         &our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3879                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3880                         } else { panic!(); }
3881                 }
3882
3883                 {
3884                         // Now, attempt to route an exact amount we have should be fine.
3885                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3886                         assert_eq!(route.paths.len(), 1);
3887                         let path = route.paths.last().unwrap();
3888                         assert_eq!(path.hops.len(), 2);
3889                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3890                         assert_eq!(path.final_value_msat(), 200_000_000);
3891                 }
3892
3893                 // Enable channel #1 back.
3894                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3895                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3896                         short_channel_id: 1,
3897                         timestamp: 4,
3898                         flags: 0,
3899                         cltv_expiry_delta: 0,
3900                         htlc_minimum_msat: 0,
3901                         htlc_maximum_msat: 1_000_000_000,
3902                         fee_base_msat: 0,
3903                         fee_proportional_millionths: 0,
3904                         excess_data: Vec::new()
3905                 });
3906
3907
3908                 // Now let's see if routing works if we know only htlc_maximum_msat.
3909                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3910                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3911                         short_channel_id: 3,
3912                         timestamp: 3,
3913                         flags: 0,
3914                         cltv_expiry_delta: 0,
3915                         htlc_minimum_msat: 0,
3916                         htlc_maximum_msat: 15_000,
3917                         fee_base_msat: 0,
3918                         fee_proportional_millionths: 0,
3919                         excess_data: Vec::new()
3920                 });
3921
3922                 {
3923                         // Attempt to route more than available results in a failure.
3924                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3925                                         &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3926                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3927                         } else { panic!(); }
3928                 }
3929
3930                 {
3931                         // Now, attempt to route an exact amount we have should be fine.
3932                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
3933                         assert_eq!(route.paths.len(), 1);
3934                         let path = route.paths.last().unwrap();
3935                         assert_eq!(path.hops.len(), 2);
3936                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
3937                         assert_eq!(path.final_value_msat(), 15_000);
3938                 }
3939
3940                 // Now let's see if routing works if we know only capacity from the UTXO.
3941
3942                 // We can't change UTXO capacity on the fly, so we'll disable
3943                 // the existing channel and add another one with the capacity we need.
3944                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3945                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3946                         short_channel_id: 3,
3947                         timestamp: 4,
3948                         flags: 2,
3949                         cltv_expiry_delta: 0,
3950                         htlc_minimum_msat: 0,
3951                         htlc_maximum_msat: MAX_VALUE_MSAT,
3952                         fee_base_msat: 0,
3953                         fee_proportional_millionths: 0,
3954                         excess_data: Vec::new()
3955                 });
3956
3957                 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3958                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3959                 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3960                 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3961                 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3962
3963                 *chain_monitor.utxo_ret.lock().unwrap() =
3964                         UtxoResult::Sync(Ok(TxOut { value: 15, script_pubkey: good_script.clone() }));
3965                 gossip_sync.add_utxo_lookup(Some(chain_monitor));
3966
3967                 add_channel(&gossip_sync, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3968                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3969                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3970                         short_channel_id: 333,
3971                         timestamp: 1,
3972                         flags: 0,
3973                         cltv_expiry_delta: (3 << 4) | 1,
3974                         htlc_minimum_msat: 0,
3975                         htlc_maximum_msat: 15_000,
3976                         fee_base_msat: 0,
3977                         fee_proportional_millionths: 0,
3978                         excess_data: Vec::new()
3979                 });
3980                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3981                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3982                         short_channel_id: 333,
3983                         timestamp: 1,
3984                         flags: 1,
3985                         cltv_expiry_delta: (3 << 4) | 2,
3986                         htlc_minimum_msat: 0,
3987                         htlc_maximum_msat: 15_000,
3988                         fee_base_msat: 100,
3989                         fee_proportional_millionths: 0,
3990                         excess_data: Vec::new()
3991                 });
3992
3993                 {
3994                         // Attempt to route more than available results in a failure.
3995                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3996                                         &our_id, &payment_params, &network_graph.read_only(), None, 15_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
3997                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3998                         } else { panic!(); }
3999                 }
4000
4001                 {
4002                         // Now, attempt to route an exact amount we have should be fine.
4003                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 15_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4004                         assert_eq!(route.paths.len(), 1);
4005                         let path = route.paths.last().unwrap();
4006                         assert_eq!(path.hops.len(), 2);
4007                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4008                         assert_eq!(path.final_value_msat(), 15_000);
4009                 }
4010
4011                 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
4012                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4013                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4014                         short_channel_id: 333,
4015                         timestamp: 6,
4016                         flags: 0,
4017                         cltv_expiry_delta: 0,
4018                         htlc_minimum_msat: 0,
4019                         htlc_maximum_msat: 10_000,
4020                         fee_base_msat: 0,
4021                         fee_proportional_millionths: 0,
4022                         excess_data: Vec::new()
4023                 });
4024
4025                 {
4026                         // Attempt to route more than available results in a failure.
4027                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4028                                         &our_id, &payment_params, &network_graph.read_only(), None, 10_001, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4029                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4030                         } else { panic!(); }
4031                 }
4032
4033                 {
4034                         // Now, attempt to route an exact amount we have should be fine.
4035                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4036                         assert_eq!(route.paths.len(), 1);
4037                         let path = route.paths.last().unwrap();
4038                         assert_eq!(path.hops.len(), 2);
4039                         assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4040                         assert_eq!(path.final_value_msat(), 10_000);
4041                 }
4042         }
4043
4044         #[test]
4045         fn available_liquidity_last_hop_test() {
4046                 // Check that available liquidity properly limits the path even when only
4047                 // one of the latter hops is limited.
4048                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4049                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4050                 let scorer = ln_test_utils::TestScorer::new();
4051                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4052                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4053                 let config = UserConfig::default();
4054                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4055
4056                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4057                 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
4058                 // Total capacity: 50 sats.
4059
4060                 // Disable other potential paths.
4061                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4062                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4063                         short_channel_id: 2,
4064                         timestamp: 2,
4065                         flags: 2,
4066                         cltv_expiry_delta: 0,
4067                         htlc_minimum_msat: 0,
4068                         htlc_maximum_msat: 100_000,
4069                         fee_base_msat: 0,
4070                         fee_proportional_millionths: 0,
4071                         excess_data: Vec::new()
4072                 });
4073                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4074                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4075                         short_channel_id: 7,
4076                         timestamp: 2,
4077                         flags: 2,
4078                         cltv_expiry_delta: 0,
4079                         htlc_minimum_msat: 0,
4080                         htlc_maximum_msat: 100_000,
4081                         fee_base_msat: 0,
4082                         fee_proportional_millionths: 0,
4083                         excess_data: Vec::new()
4084                 });
4085
4086                 // Limit capacities
4087
4088                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4089                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4090                         short_channel_id: 12,
4091                         timestamp: 2,
4092                         flags: 0,
4093                         cltv_expiry_delta: 0,
4094                         htlc_minimum_msat: 0,
4095                         htlc_maximum_msat: 100_000,
4096                         fee_base_msat: 0,
4097                         fee_proportional_millionths: 0,
4098                         excess_data: Vec::new()
4099                 });
4100                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4101                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4102                         short_channel_id: 13,
4103                         timestamp: 2,
4104                         flags: 0,
4105                         cltv_expiry_delta: 0,
4106                         htlc_minimum_msat: 0,
4107                         htlc_maximum_msat: 100_000,
4108                         fee_base_msat: 0,
4109                         fee_proportional_millionths: 0,
4110                         excess_data: Vec::new()
4111                 });
4112
4113                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4114                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4115                         short_channel_id: 6,
4116                         timestamp: 2,
4117                         flags: 0,
4118                         cltv_expiry_delta: 0,
4119                         htlc_minimum_msat: 0,
4120                         htlc_maximum_msat: 50_000,
4121                         fee_base_msat: 0,
4122                         fee_proportional_millionths: 0,
4123                         excess_data: Vec::new()
4124                 });
4125                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4126                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4127                         short_channel_id: 11,
4128                         timestamp: 2,
4129                         flags: 0,
4130                         cltv_expiry_delta: 0,
4131                         htlc_minimum_msat: 0,
4132                         htlc_maximum_msat: 100_000,
4133                         fee_base_msat: 0,
4134                         fee_proportional_millionths: 0,
4135                         excess_data: Vec::new()
4136                 });
4137                 {
4138                         // Attempt to route more than available results in a failure.
4139                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4140                                         &our_id, &payment_params, &network_graph.read_only(), None, 60_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4141                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4142                         } else { panic!(); }
4143                 }
4144
4145                 {
4146                         // Now, attempt to route 49 sats (just a bit below the capacity).
4147                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 49_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4148                         assert_eq!(route.paths.len(), 1);
4149                         let mut total_amount_paid_msat = 0;
4150                         for path in &route.paths {
4151                                 assert_eq!(path.hops.len(), 4);
4152                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4153                                 total_amount_paid_msat += path.final_value_msat();
4154                         }
4155                         assert_eq!(total_amount_paid_msat, 49_000);
4156                 }
4157
4158                 {
4159                         // Attempt to route an exact amount is also fine
4160                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4161                         assert_eq!(route.paths.len(), 1);
4162                         let mut total_amount_paid_msat = 0;
4163                         for path in &route.paths {
4164                                 assert_eq!(path.hops.len(), 4);
4165                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4166                                 total_amount_paid_msat += path.final_value_msat();
4167                         }
4168                         assert_eq!(total_amount_paid_msat, 50_000);
4169                 }
4170         }
4171
4172         #[test]
4173         fn ignore_fee_first_hop_test() {
4174                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4175                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4176                 let scorer = ln_test_utils::TestScorer::new();
4177                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4178                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4179                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
4180
4181                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4182                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4183                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4184                         short_channel_id: 1,
4185                         timestamp: 2,
4186                         flags: 0,
4187                         cltv_expiry_delta: 0,
4188                         htlc_minimum_msat: 0,
4189                         htlc_maximum_msat: 100_000,
4190                         fee_base_msat: 1_000_000,
4191                         fee_proportional_millionths: 0,
4192                         excess_data: Vec::new()
4193                 });
4194                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4195                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4196                         short_channel_id: 3,
4197                         timestamp: 2,
4198                         flags: 0,
4199                         cltv_expiry_delta: 0,
4200                         htlc_minimum_msat: 0,
4201                         htlc_maximum_msat: 50_000,
4202                         fee_base_msat: 0,
4203                         fee_proportional_millionths: 0,
4204                         excess_data: Vec::new()
4205                 });
4206
4207                 {
4208                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 50_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4209                         assert_eq!(route.paths.len(), 1);
4210                         let mut total_amount_paid_msat = 0;
4211                         for path in &route.paths {
4212                                 assert_eq!(path.hops.len(), 2);
4213                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4214                                 total_amount_paid_msat += path.final_value_msat();
4215                         }
4216                         assert_eq!(total_amount_paid_msat, 50_000);
4217                 }
4218         }
4219
4220         #[test]
4221         fn simple_mpp_route_test() {
4222                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4223                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4224                 let scorer = ln_test_utils::TestScorer::new();
4225                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4226                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4227                 let config = UserConfig::default();
4228                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42)
4229                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4230
4231                 // We need a route consisting of 3 paths:
4232                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4233                 // To achieve this, the amount being transferred should be around
4234                 // the total capacity of these 3 paths.
4235
4236                 // First, we set limits on these (previously unlimited) channels.
4237                 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
4238
4239                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
4240                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4241                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4242                         short_channel_id: 1,
4243                         timestamp: 2,
4244                         flags: 0,
4245                         cltv_expiry_delta: 0,
4246                         htlc_minimum_msat: 0,
4247                         htlc_maximum_msat: 100_000,
4248                         fee_base_msat: 0,
4249                         fee_proportional_millionths: 0,
4250                         excess_data: Vec::new()
4251                 });
4252                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4253                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4254                         short_channel_id: 3,
4255                         timestamp: 2,
4256                         flags: 0,
4257                         cltv_expiry_delta: 0,
4258                         htlc_minimum_msat: 0,
4259                         htlc_maximum_msat: 50_000,
4260                         fee_base_msat: 0,
4261                         fee_proportional_millionths: 0,
4262                         excess_data: Vec::new()
4263                 });
4264
4265                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
4266                 // (total limit 60).
4267                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4268                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4269                         short_channel_id: 12,
4270                         timestamp: 2,
4271                         flags: 0,
4272                         cltv_expiry_delta: 0,
4273                         htlc_minimum_msat: 0,
4274                         htlc_maximum_msat: 60_000,
4275                         fee_base_msat: 0,
4276                         fee_proportional_millionths: 0,
4277                         excess_data: Vec::new()
4278                 });
4279                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4280                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4281                         short_channel_id: 13,
4282                         timestamp: 2,
4283                         flags: 0,
4284                         cltv_expiry_delta: 0,
4285                         htlc_minimum_msat: 0,
4286                         htlc_maximum_msat: 60_000,
4287                         fee_base_msat: 0,
4288                         fee_proportional_millionths: 0,
4289                         excess_data: Vec::new()
4290                 });
4291
4292                 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
4293                 // (total capacity 180 sats).
4294                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4295                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4296                         short_channel_id: 2,
4297                         timestamp: 2,
4298                         flags: 0,
4299                         cltv_expiry_delta: 0,
4300                         htlc_minimum_msat: 0,
4301                         htlc_maximum_msat: 200_000,
4302                         fee_base_msat: 0,
4303                         fee_proportional_millionths: 0,
4304                         excess_data: Vec::new()
4305                 });
4306                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4307                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4308                         short_channel_id: 4,
4309                         timestamp: 2,
4310                         flags: 0,
4311                         cltv_expiry_delta: 0,
4312                         htlc_minimum_msat: 0,
4313                         htlc_maximum_msat: 180_000,
4314                         fee_base_msat: 0,
4315                         fee_proportional_millionths: 0,
4316                         excess_data: Vec::new()
4317                 });
4318
4319                 {
4320                         // Attempt to route more than available results in a failure.
4321                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4322                                 &our_id, &payment_params, &network_graph.read_only(), None, 300_000,
4323                                 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4324                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
4325                         } else { panic!(); }
4326                 }
4327
4328                 {
4329                         // Attempt to route while setting max_path_count to 0 results in a failure.
4330                         let zero_payment_params = payment_params.clone().with_max_path_count(0);
4331                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4332                                 &our_id, &zero_payment_params, &network_graph.read_only(), None, 100,
4333                                 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4334                                         assert_eq!(err, "Can't find a route with no paths allowed.");
4335                         } else { panic!(); }
4336                 }
4337
4338                 {
4339                         // Attempt to route while setting max_path_count to 3 results in a failure.
4340                         // This is the case because the minimal_value_contribution_msat would require each path
4341                         // to account for 1/3 of the total value, which is violated by 2 out of 3 paths.
4342                         let fail_payment_params = payment_params.clone().with_max_path_count(3);
4343                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4344                                 &our_id, &fail_payment_params, &network_graph.read_only(), None, 250_000,
4345                                 Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4346                                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
4347                         } else { panic!(); }
4348                 }
4349
4350                 {
4351                         // Now, attempt to route 250 sats (just a bit below the capacity).
4352                         // Our algorithm should provide us with these 3 paths.
4353                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4354                                 250_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4355                         assert_eq!(route.paths.len(), 3);
4356                         let mut total_amount_paid_msat = 0;
4357                         for path in &route.paths {
4358                                 assert_eq!(path.hops.len(), 2);
4359                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4360                                 total_amount_paid_msat += path.final_value_msat();
4361                         }
4362                         assert_eq!(total_amount_paid_msat, 250_000);
4363                 }
4364
4365                 {
4366                         // Attempt to route an exact amount is also fine
4367                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None,
4368                                 290_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4369                         assert_eq!(route.paths.len(), 3);
4370                         let mut total_amount_paid_msat = 0;
4371                         for path in &route.paths {
4372                                 assert_eq!(path.hops.len(), 2);
4373                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
4374                                 total_amount_paid_msat += path.final_value_msat();
4375                         }
4376                         assert_eq!(total_amount_paid_msat, 290_000);
4377                 }
4378         }
4379
4380         #[test]
4381         fn long_mpp_route_test() {
4382                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4383                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4384                 let scorer = ln_test_utils::TestScorer::new();
4385                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4386                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4387                 let config = UserConfig::default();
4388                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4389
4390                 // We need a route consisting of 3 paths:
4391                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4392                 // Note that these paths overlap (channels 5, 12, 13).
4393                 // We will route 300 sats.
4394                 // Each path will have 100 sats capacity, those channels which
4395                 // are used twice will have 200 sats capacity.
4396
4397                 // Disable other potential paths.
4398                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4399                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4400                         short_channel_id: 2,
4401                         timestamp: 2,
4402                         flags: 2,
4403                         cltv_expiry_delta: 0,
4404                         htlc_minimum_msat: 0,
4405                         htlc_maximum_msat: 100_000,
4406                         fee_base_msat: 0,
4407                         fee_proportional_millionths: 0,
4408                         excess_data: Vec::new()
4409                 });
4410                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4411                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4412                         short_channel_id: 7,
4413                         timestamp: 2,
4414                         flags: 2,
4415                         cltv_expiry_delta: 0,
4416                         htlc_minimum_msat: 0,
4417                         htlc_maximum_msat: 100_000,
4418                         fee_base_msat: 0,
4419                         fee_proportional_millionths: 0,
4420                         excess_data: Vec::new()
4421                 });
4422
4423                 // Path via {node0, node2} is channels {1, 3, 5}.
4424                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4425                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4426                         short_channel_id: 1,
4427                         timestamp: 2,
4428                         flags: 0,
4429                         cltv_expiry_delta: 0,
4430                         htlc_minimum_msat: 0,
4431                         htlc_maximum_msat: 100_000,
4432                         fee_base_msat: 0,
4433                         fee_proportional_millionths: 0,
4434                         excess_data: Vec::new()
4435                 });
4436                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4437                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4438                         short_channel_id: 3,
4439                         timestamp: 2,
4440                         flags: 0,
4441                         cltv_expiry_delta: 0,
4442                         htlc_minimum_msat: 0,
4443                         htlc_maximum_msat: 100_000,
4444                         fee_base_msat: 0,
4445                         fee_proportional_millionths: 0,
4446                         excess_data: Vec::new()
4447                 });
4448
4449                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4450                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4451                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4452                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4453                         short_channel_id: 5,
4454                         timestamp: 2,
4455                         flags: 0,
4456                         cltv_expiry_delta: 0,
4457                         htlc_minimum_msat: 0,
4458                         htlc_maximum_msat: 200_000,
4459                         fee_base_msat: 0,
4460                         fee_proportional_millionths: 0,
4461                         excess_data: Vec::new()
4462                 });
4463
4464                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4465                 // Add 100 sats to the capacities of {12, 13}, because these channels
4466                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4467                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4468                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4469                         short_channel_id: 12,
4470                         timestamp: 2,
4471                         flags: 0,
4472                         cltv_expiry_delta: 0,
4473                         htlc_minimum_msat: 0,
4474                         htlc_maximum_msat: 200_000,
4475                         fee_base_msat: 0,
4476                         fee_proportional_millionths: 0,
4477                         excess_data: Vec::new()
4478                 });
4479                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4480                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4481                         short_channel_id: 13,
4482                         timestamp: 2,
4483                         flags: 0,
4484                         cltv_expiry_delta: 0,
4485                         htlc_minimum_msat: 0,
4486                         htlc_maximum_msat: 200_000,
4487                         fee_base_msat: 0,
4488                         fee_proportional_millionths: 0,
4489                         excess_data: Vec::new()
4490                 });
4491
4492                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4493                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4494                         short_channel_id: 6,
4495                         timestamp: 2,
4496                         flags: 0,
4497                         cltv_expiry_delta: 0,
4498                         htlc_minimum_msat: 0,
4499                         htlc_maximum_msat: 100_000,
4500                         fee_base_msat: 0,
4501                         fee_proportional_millionths: 0,
4502                         excess_data: Vec::new()
4503                 });
4504                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4505                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4506                         short_channel_id: 11,
4507                         timestamp: 2,
4508                         flags: 0,
4509                         cltv_expiry_delta: 0,
4510                         htlc_minimum_msat: 0,
4511                         htlc_maximum_msat: 100_000,
4512                         fee_base_msat: 0,
4513                         fee_proportional_millionths: 0,
4514                         excess_data: Vec::new()
4515                 });
4516
4517                 // Path via {node7, node2} is channels {12, 13, 5}.
4518                 // We already limited them to 200 sats (they are used twice for 100 sats).
4519                 // Nothing to do here.
4520
4521                 {
4522                         // Attempt to route more than available results in a failure.
4523                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4524                                         &our_id, &payment_params, &network_graph.read_only(), None, 350_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4525                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4526                         } else { panic!(); }
4527                 }
4528
4529                 {
4530                         // Now, attempt to route 300 sats (exact amount we can route).
4531                         // Our algorithm should provide us with these 3 paths, 100 sats each.
4532                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 300_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4533                         assert_eq!(route.paths.len(), 3);
4534
4535                         let mut total_amount_paid_msat = 0;
4536                         for path in &route.paths {
4537                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4538                                 total_amount_paid_msat += path.final_value_msat();
4539                         }
4540                         assert_eq!(total_amount_paid_msat, 300_000);
4541                 }
4542
4543         }
4544
4545         #[test]
4546         fn mpp_cheaper_route_test() {
4547                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4548                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4549                 let scorer = ln_test_utils::TestScorer::new();
4550                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4551                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4552                 let config = UserConfig::default();
4553                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4554
4555                 // This test checks that if we have two cheaper paths and one more expensive path,
4556                 // so that liquidity-wise any 2 of 3 combination is sufficient,
4557                 // two cheaper paths will be taken.
4558                 // These paths have equal available liquidity.
4559
4560                 // We need a combination of 3 paths:
4561                 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
4562                 // Note that these paths overlap (channels 5, 12, 13).
4563                 // Each path will have 100 sats capacity, those channels which
4564                 // are used twice will have 200 sats capacity.
4565
4566                 // Disable other potential paths.
4567                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4568                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4569                         short_channel_id: 2,
4570                         timestamp: 2,
4571                         flags: 2,
4572                         cltv_expiry_delta: 0,
4573                         htlc_minimum_msat: 0,
4574                         htlc_maximum_msat: 100_000,
4575                         fee_base_msat: 0,
4576                         fee_proportional_millionths: 0,
4577                         excess_data: Vec::new()
4578                 });
4579                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4580                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4581                         short_channel_id: 7,
4582                         timestamp: 2,
4583                         flags: 2,
4584                         cltv_expiry_delta: 0,
4585                         htlc_minimum_msat: 0,
4586                         htlc_maximum_msat: 100_000,
4587                         fee_base_msat: 0,
4588                         fee_proportional_millionths: 0,
4589                         excess_data: Vec::new()
4590                 });
4591
4592                 // Path via {node0, node2} is channels {1, 3, 5}.
4593                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4594                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4595                         short_channel_id: 1,
4596                         timestamp: 2,
4597                         flags: 0,
4598                         cltv_expiry_delta: 0,
4599                         htlc_minimum_msat: 0,
4600                         htlc_maximum_msat: 100_000,
4601                         fee_base_msat: 0,
4602                         fee_proportional_millionths: 0,
4603                         excess_data: Vec::new()
4604                 });
4605                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4606                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4607                         short_channel_id: 3,
4608                         timestamp: 2,
4609                         flags: 0,
4610                         cltv_expiry_delta: 0,
4611                         htlc_minimum_msat: 0,
4612                         htlc_maximum_msat: 100_000,
4613                         fee_base_msat: 0,
4614                         fee_proportional_millionths: 0,
4615                         excess_data: Vec::new()
4616                 });
4617
4618                 // Capacity of 200 sats because this channel will be used by 3rd path as well.
4619                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4620                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4621                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4622                         short_channel_id: 5,
4623                         timestamp: 2,
4624                         flags: 0,
4625                         cltv_expiry_delta: 0,
4626                         htlc_minimum_msat: 0,
4627                         htlc_maximum_msat: 200_000,
4628                         fee_base_msat: 0,
4629                         fee_proportional_millionths: 0,
4630                         excess_data: Vec::new()
4631                 });
4632
4633                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4634                 // Add 100 sats to the capacities of {12, 13}, because these channels
4635                 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
4636                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4637                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4638                         short_channel_id: 12,
4639                         timestamp: 2,
4640                         flags: 0,
4641                         cltv_expiry_delta: 0,
4642                         htlc_minimum_msat: 0,
4643                         htlc_maximum_msat: 200_000,
4644                         fee_base_msat: 0,
4645                         fee_proportional_millionths: 0,
4646                         excess_data: Vec::new()
4647                 });
4648                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4649                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4650                         short_channel_id: 13,
4651                         timestamp: 2,
4652                         flags: 0,
4653                         cltv_expiry_delta: 0,
4654                         htlc_minimum_msat: 0,
4655                         htlc_maximum_msat: 200_000,
4656                         fee_base_msat: 0,
4657                         fee_proportional_millionths: 0,
4658                         excess_data: Vec::new()
4659                 });
4660
4661                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4662                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4663                         short_channel_id: 6,
4664                         timestamp: 2,
4665                         flags: 0,
4666                         cltv_expiry_delta: 0,
4667                         htlc_minimum_msat: 0,
4668                         htlc_maximum_msat: 100_000,
4669                         fee_base_msat: 1_000,
4670                         fee_proportional_millionths: 0,
4671                         excess_data: Vec::new()
4672                 });
4673                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4674                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4675                         short_channel_id: 11,
4676                         timestamp: 2,
4677                         flags: 0,
4678                         cltv_expiry_delta: 0,
4679                         htlc_minimum_msat: 0,
4680                         htlc_maximum_msat: 100_000,
4681                         fee_base_msat: 0,
4682                         fee_proportional_millionths: 0,
4683                         excess_data: Vec::new()
4684                 });
4685
4686                 // Path via {node7, node2} is channels {12, 13, 5}.
4687                 // We already limited them to 200 sats (they are used twice for 100 sats).
4688                 // Nothing to do here.
4689
4690                 {
4691                         // Now, attempt to route 180 sats.
4692                         // Our algorithm should provide us with these 2 paths.
4693                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 180_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4694                         assert_eq!(route.paths.len(), 2);
4695
4696                         let mut total_value_transferred_msat = 0;
4697                         let mut total_paid_msat = 0;
4698                         for path in &route.paths {
4699                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4700                                 total_value_transferred_msat += path.final_value_msat();
4701                                 for hop in &path.hops {
4702                                         total_paid_msat += hop.fee_msat;
4703                                 }
4704                         }
4705                         // If we paid fee, this would be higher.
4706                         assert_eq!(total_value_transferred_msat, 180_000);
4707                         let total_fees_paid = total_paid_msat - total_value_transferred_msat;
4708                         assert_eq!(total_fees_paid, 0);
4709                 }
4710         }
4711
4712         #[test]
4713         fn fees_on_mpp_route_test() {
4714                 // This test makes sure that MPP algorithm properly takes into account
4715                 // fees charged on the channels, by making the fees impactful:
4716                 // if the fee is not properly accounted for, the behavior is different.
4717                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4718                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4719                 let scorer = ln_test_utils::TestScorer::new();
4720                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4721                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4722                 let config = UserConfig::default();
4723                 let payment_params = PaymentParameters::from_node_id(nodes[3], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
4724
4725                 // We need a route consisting of 2 paths:
4726                 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
4727                 // We will route 200 sats, Each path will have 100 sats capacity.
4728
4729                 // This test is not particularly stable: e.g.,
4730                 // there's a way to route via {node0, node2, node4}.
4731                 // It works while pathfinding is deterministic, but can be broken otherwise.
4732                 // It's fine to ignore this concern for now.
4733
4734                 // Disable other potential paths.
4735                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4736                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4737                         short_channel_id: 2,
4738                         timestamp: 2,
4739                         flags: 2,
4740                         cltv_expiry_delta: 0,
4741                         htlc_minimum_msat: 0,
4742                         htlc_maximum_msat: 100_000,
4743                         fee_base_msat: 0,
4744                         fee_proportional_millionths: 0,
4745                         excess_data: Vec::new()
4746                 });
4747
4748                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4749                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4750                         short_channel_id: 7,
4751                         timestamp: 2,
4752                         flags: 2,
4753                         cltv_expiry_delta: 0,
4754                         htlc_minimum_msat: 0,
4755                         htlc_maximum_msat: 100_000,
4756                         fee_base_msat: 0,
4757                         fee_proportional_millionths: 0,
4758                         excess_data: Vec::new()
4759                 });
4760
4761                 // Path via {node0, node2} is channels {1, 3, 5}.
4762                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4763                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4764                         short_channel_id: 1,
4765                         timestamp: 2,
4766                         flags: 0,
4767                         cltv_expiry_delta: 0,
4768                         htlc_minimum_msat: 0,
4769                         htlc_maximum_msat: 100_000,
4770                         fee_base_msat: 0,
4771                         fee_proportional_millionths: 0,
4772                         excess_data: Vec::new()
4773                 });
4774                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4775                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4776                         short_channel_id: 3,
4777                         timestamp: 2,
4778                         flags: 0,
4779                         cltv_expiry_delta: 0,
4780                         htlc_minimum_msat: 0,
4781                         htlc_maximum_msat: 100_000,
4782                         fee_base_msat: 0,
4783                         fee_proportional_millionths: 0,
4784                         excess_data: Vec::new()
4785                 });
4786
4787                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4788                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4789                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4790                         short_channel_id: 5,
4791                         timestamp: 2,
4792                         flags: 0,
4793                         cltv_expiry_delta: 0,
4794                         htlc_minimum_msat: 0,
4795                         htlc_maximum_msat: 100_000,
4796                         fee_base_msat: 0,
4797                         fee_proportional_millionths: 0,
4798                         excess_data: Vec::new()
4799                 });
4800
4801                 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
4802                 // All channels should be 100 sats capacity. But for the fee experiment,
4803                 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
4804                 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
4805                 // 100 sats (and pay 150 sats in fees for the use of channel 6),
4806                 // so no matter how large are other channels,
4807                 // the whole path will be limited by 100 sats with just these 2 conditions:
4808                 // - channel 12 capacity is 250 sats
4809                 // - fee for channel 6 is 150 sats
4810                 // Let's test this by enforcing these 2 conditions and removing other limits.
4811                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4812                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4813                         short_channel_id: 12,
4814                         timestamp: 2,
4815                         flags: 0,
4816                         cltv_expiry_delta: 0,
4817                         htlc_minimum_msat: 0,
4818                         htlc_maximum_msat: 250_000,
4819                         fee_base_msat: 0,
4820                         fee_proportional_millionths: 0,
4821                         excess_data: Vec::new()
4822                 });
4823                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4824                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4825                         short_channel_id: 13,
4826                         timestamp: 2,
4827                         flags: 0,
4828                         cltv_expiry_delta: 0,
4829                         htlc_minimum_msat: 0,
4830                         htlc_maximum_msat: MAX_VALUE_MSAT,
4831                         fee_base_msat: 0,
4832                         fee_proportional_millionths: 0,
4833                         excess_data: Vec::new()
4834                 });
4835
4836                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4837                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4838                         short_channel_id: 6,
4839                         timestamp: 2,
4840                         flags: 0,
4841                         cltv_expiry_delta: 0,
4842                         htlc_minimum_msat: 0,
4843                         htlc_maximum_msat: MAX_VALUE_MSAT,
4844                         fee_base_msat: 150_000,
4845                         fee_proportional_millionths: 0,
4846                         excess_data: Vec::new()
4847                 });
4848                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4849                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4850                         short_channel_id: 11,
4851                         timestamp: 2,
4852                         flags: 0,
4853                         cltv_expiry_delta: 0,
4854                         htlc_minimum_msat: 0,
4855                         htlc_maximum_msat: MAX_VALUE_MSAT,
4856                         fee_base_msat: 0,
4857                         fee_proportional_millionths: 0,
4858                         excess_data: Vec::new()
4859                 });
4860
4861                 {
4862                         // Attempt to route more than available results in a failure.
4863                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4864                                         &our_id, &payment_params, &network_graph.read_only(), None, 210_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
4865                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4866                         } else { panic!(); }
4867                 }
4868
4869                 {
4870                         // Now, attempt to route 200 sats (exact amount we can route).
4871                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 200_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4872                         assert_eq!(route.paths.len(), 2);
4873
4874                         let mut total_amount_paid_msat = 0;
4875                         for path in &route.paths {
4876                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[3]);
4877                                 total_amount_paid_msat += path.final_value_msat();
4878                         }
4879                         assert_eq!(total_amount_paid_msat, 200_000);
4880                         assert_eq!(route.get_total_fees(), 150_000);
4881                 }
4882         }
4883
4884         #[test]
4885         fn mpp_with_last_hops() {
4886                 // Previously, if we tried to send an MPP payment to a destination which was only reachable
4887                 // via a single last-hop route hint, we'd fail to route if we first collected routes
4888                 // totaling close but not quite enough to fund the full payment.
4889                 //
4890                 // This was because we considered last-hop hints to have exactly the sought payment amount
4891                 // instead of the amount we were trying to collect, needlessly limiting our path searching
4892                 // at the very first hop.
4893                 //
4894                 // Specifically, this interacted with our "all paths must fund at least 5% of total target"
4895                 // criterion to cause us to refuse all routes at the last hop hint which would be considered
4896                 // to only have the remaining to-collect amount in available liquidity.
4897                 //
4898                 // This bug appeared in production in some specific channel configurations.
4899                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4900                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4901                 let scorer = ln_test_utils::TestScorer::new();
4902                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4903                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4904                 let config = UserConfig::default();
4905                 let payment_params = PaymentParameters::from_node_id(PublicKey::from_slice(&[02; 33]).unwrap(), 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
4906                         .with_route_hints(vec![RouteHint(vec![RouteHintHop {
4907                                 src_node_id: nodes[2],
4908                                 short_channel_id: 42,
4909                                 fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
4910                                 cltv_expiry_delta: 42,
4911                                 htlc_minimum_msat: None,
4912                                 htlc_maximum_msat: None,
4913                         }])]).unwrap().with_max_channel_saturation_power_of_half(0);
4914
4915                 // Keep only two paths from us to nodes[2], both with a 99sat HTLC maximum, with one with
4916                 // no fee and one with a 1msat fee. Previously, trying to route 100 sats to nodes[2] here
4917                 // would first use the no-fee route and then fail to find a path along the second route as
4918                 // we think we can only send up to 1 additional sat over the last-hop but refuse to as its
4919                 // under 5% of our payment amount.
4920                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4921                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4922                         short_channel_id: 1,
4923                         timestamp: 2,
4924                         flags: 0,
4925                         cltv_expiry_delta: (5 << 4) | 5,
4926                         htlc_minimum_msat: 0,
4927                         htlc_maximum_msat: 99_000,
4928                         fee_base_msat: u32::max_value(),
4929                         fee_proportional_millionths: u32::max_value(),
4930                         excess_data: Vec::new()
4931                 });
4932                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4933                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4934                         short_channel_id: 2,
4935                         timestamp: 2,
4936                         flags: 0,
4937                         cltv_expiry_delta: (5 << 4) | 3,
4938                         htlc_minimum_msat: 0,
4939                         htlc_maximum_msat: 99_000,
4940                         fee_base_msat: u32::max_value(),
4941                         fee_proportional_millionths: u32::max_value(),
4942                         excess_data: Vec::new()
4943                 });
4944                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4945                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4946                         short_channel_id: 4,
4947                         timestamp: 2,
4948                         flags: 0,
4949                         cltv_expiry_delta: (4 << 4) | 1,
4950                         htlc_minimum_msat: 0,
4951                         htlc_maximum_msat: MAX_VALUE_MSAT,
4952                         fee_base_msat: 1,
4953                         fee_proportional_millionths: 0,
4954                         excess_data: Vec::new()
4955                 });
4956                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4957                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4958                         short_channel_id: 13,
4959                         timestamp: 2,
4960                         flags: 0|2, // Channel disabled
4961                         cltv_expiry_delta: (13 << 4) | 1,
4962                         htlc_minimum_msat: 0,
4963                         htlc_maximum_msat: MAX_VALUE_MSAT,
4964                         fee_base_msat: 0,
4965                         fee_proportional_millionths: 2000000,
4966                         excess_data: Vec::new()
4967                 });
4968
4969                 // Get a route for 100 sats and check that we found the MPP route no problem and didn't
4970                 // overpay at all.
4971                 let mut route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
4972                 assert_eq!(route.paths.len(), 2);
4973                 route.paths.sort_by_key(|path| path.hops[0].short_channel_id);
4974                 // Paths are manually ordered ordered by SCID, so:
4975                 // * the first is channel 1 (0 fee, but 99 sat maximum) -> channel 3 -> channel 42
4976                 // * the second is channel 2 (1 msat fee) -> channel 4 -> channel 42
4977                 assert_eq!(route.paths[0].hops[0].short_channel_id, 1);
4978                 assert_eq!(route.paths[0].hops[0].fee_msat, 0);
4979                 assert_eq!(route.paths[0].hops[2].fee_msat, 99_000);
4980                 assert_eq!(route.paths[1].hops[0].short_channel_id, 2);
4981                 assert_eq!(route.paths[1].hops[0].fee_msat, 1);
4982                 assert_eq!(route.paths[1].hops[2].fee_msat, 1_000);
4983                 assert_eq!(route.get_total_fees(), 1);
4984                 assert_eq!(route.get_total_amount(), 100_000);
4985         }
4986
4987         #[test]
4988         fn drop_lowest_channel_mpp_route_test() {
4989                 // This test checks that low-capacity channel is dropped when after
4990                 // path finding we realize that we found more capacity than we need.
4991                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
4992                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4993                 let scorer = ln_test_utils::TestScorer::new();
4994                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
4995                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
4996                 let config = UserConfig::default();
4997                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap()
4998                         .with_max_channel_saturation_power_of_half(0);
4999
5000                 // We need a route consisting of 3 paths:
5001                 // From our node to node2 via node0, node7, node1 (three paths one hop each).
5002
5003                 // The first and the second paths should be sufficient, but the third should be
5004                 // cheaper, so that we select it but drop later.
5005
5006                 // First, we set limits on these (previously unlimited) channels.
5007                 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
5008
5009                 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
5010                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5011                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5012                         short_channel_id: 1,
5013                         timestamp: 2,
5014                         flags: 0,
5015                         cltv_expiry_delta: 0,
5016                         htlc_minimum_msat: 0,
5017                         htlc_maximum_msat: 100_000,
5018                         fee_base_msat: 0,
5019                         fee_proportional_millionths: 0,
5020                         excess_data: Vec::new()
5021                 });
5022                 update_channel(&gossip_sync, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
5023                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5024                         short_channel_id: 3,
5025                         timestamp: 2,
5026                         flags: 0,
5027                         cltv_expiry_delta: 0,
5028                         htlc_minimum_msat: 0,
5029                         htlc_maximum_msat: 50_000,
5030                         fee_base_msat: 100,
5031                         fee_proportional_millionths: 0,
5032                         excess_data: Vec::new()
5033                 });
5034
5035                 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
5036                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5037                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5038                         short_channel_id: 12,
5039                         timestamp: 2,
5040                         flags: 0,
5041                         cltv_expiry_delta: 0,
5042                         htlc_minimum_msat: 0,
5043                         htlc_maximum_msat: 60_000,
5044                         fee_base_msat: 100,
5045                         fee_proportional_millionths: 0,
5046                         excess_data: Vec::new()
5047                 });
5048                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5049                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5050                         short_channel_id: 13,
5051                         timestamp: 2,
5052                         flags: 0,
5053                         cltv_expiry_delta: 0,
5054                         htlc_minimum_msat: 0,
5055                         htlc_maximum_msat: 60_000,
5056                         fee_base_msat: 0,
5057                         fee_proportional_millionths: 0,
5058                         excess_data: Vec::new()
5059                 });
5060
5061                 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
5062                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5063                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5064                         short_channel_id: 2,
5065                         timestamp: 2,
5066                         flags: 0,
5067                         cltv_expiry_delta: 0,
5068                         htlc_minimum_msat: 0,
5069                         htlc_maximum_msat: 20_000,
5070                         fee_base_msat: 0,
5071                         fee_proportional_millionths: 0,
5072                         excess_data: Vec::new()
5073                 });
5074                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5075                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5076                         short_channel_id: 4,
5077                         timestamp: 2,
5078                         flags: 0,
5079                         cltv_expiry_delta: 0,
5080                         htlc_minimum_msat: 0,
5081                         htlc_maximum_msat: 20_000,
5082                         fee_base_msat: 0,
5083                         fee_proportional_millionths: 0,
5084                         excess_data: Vec::new()
5085                 });
5086
5087                 {
5088                         // Attempt to route more than available results in a failure.
5089                         if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
5090                                         &our_id, &payment_params, &network_graph.read_only(), None, 150_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5091                                 assert_eq!(err, "Failed to find a sufficient route to the given destination");
5092                         } else { panic!(); }
5093                 }
5094
5095                 {
5096                         // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
5097                         // Our algorithm should provide us with these 3 paths.
5098                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 125_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5099                         assert_eq!(route.paths.len(), 3);
5100                         let mut total_amount_paid_msat = 0;
5101                         for path in &route.paths {
5102                                 assert_eq!(path.hops.len(), 2);
5103                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5104                                 total_amount_paid_msat += path.final_value_msat();
5105                         }
5106                         assert_eq!(total_amount_paid_msat, 125_000);
5107                 }
5108
5109                 {
5110                         // Attempt to route without the last small cheap channel
5111                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5112                         assert_eq!(route.paths.len(), 2);
5113                         let mut total_amount_paid_msat = 0;
5114                         for path in &route.paths {
5115                                 assert_eq!(path.hops.len(), 2);
5116                                 assert_eq!(path.hops.last().unwrap().pubkey, nodes[2]);
5117                                 total_amount_paid_msat += path.final_value_msat();
5118                         }
5119                         assert_eq!(total_amount_paid_msat, 90_000);
5120                 }
5121         }
5122
5123         #[test]
5124         fn min_criteria_consistency() {
5125                 // Test that we don't use an inconsistent metric between updating and walking nodes during
5126                 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
5127                 // was updated with a different criterion from the heap sorting, resulting in loops in
5128                 // calculated paths. We test for that specific case here.
5129
5130                 // We construct a network that looks like this:
5131                 //
5132                 //            node2 -1(3)2- node3
5133                 //              2          2
5134                 //               (2)     (4)
5135                 //                  1   1
5136                 //    node1 -1(5)2- node4 -1(1)2- node6
5137                 //    2
5138                 //   (6)
5139                 //        1
5140                 // our_node
5141                 //
5142                 // We create a loop on the side of our real path - our destination is node 6, with a
5143                 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
5144                 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
5145                 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
5146                 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
5147                 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
5148                 // "previous hop" being set to node 3, creating a loop in the path.
5149                 let secp_ctx = Secp256k1::new();
5150                 let logger = Arc::new(ln_test_utils::TestLogger::new());
5151                 let network = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
5152                 let gossip_sync = P2PGossipSync::new(Arc::clone(&network), None, Arc::clone(&logger));
5153                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5154                 let scorer = ln_test_utils::TestScorer::new();
5155                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5156                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5157                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42);
5158
5159                 add_channel(&gossip_sync, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
5160                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5161                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5162                         short_channel_id: 6,
5163                         timestamp: 1,
5164                         flags: 0,
5165                         cltv_expiry_delta: (6 << 4) | 0,
5166                         htlc_minimum_msat: 0,
5167                         htlc_maximum_msat: MAX_VALUE_MSAT,
5168                         fee_base_msat: 0,
5169                         fee_proportional_millionths: 0,
5170                         excess_data: Vec::new()
5171                 });
5172                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
5173
5174                 add_channel(&gossip_sync, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
5175                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5176                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5177                         short_channel_id: 5,
5178                         timestamp: 1,
5179                         flags: 0,
5180                         cltv_expiry_delta: (5 << 4) | 0,
5181                         htlc_minimum_msat: 0,
5182                         htlc_maximum_msat: MAX_VALUE_MSAT,
5183                         fee_base_msat: 100,
5184                         fee_proportional_millionths: 0,
5185                         excess_data: Vec::new()
5186                 });
5187                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
5188
5189                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
5190                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5191                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5192                         short_channel_id: 4,
5193                         timestamp: 1,
5194                         flags: 0,
5195                         cltv_expiry_delta: (4 << 4) | 0,
5196                         htlc_minimum_msat: 0,
5197                         htlc_maximum_msat: MAX_VALUE_MSAT,
5198                         fee_base_msat: 0,
5199                         fee_proportional_millionths: 0,
5200                         excess_data: Vec::new()
5201                 });
5202                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
5203
5204                 add_channel(&gossip_sync, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
5205                 update_channel(&gossip_sync, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
5206                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5207                         short_channel_id: 3,
5208                         timestamp: 1,
5209                         flags: 0,
5210                         cltv_expiry_delta: (3 << 4) | 0,
5211                         htlc_minimum_msat: 0,
5212                         htlc_maximum_msat: MAX_VALUE_MSAT,
5213                         fee_base_msat: 0,
5214                         fee_proportional_millionths: 0,
5215                         excess_data: Vec::new()
5216                 });
5217                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
5218
5219                 add_channel(&gossip_sync, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
5220                 update_channel(&gossip_sync, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
5221                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5222                         short_channel_id: 2,
5223                         timestamp: 1,
5224                         flags: 0,
5225                         cltv_expiry_delta: (2 << 4) | 0,
5226                         htlc_minimum_msat: 0,
5227                         htlc_maximum_msat: MAX_VALUE_MSAT,
5228                         fee_base_msat: 0,
5229                         fee_proportional_millionths: 0,
5230                         excess_data: Vec::new()
5231                 });
5232
5233                 add_channel(&gossip_sync, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
5234                 update_channel(&gossip_sync, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
5235                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5236                         short_channel_id: 1,
5237                         timestamp: 1,
5238                         flags: 0,
5239                         cltv_expiry_delta: (1 << 4) | 0,
5240                         htlc_minimum_msat: 100,
5241                         htlc_maximum_msat: MAX_VALUE_MSAT,
5242                         fee_base_msat: 0,
5243                         fee_proportional_millionths: 0,
5244                         excess_data: Vec::new()
5245                 });
5246                 add_or_update_node(&gossip_sync, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
5247
5248                 {
5249                         // Now ensure the route flows simply over nodes 1 and 4 to 6.
5250                         let route = get_route(&our_id, &payment_params, &network.read_only(), None, 10_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5251                         assert_eq!(route.paths.len(), 1);
5252                         assert_eq!(route.paths[0].hops.len(), 3);
5253
5254                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[1]);
5255                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5256                         assert_eq!(route.paths[0].hops[0].fee_msat, 100);
5257                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (5 << 4) | 0);
5258                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(1));
5259                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(6));
5260
5261                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[4]);
5262                         assert_eq!(route.paths[0].hops[1].short_channel_id, 5);
5263                         assert_eq!(route.paths[0].hops[1].fee_msat, 0);
5264                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, (1 << 4) | 0);
5265                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(4));
5266                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(5));
5267
5268                         assert_eq!(route.paths[0].hops[2].pubkey, nodes[6]);
5269                         assert_eq!(route.paths[0].hops[2].short_channel_id, 1);
5270                         assert_eq!(route.paths[0].hops[2].fee_msat, 10_000);
5271                         assert_eq!(route.paths[0].hops[2].cltv_expiry_delta, 42);
5272                         assert_eq!(route.paths[0].hops[2].node_features.le_flags(), &id_to_feature_flags(6));
5273                         assert_eq!(route.paths[0].hops[2].channel_features.le_flags(), &id_to_feature_flags(1));
5274                 }
5275         }
5276
5277
5278         #[test]
5279         fn exact_fee_liquidity_limit() {
5280                 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
5281                 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
5282                 // we calculated fees on a higher value, resulting in us ignoring such paths.
5283                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5284                 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
5285                 let scorer = ln_test_utils::TestScorer::new();
5286                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5287                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5288                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42);
5289
5290                 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
5291                 // send.
5292                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5293                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5294                         short_channel_id: 2,
5295                         timestamp: 2,
5296                         flags: 0,
5297                         cltv_expiry_delta: 0,
5298                         htlc_minimum_msat: 0,
5299                         htlc_maximum_msat: 85_000,
5300                         fee_base_msat: 0,
5301                         fee_proportional_millionths: 0,
5302                         excess_data: Vec::new()
5303                 });
5304
5305                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5306                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5307                         short_channel_id: 12,
5308                         timestamp: 2,
5309                         flags: 0,
5310                         cltv_expiry_delta: (4 << 4) | 1,
5311                         htlc_minimum_msat: 0,
5312                         htlc_maximum_msat: 270_000,
5313                         fee_base_msat: 0,
5314                         fee_proportional_millionths: 1000000,
5315                         excess_data: Vec::new()
5316                 });
5317
5318                 {
5319                         // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
5320                         // 200% fee charged channel 13 in the 1-to-2 direction.
5321                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5322                         assert_eq!(route.paths.len(), 1);
5323                         assert_eq!(route.paths[0].hops.len(), 2);
5324
5325                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5326                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5327                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5328                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5329                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5330                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5331
5332                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5333                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5334                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5335                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5336                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), &id_to_feature_flags(3));
5337                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5338                 }
5339         }
5340
5341         #[test]
5342         fn htlc_max_reduction_below_min() {
5343                 // Test that if, while walking the graph, we reduce the value being sent to meet an
5344                 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
5345                 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
5346                 // resulting in us thinking there is no possible path, even if other paths exist.
5347                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5348                 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5349                 let scorer = ln_test_utils::TestScorer::new();
5350                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5351                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5352                 let config = UserConfig::default();
5353                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5354
5355                 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
5356                 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
5357                 // then try to send 90_000.
5358                 update_channel(&gossip_sync, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
5359                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5360                         short_channel_id: 2,
5361                         timestamp: 2,
5362                         flags: 0,
5363                         cltv_expiry_delta: 0,
5364                         htlc_minimum_msat: 0,
5365                         htlc_maximum_msat: 80_000,
5366                         fee_base_msat: 0,
5367                         fee_proportional_millionths: 0,
5368                         excess_data: Vec::new()
5369                 });
5370                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5371                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5372                         short_channel_id: 4,
5373                         timestamp: 2,
5374                         flags: 0,
5375                         cltv_expiry_delta: (4 << 4) | 1,
5376                         htlc_minimum_msat: 90_000,
5377                         htlc_maximum_msat: MAX_VALUE_MSAT,
5378                         fee_base_msat: 0,
5379                         fee_proportional_millionths: 0,
5380                         excess_data: Vec::new()
5381                 });
5382
5383                 {
5384                         // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
5385                         // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
5386                         // expensive) channels 12-13 path.
5387                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 90_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5388                         assert_eq!(route.paths.len(), 1);
5389                         assert_eq!(route.paths[0].hops.len(), 2);
5390
5391                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[7]);
5392                         assert_eq!(route.paths[0].hops[0].short_channel_id, 12);
5393                         assert_eq!(route.paths[0].hops[0].fee_msat, 90_000*2);
5394                         assert_eq!(route.paths[0].hops[0].cltv_expiry_delta, (13 << 4) | 1);
5395                         assert_eq!(route.paths[0].hops[0].node_features.le_flags(), &id_to_feature_flags(8));
5396                         assert_eq!(route.paths[0].hops[0].channel_features.le_flags(), &id_to_feature_flags(12));
5397
5398                         assert_eq!(route.paths[0].hops[1].pubkey, nodes[2]);
5399                         assert_eq!(route.paths[0].hops[1].short_channel_id, 13);
5400                         assert_eq!(route.paths[0].hops[1].fee_msat, 90_000);
5401                         assert_eq!(route.paths[0].hops[1].cltv_expiry_delta, 42);
5402                         assert_eq!(route.paths[0].hops[1].node_features.le_flags(), channelmanager::provided_invoice_features(&config).le_flags());
5403                         assert_eq!(route.paths[0].hops[1].channel_features.le_flags(), &id_to_feature_flags(13));
5404                 }
5405         }
5406
5407         #[test]
5408         fn multiple_direct_first_hops() {
5409                 // Previously we'd only ever considered one first hop path per counterparty.
5410                 // However, as we don't restrict users to one channel per peer, we really need to support
5411                 // looking at all first hop paths.
5412                 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
5413                 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
5414                 // route over multiple channels with the same first hop.
5415                 let secp_ctx = Secp256k1::new();
5416                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5417                 let logger = Arc::new(ln_test_utils::TestLogger::new());
5418                 let network_graph = NetworkGraph::new(Network::Testnet, Arc::clone(&logger));
5419                 let scorer = ln_test_utils::TestScorer::new();
5420                 let config = UserConfig::default();
5421                 let payment_params = PaymentParameters::from_node_id(nodes[0], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5422                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5423                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5424
5425                 {
5426                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5427                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 200_000),
5428                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 10_000),
5429                         ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5430                         assert_eq!(route.paths.len(), 1);
5431                         assert_eq!(route.paths[0].hops.len(), 1);
5432
5433                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5434                         assert_eq!(route.paths[0].hops[0].short_channel_id, 3);
5435                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5436                 }
5437                 {
5438                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5439                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5440                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5441                         ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5442                         assert_eq!(route.paths.len(), 2);
5443                         assert_eq!(route.paths[0].hops.len(), 1);
5444                         assert_eq!(route.paths[1].hops.len(), 1);
5445
5446                         assert!((route.paths[0].hops[0].short_channel_id == 3 && route.paths[1].hops[0].short_channel_id == 2) ||
5447                                 (route.paths[0].hops[0].short_channel_id == 2 && route.paths[1].hops[0].short_channel_id == 3));
5448
5449                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5450                         assert_eq!(route.paths[0].hops[0].fee_msat, 50_000);
5451
5452                         assert_eq!(route.paths[1].hops[0].pubkey, nodes[0]);
5453                         assert_eq!(route.paths[1].hops[0].fee_msat, 50_000);
5454                 }
5455
5456                 {
5457                         // If we have a bunch of outbound channels to the same node, where most are not
5458                         // sufficient to pay the full payment, but one is, we should default to just using the
5459                         // one single channel that has sufficient balance, avoiding MPP.
5460                         //
5461                         // If we have several options above the 3xpayment value threshold, we should pick the
5462                         // smallest of them, avoiding further fragmenting our available outbound balance to
5463                         // this node.
5464                         let route = get_route(&our_id, &payment_params, &network_graph.read_only(), Some(&[
5465                                 &get_channel_details(Some(2), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5466                                 &get_channel_details(Some(3), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5467                                 &get_channel_details(Some(5), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5468                                 &get_channel_details(Some(6), nodes[0], channelmanager::provided_init_features(&config), 300_000),
5469                                 &get_channel_details(Some(7), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5470                                 &get_channel_details(Some(8), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5471                                 &get_channel_details(Some(9), nodes[0], channelmanager::provided_init_features(&config), 50_000),
5472                                 &get_channel_details(Some(4), nodes[0], channelmanager::provided_init_features(&config), 1_000_000),
5473                         ]), 100_000, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5474                         assert_eq!(route.paths.len(), 1);
5475                         assert_eq!(route.paths[0].hops.len(), 1);
5476
5477                         assert_eq!(route.paths[0].hops[0].pubkey, nodes[0]);
5478                         assert_eq!(route.paths[0].hops[0].short_channel_id, 6);
5479                         assert_eq!(route.paths[0].hops[0].fee_msat, 100_000);
5480                 }
5481         }
5482
5483         #[test]
5484         fn prefers_shorter_route_with_higher_fees() {
5485                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5486                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5487                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5488
5489                 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
5490                 let scorer = ln_test_utils::TestScorer::new();
5491                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5492                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5493                 let route = get_route(
5494                         &our_id, &payment_params, &network_graph.read_only(), None, 100,
5495                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5496                 ).unwrap();
5497                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5498
5499                 assert_eq!(route.get_total_fees(), 100);
5500                 assert_eq!(route.get_total_amount(), 100);
5501                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5502
5503                 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
5504                 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
5505                 let scorer = FixedPenaltyScorer::with_penalty(100);
5506                 let route = get_route(
5507                         &our_id, &payment_params, &network_graph.read_only(), None, 100,
5508                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5509                 ).unwrap();
5510                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5511
5512                 assert_eq!(route.get_total_fees(), 300);
5513                 assert_eq!(route.get_total_amount(), 100);
5514                 assert_eq!(path, vec![2, 4, 7, 10]);
5515         }
5516
5517         struct BadChannelScorer {
5518                 short_channel_id: u64,
5519         }
5520
5521         #[cfg(c_bindings)]
5522         impl Writeable for BadChannelScorer {
5523                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5524         }
5525         impl Score for BadChannelScorer {
5526                 type ScoreParams = ();
5527                 fn channel_penalty_msat(&self, short_channel_id: u64, _: &NodeId, _: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5528                         if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
5529                 }
5530
5531                 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5532                 fn payment_path_successful(&mut self, _path: &Path) {}
5533                 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5534                 fn probe_successful(&mut self, _path: &Path) {}
5535         }
5536
5537         struct BadNodeScorer {
5538                 node_id: NodeId,
5539         }
5540
5541         #[cfg(c_bindings)]
5542         impl Writeable for BadNodeScorer {
5543                 fn write<W: Writer>(&self, _w: &mut W) -> Result<(), crate::io::Error> { unimplemented!() }
5544         }
5545
5546         impl Score for BadNodeScorer {
5547                 type ScoreParams = ();
5548                 fn channel_penalty_msat(&self, _: u64, _: &NodeId, target: &NodeId, _: ChannelUsage, _score_params:&Self::ScoreParams) -> u64 {
5549                         if *target == self.node_id { u64::max_value() } else { 0 }
5550                 }
5551
5552                 fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5553                 fn payment_path_successful(&mut self, _path: &Path) {}
5554                 fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64) {}
5555                 fn probe_successful(&mut self, _path: &Path) {}
5556         }
5557
5558         #[test]
5559         fn avoids_routing_through_bad_channels_and_nodes() {
5560                 let (secp_ctx, network, _, _, logger) = build_graph();
5561                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5562                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5563                 let network_graph = network.read_only();
5564
5565                 // A path to nodes[6] exists when no penalties are applied to any channel.
5566                 let scorer = ln_test_utils::TestScorer::new();
5567                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5568                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5569                 let route = get_route(
5570                         &our_id, &payment_params, &network_graph, None, 100,
5571                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5572                 ).unwrap();
5573                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5574
5575                 assert_eq!(route.get_total_fees(), 100);
5576                 assert_eq!(route.get_total_amount(), 100);
5577                 assert_eq!(path, vec![2, 4, 6, 11, 8]);
5578
5579                 // A different path to nodes[6] exists if channel 6 cannot be routed over.
5580                 let scorer = BadChannelScorer { short_channel_id: 6 };
5581                 let route = get_route(
5582                         &our_id, &payment_params, &network_graph, None, 100,
5583                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5584                 ).unwrap();
5585                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5586
5587                 assert_eq!(route.get_total_fees(), 300);
5588                 assert_eq!(route.get_total_amount(), 100);
5589                 assert_eq!(path, vec![2, 4, 7, 10]);
5590
5591                 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
5592                 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
5593                 match get_route(
5594                         &our_id, &payment_params, &network_graph, None, 100,
5595                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes
5596                 ) {
5597                         Err(LightningError { err, .. } ) => {
5598                                 assert_eq!(err, "Failed to find a path to the given destination");
5599                         },
5600                         Ok(_) => panic!("Expected error"),
5601                 }
5602         }
5603
5604         #[test]
5605         fn total_fees_single_path() {
5606                 let route = Route {
5607                         paths: vec![Path { hops: vec![
5608                                 RouteHop {
5609                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5610                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5611                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5612                                 },
5613                                 RouteHop {
5614                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5615                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5616                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5617                                 },
5618                                 RouteHop {
5619                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
5620                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5621                                         short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
5622                                 },
5623                         ], blinded_tail: None }],
5624                         payment_params: None,
5625                 };
5626
5627                 assert_eq!(route.get_total_fees(), 250);
5628                 assert_eq!(route.get_total_amount(), 225);
5629         }
5630
5631         #[test]
5632         fn total_fees_multi_path() {
5633                 let route = Route {
5634                         paths: vec![Path { hops: vec![
5635                                 RouteHop {
5636                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5637                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5638                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5639                                 },
5640                                 RouteHop {
5641                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5642                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5643                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5644                                 },
5645                         ], blinded_tail: None }, Path { hops: vec![
5646                                 RouteHop {
5647                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
5648                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5649                                         short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
5650                                 },
5651                                 RouteHop {
5652                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
5653                                         channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
5654                                         short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
5655                                 },
5656                         ], blinded_tail: None }],
5657                         payment_params: None,
5658                 };
5659
5660                 assert_eq!(route.get_total_fees(), 200);
5661                 assert_eq!(route.get_total_amount(), 300);
5662         }
5663
5664         #[test]
5665         fn total_empty_route_no_panic() {
5666                 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
5667                 // would both panic if the route was completely empty. We test to ensure they return 0
5668                 // here, even though its somewhat nonsensical as a route.
5669                 let route = Route { paths: Vec::new(), payment_params: None };
5670
5671                 assert_eq!(route.get_total_fees(), 0);
5672                 assert_eq!(route.get_total_amount(), 0);
5673         }
5674
5675         #[test]
5676         fn limits_total_cltv_delta() {
5677                 let (secp_ctx, network, _, _, logger) = build_graph();
5678                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5679                 let network_graph = network.read_only();
5680
5681                 let scorer = ln_test_utils::TestScorer::new();
5682
5683                 // Make sure that generally there is at least one route available
5684                 let feasible_max_total_cltv_delta = 1008;
5685                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5686                         .with_max_total_cltv_expiry_delta(feasible_max_total_cltv_delta);
5687                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5688                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5689                 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5690                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5691                 assert_ne!(path.len(), 0);
5692
5693                 // But not if we exclude all paths on the basis of their accumulated CLTV delta
5694                 let fail_max_total_cltv_delta = 23;
5695                 let fail_payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5696                         .with_max_total_cltv_expiry_delta(fail_max_total_cltv_delta);
5697                 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5698                 {
5699                         Err(LightningError { err, .. } ) => {
5700                                 assert_eq!(err, "Failed to find a path to the given destination");
5701                         },
5702                         Ok(_) => panic!("Expected error"),
5703                 }
5704         }
5705
5706         #[test]
5707         fn avoids_recently_failed_paths() {
5708                 // Ensure that the router always avoids all of the `previously_failed_channels` channels by
5709                 // randomly inserting channels into it until we can't find a route anymore.
5710                 let (secp_ctx, network, _, _, logger) = build_graph();
5711                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5712                 let network_graph = network.read_only();
5713
5714                 let scorer = ln_test_utils::TestScorer::new();
5715                 let mut payment_params = PaymentParameters::from_node_id(nodes[6], 0).with_route_hints(last_hops(&nodes)).unwrap()
5716                         .with_max_path_count(1);
5717                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5718                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5719
5720                 // We should be able to find a route initially, and then after we fail a few random
5721                 // channels eventually we won't be able to any longer.
5722                 assert!(get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).is_ok());
5723                 loop {
5724                         if let Ok(route) = get_route(&our_id, &payment_params, &network_graph, None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes) {
5725                                 for chan in route.paths[0].hops.iter() {
5726                                         assert!(!payment_params.previously_failed_channels.contains(&chan.short_channel_id));
5727                                 }
5728                                 let victim = (u64::from_ne_bytes(random_seed_bytes[0..8].try_into().unwrap()) as usize)
5729                                         % route.paths[0].hops.len();
5730                                 payment_params.previously_failed_channels.push(route.paths[0].hops[victim].short_channel_id);
5731                         } else { break; }
5732                 }
5733         }
5734
5735         #[test]
5736         fn limits_path_length() {
5737                 let (secp_ctx, network, _, _, logger) = build_line_graph();
5738                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5739                 let network_graph = network.read_only();
5740
5741                 let scorer = ln_test_utils::TestScorer::new();
5742                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5743                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5744
5745                 // First check we can actually create a long route on this graph.
5746                 let feasible_payment_params = PaymentParameters::from_node_id(nodes[18], 0);
5747                 let route = get_route(&our_id, &feasible_payment_params, &network_graph, None, 100,
5748                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5749                 let path = route.paths[0].hops.iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
5750                 assert!(path.len() == MAX_PATH_LENGTH_ESTIMATE.into());
5751
5752                 // But we can't create a path surpassing the MAX_PATH_LENGTH_ESTIMATE limit.
5753                 let fail_payment_params = PaymentParameters::from_node_id(nodes[19], 0);
5754                 match get_route(&our_id, &fail_payment_params, &network_graph, None, 100,
5755                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes)
5756                 {
5757                         Err(LightningError { err, .. } ) => {
5758                                 assert_eq!(err, "Failed to find a path to the given destination");
5759                         },
5760                         Ok(_) => panic!("Expected error"),
5761                 }
5762         }
5763
5764         #[test]
5765         fn adds_and_limits_cltv_offset() {
5766                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
5767                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5768
5769                 let scorer = ln_test_utils::TestScorer::new();
5770
5771                 let payment_params = PaymentParameters::from_node_id(nodes[6], 42).with_route_hints(last_hops(&nodes)).unwrap();
5772                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5773                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5774                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5775                 assert_eq!(route.paths.len(), 1);
5776
5777                 let cltv_expiry_deltas_before = route.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5778
5779                 // Check whether the offset added to the last hop by default is in [1 .. DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA]
5780                 let mut route_default = route.clone();
5781                 add_random_cltv_offset(&mut route_default, &payment_params, &network_graph.read_only(), &random_seed_bytes);
5782                 let cltv_expiry_deltas_default = route_default.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5783                 assert_eq!(cltv_expiry_deltas_before.split_last().unwrap().1, cltv_expiry_deltas_default.split_last().unwrap().1);
5784                 assert!(cltv_expiry_deltas_default.last() > cltv_expiry_deltas_before.last());
5785                 assert!(cltv_expiry_deltas_default.last().unwrap() <= &DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA);
5786
5787                 // Check that no offset is added when we restrict the max_total_cltv_expiry_delta
5788                 let mut route_limited = route.clone();
5789                 let limited_max_total_cltv_expiry_delta = cltv_expiry_deltas_before.iter().sum();
5790                 let limited_payment_params = payment_params.with_max_total_cltv_expiry_delta(limited_max_total_cltv_expiry_delta);
5791                 add_random_cltv_offset(&mut route_limited, &limited_payment_params, &network_graph.read_only(), &random_seed_bytes);
5792                 let cltv_expiry_deltas_limited = route_limited.paths[0].hops.iter().map(|h| h.cltv_expiry_delta).collect::<Vec<u32>>();
5793                 assert_eq!(cltv_expiry_deltas_before, cltv_expiry_deltas_limited);
5794         }
5795
5796         #[test]
5797         fn adds_plausible_cltv_offset() {
5798                 let (secp_ctx, network, _, _, logger) = build_graph();
5799                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5800                 let network_graph = network.read_only();
5801                 let network_nodes = network_graph.nodes();
5802                 let network_channels = network_graph.channels();
5803                 let scorer = ln_test_utils::TestScorer::new();
5804                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5805                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[4u8; 32], Network::Testnet);
5806                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5807
5808                 let mut route = get_route(&our_id, &payment_params, &network_graph, None, 100,
5809                                                                   Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
5810                 add_random_cltv_offset(&mut route, &payment_params, &network_graph, &random_seed_bytes);
5811
5812                 let mut path_plausibility = vec![];
5813
5814                 for p in route.paths {
5815                         // 1. Select random observation point
5816                         let mut prng = ChaCha20::new(&random_seed_bytes, &[0u8; 12]);
5817                         let mut random_bytes = [0u8; ::core::mem::size_of::<usize>()];
5818
5819                         prng.process_in_place(&mut random_bytes);
5820                         let random_path_index = usize::from_be_bytes(random_bytes).wrapping_rem(p.hops.len());
5821                         let observation_point = NodeId::from_pubkey(&p.hops.get(random_path_index).unwrap().pubkey);
5822
5823                         // 2. Calculate what CLTV expiry delta we would observe there
5824                         let observed_cltv_expiry_delta: u32 = p.hops[random_path_index..].iter().map(|h| h.cltv_expiry_delta).sum();
5825
5826                         // 3. Starting from the observation point, find candidate paths
5827                         let mut candidates: VecDeque<(NodeId, Vec<u32>)> = VecDeque::new();
5828                         candidates.push_back((observation_point, vec![]));
5829
5830                         let mut found_plausible_candidate = false;
5831
5832                         'candidate_loop: while let Some((cur_node_id, cur_path_cltv_deltas)) = candidates.pop_front() {
5833                                 if let Some(remaining) = observed_cltv_expiry_delta.checked_sub(cur_path_cltv_deltas.iter().sum::<u32>()) {
5834                                         if remaining == 0 || remaining.wrapping_rem(40) == 0 || remaining.wrapping_rem(144) == 0 {
5835                                                 found_plausible_candidate = true;
5836                                                 break 'candidate_loop;
5837                                         }
5838                                 }
5839
5840                                 if let Some(cur_node) = network_nodes.get(&cur_node_id) {
5841                                         for channel_id in &cur_node.channels {
5842                                                 if let Some(channel_info) = network_channels.get(&channel_id) {
5843                                                         if let Some((dir_info, next_id)) = channel_info.as_directed_from(&cur_node_id) {
5844                                                                 let next_cltv_expiry_delta = dir_info.direction().cltv_expiry_delta as u32;
5845                                                                 if cur_path_cltv_deltas.iter().sum::<u32>()
5846                                                                         .saturating_add(next_cltv_expiry_delta) <= observed_cltv_expiry_delta {
5847                                                                         let mut new_path_cltv_deltas = cur_path_cltv_deltas.clone();
5848                                                                         new_path_cltv_deltas.push(next_cltv_expiry_delta);
5849                                                                         candidates.push_back((*next_id, new_path_cltv_deltas));
5850                                                                 }
5851                                                         }
5852                                                 }
5853                                         }
5854                                 }
5855                         }
5856
5857                         path_plausibility.push(found_plausible_candidate);
5858                 }
5859                 assert!(path_plausibility.iter().all(|x| *x));
5860         }
5861
5862         #[test]
5863         fn builds_correct_path_from_hops() {
5864                 let (secp_ctx, network, _, _, logger) = build_graph();
5865                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
5866                 let network_graph = network.read_only();
5867
5868                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5869                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5870
5871                 let payment_params = PaymentParameters::from_node_id(nodes[3], 0);
5872                 let hops = [nodes[1], nodes[2], nodes[4], nodes[3]];
5873                 let route = build_route_from_hops_internal(&our_id, &hops, &payment_params,
5874                          &network_graph, 100, Arc::clone(&logger), &random_seed_bytes).unwrap();
5875                 let route_hop_pubkeys = route.paths[0].hops.iter().map(|hop| hop.pubkey).collect::<Vec<_>>();
5876                 assert_eq!(hops.len(), route.paths[0].hops.len());
5877                 for (idx, hop_pubkey) in hops.iter().enumerate() {
5878                         assert!(*hop_pubkey == route_hop_pubkeys[idx]);
5879                 }
5880         }
5881
5882         #[test]
5883         fn avoids_saturating_channels() {
5884                 let (secp_ctx, network_graph, gossip_sync, _, logger) = build_graph();
5885                 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
5886                 let decay_params = ProbabilisticScoringDecayParameters::default();
5887                 let scorer = ProbabilisticScorer::new(decay_params, &*network_graph, Arc::clone(&logger));
5888
5889                 // Set the fee on channel 13 to 100% to match channel 4 giving us two equivalent paths (us
5890                 // -> node 7 -> node2 and us -> node 1 -> node 2) which we should balance over.
5891                 update_channel(&gossip_sync, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
5892                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5893                         short_channel_id: 4,
5894                         timestamp: 2,
5895                         flags: 0,
5896                         cltv_expiry_delta: (4 << 4) | 1,
5897                         htlc_minimum_msat: 0,
5898                         htlc_maximum_msat: 250_000_000,
5899                         fee_base_msat: 0,
5900                         fee_proportional_millionths: 0,
5901                         excess_data: Vec::new()
5902                 });
5903                 update_channel(&gossip_sync, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
5904                         chain_hash: genesis_block(Network::Testnet).header.block_hash(),
5905                         short_channel_id: 13,
5906                         timestamp: 2,
5907                         flags: 0,
5908                         cltv_expiry_delta: (13 << 4) | 1,
5909                         htlc_minimum_msat: 0,
5910                         htlc_maximum_msat: 250_000_000,
5911                         fee_base_msat: 0,
5912                         fee_proportional_millionths: 0,
5913                         excess_data: Vec::new()
5914                 });
5915
5916                 let config = UserConfig::default();
5917                 let payment_params = PaymentParameters::from_node_id(nodes[2], 42).with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
5918                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
5919                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
5920                 // 100,000 sats is less than the available liquidity on each channel, set above.
5921                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100_000_000, Arc::clone(&logger), &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes).unwrap();
5922                 assert_eq!(route.paths.len(), 2);
5923                 assert!((route.paths[0].hops[1].short_channel_id == 4 && route.paths[1].hops[1].short_channel_id == 13) ||
5924                         (route.paths[1].hops[1].short_channel_id == 4 && route.paths[0].hops[1].short_channel_id == 13));
5925         }
5926
5927         #[cfg(not(feature = "no-std"))]
5928         pub(super) fn random_init_seed() -> u64 {
5929                 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
5930                 use core::hash::{BuildHasher, Hasher};
5931                 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
5932                 println!("Using seed of {}", seed);
5933                 seed
5934         }
5935
5936         #[test]
5937         #[cfg(not(feature = "no-std"))]
5938         fn generate_routes() {
5939                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
5940
5941                 let logger = ln_test_utils::TestLogger::new();
5942                 let graph = match super::bench_utils::read_network_graph(&logger) {
5943                         Ok(f) => f,
5944                         Err(e) => {
5945                                 eprintln!("{}", e);
5946                                 return;
5947                         },
5948                 };
5949
5950                 let params = ProbabilisticScoringFeeParameters::default();
5951                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
5952                 let features = super::InvoiceFeatures::empty();
5953
5954                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
5955         }
5956
5957         #[test]
5958         #[cfg(not(feature = "no-std"))]
5959         fn generate_routes_mpp() {
5960                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
5961
5962                 let logger = ln_test_utils::TestLogger::new();
5963                 let graph = match super::bench_utils::read_network_graph(&logger) {
5964                         Ok(f) => f,
5965                         Err(e) => {
5966                                 eprintln!("{}", e);
5967                                 return;
5968                         },
5969                 };
5970
5971                 let params = ProbabilisticScoringFeeParameters::default();
5972                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
5973                 let features = channelmanager::provided_invoice_features(&UserConfig::default());
5974
5975                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 0, 2);
5976         }
5977
5978         #[test]
5979         #[cfg(not(feature = "no-std"))]
5980         fn generate_large_mpp_routes() {
5981                 use crate::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters};
5982
5983                 let logger = ln_test_utils::TestLogger::new();
5984                 let graph = match super::bench_utils::read_network_graph(&logger) {
5985                         Ok(f) => f,
5986                         Err(e) => {
5987                                 eprintln!("{}", e);
5988                                 return;
5989                         },
5990                 };
5991
5992                 let params = ProbabilisticScoringFeeParameters::default();
5993                 let mut scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &graph, &logger);
5994                 let features = channelmanager::provided_invoice_features(&UserConfig::default());
5995
5996                 super::bench_utils::generate_test_routes(&graph, &mut scorer, &params, features, random_init_seed(), 1_000_000, 2);
5997         }
5998
5999         #[test]
6000         fn honors_manual_penalties() {
6001                 let (secp_ctx, network_graph, _, _, logger) = build_line_graph();
6002                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6003
6004                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6005                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6006
6007                 let mut scorer_params = ProbabilisticScoringFeeParameters::default();
6008                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), Arc::clone(&network_graph), Arc::clone(&logger));
6009
6010                 // First check set manual penalties are returned by the scorer.
6011                 let usage = ChannelUsage {
6012                         amount_msat: 0,
6013                         inflight_htlc_msat: 0,
6014                         effective_capacity: EffectiveCapacity::Total { capacity_msat: 1_024_000, htlc_maximum_msat: 1_000 },
6015                 };
6016                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[3]), 123);
6017                 scorer_params.set_manual_penalty(&NodeId::from_pubkey(&nodes[4]), 456);
6018                 assert_eq!(scorer.channel_penalty_msat(42, &NodeId::from_pubkey(&nodes[3]), &NodeId::from_pubkey(&nodes[4]), usage, &scorer_params), 456);
6019
6020                 // Then check we can get a normal route
6021                 let payment_params = PaymentParameters::from_node_id(nodes[10], 42);
6022                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6023                 assert!(route.is_ok());
6024
6025                 // Then check that we can't get a route if we ban an intermediate node.
6026                 scorer_params.add_banned(&NodeId::from_pubkey(&nodes[3]));
6027                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6028                 assert!(route.is_err());
6029
6030                 // Finally make sure we can route again, when we remove the ban.
6031                 scorer_params.remove_banned(&NodeId::from_pubkey(&nodes[3]));
6032                 let route = get_route(&our_id, &payment_params, &network_graph.read_only(), None, 100, Arc::clone(&logger), &scorer, &scorer_params,&random_seed_bytes);
6033                 assert!(route.is_ok());
6034         }
6035
6036         #[test]
6037         fn abide_by_route_hint_max_htlc() {
6038                 // Check that we abide by any htlc_maximum_msat provided in the route hints of the payment
6039                 // params in the final route.
6040                 let (secp_ctx, network_graph, _, _, logger) = build_graph();
6041                 let netgraph = network_graph.read_only();
6042                 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
6043                 let scorer = ln_test_utils::TestScorer::new();
6044                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6045                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6046                 let config = UserConfig::default();
6047
6048                 let max_htlc_msat = 50_000;
6049                 let route_hint_1 = RouteHint(vec![RouteHintHop {
6050                         src_node_id: nodes[2],
6051                         short_channel_id: 42,
6052                         fees: RoutingFees {
6053                                 base_msat: 100,
6054                                 proportional_millionths: 0,
6055                         },
6056                         cltv_expiry_delta: 10,
6057                         htlc_minimum_msat: None,
6058                         htlc_maximum_msat: Some(max_htlc_msat),
6059                 }]);
6060                 let dest_node_id = ln_test_utils::pubkey(42);
6061                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6062                         .with_route_hints(vec![route_hint_1.clone()]).unwrap()
6063                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6064
6065                 // Make sure we'll error if our route hints don't have enough liquidity according to their
6066                 // htlc_maximum_msat.
6067                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id,
6068                         &payment_params, &netgraph, None, max_htlc_msat + 1, Arc::clone(&logger), &scorer, &(),
6069                         &random_seed_bytes)
6070                 {
6071                         assert_eq!(err, "Failed to find a sufficient route to the given destination");
6072                 } else { panic!(); }
6073
6074                 // Make sure we'll split an MPP payment across route hints if their htlc_maximum_msat warrants.
6075                 let mut route_hint_2 = route_hint_1.clone();
6076                 route_hint_2.0[0].short_channel_id = 43;
6077                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6078                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6079                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6080                 let route = get_route(&our_id, &payment_params, &netgraph, None, max_htlc_msat + 1,
6081                         Arc::clone(&logger), &scorer, &(), &random_seed_bytes).unwrap();
6082                 assert_eq!(route.paths.len(), 2);
6083                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6084                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6085         }
6086
6087         #[test]
6088         fn direct_channel_to_hints_with_max_htlc() {
6089                 // Check that if we have a first hop channel peer that's connected to multiple provided route
6090                 // hints, that we properly split the payment between the route hints if needed.
6091                 let logger = Arc::new(ln_test_utils::TestLogger::new());
6092                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, Arc::clone(&logger)));
6093                 let scorer = ln_test_utils::TestScorer::new();
6094                 let keys_manager = ln_test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
6095                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6096                 let config = UserConfig::default();
6097
6098                 let our_node_id = ln_test_utils::pubkey(42);
6099                 let intermed_node_id = ln_test_utils::pubkey(43);
6100                 let first_hop = vec![get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), 10_000_000)];
6101
6102                 let amt_msat = 900_000;
6103                 let max_htlc_msat = 500_000;
6104                 let route_hint_1 = RouteHint(vec![RouteHintHop {
6105                         src_node_id: intermed_node_id,
6106                         short_channel_id: 44,
6107                         fees: RoutingFees {
6108                                 base_msat: 100,
6109                                 proportional_millionths: 0,
6110                         },
6111                         cltv_expiry_delta: 10,
6112                         htlc_minimum_msat: None,
6113                         htlc_maximum_msat: Some(max_htlc_msat),
6114                 }, RouteHintHop {
6115                         src_node_id: intermed_node_id,
6116                         short_channel_id: 45,
6117                         fees: RoutingFees {
6118                                 base_msat: 100,
6119                                 proportional_millionths: 0,
6120                         },
6121                         cltv_expiry_delta: 10,
6122                         htlc_minimum_msat: None,
6123                         // Check that later route hint max htlcs don't override earlier ones
6124                         htlc_maximum_msat: Some(max_htlc_msat - 50),
6125                 }]);
6126                 let mut route_hint_2 = route_hint_1.clone();
6127                 route_hint_2.0[0].short_channel_id = 46;
6128                 route_hint_2.0[1].short_channel_id = 47;
6129                 let dest_node_id = ln_test_utils::pubkey(44);
6130                 let payment_params = PaymentParameters::from_node_id(dest_node_id, 42)
6131                         .with_route_hints(vec![route_hint_1, route_hint_2]).unwrap()
6132                         .with_bolt11_features(channelmanager::provided_invoice_features(&config)).unwrap();
6133
6134                 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6135                         Some(&first_hop.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6136                         &random_seed_bytes).unwrap();
6137                 assert_eq!(route.paths.len(), 2);
6138                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6139                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6140                 assert_eq!(route.get_total_amount(), amt_msat);
6141
6142                 // Re-run but with two first hop channels connected to the same route hint peers that must be
6143                 // split between.
6144                 let first_hops = vec![
6145                         get_channel_details(Some(42), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6146                         get_channel_details(Some(43), intermed_node_id, InitFeatures::from_le_bytes(vec![0b11]), amt_msat - 10),
6147                 ];
6148                 let route = get_route(&our_node_id, &payment_params, &network_graph.read_only(),
6149                         Some(&first_hops.iter().collect::<Vec<_>>()), amt_msat, Arc::clone(&logger), &scorer, &(),
6150                         &random_seed_bytes).unwrap();
6151                 assert_eq!(route.paths.len(), 2);
6152                 assert!(route.paths[0].hops.last().unwrap().fee_msat <= max_htlc_msat);
6153                 assert!(route.paths[1].hops.last().unwrap().fee_msat <= max_htlc_msat);
6154                 assert_eq!(route.get_total_amount(), amt_msat);
6155         }
6156
6157         #[test]
6158         fn blinded_route_ser() {
6159                 let blinded_path_1 = BlindedPath {
6160                         introduction_node_id: ln_test_utils::pubkey(42),
6161                         blinding_point: ln_test_utils::pubkey(43),
6162                         blinded_hops: vec![
6163                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(44), encrypted_payload: Vec::new() },
6164                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() }
6165                         ],
6166                 };
6167                 let blinded_path_2 = BlindedPath {
6168                         introduction_node_id: ln_test_utils::pubkey(46),
6169                         blinding_point: ln_test_utils::pubkey(47),
6170                         blinded_hops: vec![
6171                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(48), encrypted_payload: Vec::new() },
6172                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }
6173                         ],
6174                 };
6175                 // (De)serialize a Route with 1 blinded path out of two total paths.
6176                 let mut route = Route { paths: vec![Path {
6177                         hops: vec![RouteHop {
6178                                 pubkey: ln_test_utils::pubkey(50),
6179                                 node_features: NodeFeatures::empty(),
6180                                 short_channel_id: 42,
6181                                 channel_features: ChannelFeatures::empty(),
6182                                 fee_msat: 100,
6183                                 cltv_expiry_delta: 0,
6184                         }],
6185                         blinded_tail: Some(BlindedTail {
6186                                 hops: blinded_path_1.blinded_hops,
6187                                 blinding_point: blinded_path_1.blinding_point,
6188                                 excess_final_cltv_expiry_delta: 40,
6189                                 final_value_msat: 100,
6190                         })}, Path {
6191                         hops: vec![RouteHop {
6192                                 pubkey: ln_test_utils::pubkey(51),
6193                                 node_features: NodeFeatures::empty(),
6194                                 short_channel_id: 43,
6195                                 channel_features: ChannelFeatures::empty(),
6196                                 fee_msat: 100,
6197                                 cltv_expiry_delta: 0,
6198                         }], blinded_tail: None }],
6199                         payment_params: None,
6200                 };
6201                 let encoded_route = route.encode();
6202                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6203                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6204                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6205
6206                 // (De)serialize a Route with two paths, each containing a blinded tail.
6207                 route.paths[1].blinded_tail = Some(BlindedTail {
6208                         hops: blinded_path_2.blinded_hops,
6209                         blinding_point: blinded_path_2.blinding_point,
6210                         excess_final_cltv_expiry_delta: 41,
6211                         final_value_msat: 101,
6212                 });
6213                 let encoded_route = route.encode();
6214                 let decoded_route: Route = Readable::read(&mut Cursor::new(&encoded_route[..])).unwrap();
6215                 assert_eq!(decoded_route.paths[0].blinded_tail, route.paths[0].blinded_tail);
6216                 assert_eq!(decoded_route.paths[1].blinded_tail, route.paths[1].blinded_tail);
6217         }
6218
6219         #[test]
6220         fn blinded_path_inflight_processing() {
6221                 // Ensure we'll score the channel that's inbound to a blinded path's introduction node, and
6222                 // account for the blinded tail's final amount_msat.
6223                 let mut inflight_htlcs = InFlightHtlcs::new();
6224                 let blinded_path = BlindedPath {
6225                         introduction_node_id: ln_test_utils::pubkey(43),
6226                         blinding_point: ln_test_utils::pubkey(48),
6227                         blinded_hops: vec![BlindedHop { blinded_node_id: ln_test_utils::pubkey(49), encrypted_payload: Vec::new() }],
6228                 };
6229                 let path = Path {
6230                         hops: vec![RouteHop {
6231                                 pubkey: ln_test_utils::pubkey(42),
6232                                 node_features: NodeFeatures::empty(),
6233                                 short_channel_id: 42,
6234                                 channel_features: ChannelFeatures::empty(),
6235                                 fee_msat: 100,
6236                                 cltv_expiry_delta: 0,
6237                         },
6238                         RouteHop {
6239                                 pubkey: blinded_path.introduction_node_id,
6240                                 node_features: NodeFeatures::empty(),
6241                                 short_channel_id: 43,
6242                                 channel_features: ChannelFeatures::empty(),
6243                                 fee_msat: 1,
6244                                 cltv_expiry_delta: 0,
6245                         }],
6246                         blinded_tail: Some(BlindedTail {
6247                                 hops: blinded_path.blinded_hops,
6248                                 blinding_point: blinded_path.blinding_point,
6249                                 excess_final_cltv_expiry_delta: 0,
6250                                 final_value_msat: 200,
6251                         }),
6252                 };
6253                 inflight_htlcs.process_path(&path, ln_test_utils::pubkey(44));
6254                 assert_eq!(*inflight_htlcs.0.get(&(42, true)).unwrap(), 301);
6255                 assert_eq!(*inflight_htlcs.0.get(&(43, false)).unwrap(), 201);
6256         }
6257
6258         #[test]
6259         fn blinded_path_cltv_shadow_offset() {
6260                 // Make sure we add a shadow offset when sending to blinded paths.
6261                 let blinded_path = BlindedPath {
6262                         introduction_node_id: ln_test_utils::pubkey(43),
6263                         blinding_point: ln_test_utils::pubkey(44),
6264                         blinded_hops: vec![
6265                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(45), encrypted_payload: Vec::new() },
6266                                 BlindedHop { blinded_node_id: ln_test_utils::pubkey(46), encrypted_payload: Vec::new() }
6267                         ],
6268                 };
6269                 let mut route = Route { paths: vec![Path {
6270                         hops: vec![RouteHop {
6271                                 pubkey: ln_test_utils::pubkey(42),
6272                                 node_features: NodeFeatures::empty(),
6273                                 short_channel_id: 42,
6274                                 channel_features: ChannelFeatures::empty(),
6275                                 fee_msat: 100,
6276                                 cltv_expiry_delta: 0,
6277                         },
6278                         RouteHop {
6279                                 pubkey: blinded_path.introduction_node_id,
6280                                 node_features: NodeFeatures::empty(),
6281                                 short_channel_id: 43,
6282                                 channel_features: ChannelFeatures::empty(),
6283                                 fee_msat: 1,
6284                                 cltv_expiry_delta: 0,
6285                         }
6286                         ],
6287                         blinded_tail: Some(BlindedTail {
6288                                 hops: blinded_path.blinded_hops,
6289                                 blinding_point: blinded_path.blinding_point,
6290                                 excess_final_cltv_expiry_delta: 0,
6291                                 final_value_msat: 200,
6292                         }),
6293                 }], payment_params: None};
6294
6295                 let payment_params = PaymentParameters::from_node_id(ln_test_utils::pubkey(47), 18);
6296                 let (_, network_graph, _, _, _) = build_line_graph();
6297                 add_random_cltv_offset(&mut route, &payment_params, &network_graph.read_only(), &[0; 32]);
6298                 assert_eq!(route.paths[0].blinded_tail.as_ref().unwrap().excess_final_cltv_expiry_delta, 40);
6299                 assert_eq!(route.paths[0].hops.last().unwrap().cltv_expiry_delta, 40);
6300         }
6301 }
6302
6303 #[cfg(all(any(test, ldk_bench), not(feature = "no-std")))]
6304 pub(crate) mod bench_utils {
6305         use super::*;
6306         use std::fs::File;
6307
6308         use bitcoin::hashes::Hash;
6309         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
6310
6311         use crate::chain::transaction::OutPoint;
6312         use crate::sign::{EntropySource, KeysManager};
6313         use crate::ln::channelmanager::{self, ChannelCounterparty, ChannelDetails};
6314         use crate::ln::features::InvoiceFeatures;
6315         use crate::routing::gossip::NetworkGraph;
6316         use crate::util::config::UserConfig;
6317         use crate::util::ser::ReadableArgs;
6318         use crate::util::test_utils::TestLogger;
6319
6320         /// Tries to open a network graph file, or panics with a URL to fetch it.
6321         pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
6322                 let res = File::open("net_graph-2023-01-18.bin") // By default we're run in RL/lightning
6323                         .or_else(|_| File::open("lightning/net_graph-2023-01-18.bin")) // We may be run manually in RL/
6324                         .or_else(|_| { // Fall back to guessing based on the binary location
6325                                 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
6326                                 let mut path = std::env::current_exe().unwrap();
6327                                 path.pop(); // lightning-...
6328                                 path.pop(); // deps
6329                                 path.pop(); // debug
6330                                 path.pop(); // target
6331                                 path.push("lightning");
6332                                 path.push("net_graph-2023-01-18.bin");
6333                                 File::open(path)
6334                         })
6335                         .or_else(|_| { // Fall back to guessing based on the binary location for a subcrate
6336                                 // path is likely something like .../rust-lightning/bench/target/debug/deps/bench..
6337                                 let mut path = std::env::current_exe().unwrap();
6338                                 path.pop(); // bench...
6339                                 path.pop(); // deps
6340                                 path.pop(); // debug
6341                                 path.pop(); // target
6342                                 path.pop(); // bench
6343                                 path.push("lightning");
6344                                 path.push("net_graph-2023-01-18.bin");
6345                                 File::open(path)
6346                         })
6347                 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.113-2023-01-18.bin and place it at lightning/net_graph-2023-01-18.bin");
6348                 #[cfg(require_route_graph_test)]
6349                 return Ok(res.unwrap());
6350                 #[cfg(not(require_route_graph_test))]
6351                 return res;
6352         }
6353
6354         pub(crate) fn read_network_graph(logger: &TestLogger) -> Result<NetworkGraph<&TestLogger>, &'static str> {
6355                 get_route_file().map(|mut f| NetworkGraph::read(&mut f, logger).unwrap())
6356         }
6357
6358         pub(crate) fn payer_pubkey() -> PublicKey {
6359                 let secp_ctx = Secp256k1::new();
6360                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
6361         }
6362
6363         #[inline]
6364         pub(crate) fn first_hop(node_id: PublicKey) -> ChannelDetails {
6365                 ChannelDetails {
6366                         channel_id: [0; 32],
6367                         counterparty: ChannelCounterparty {
6368                                 features: channelmanager::provided_init_features(&UserConfig::default()),
6369                                 node_id,
6370                                 unspendable_punishment_reserve: 0,
6371                                 forwarding_info: None,
6372                                 outbound_htlc_minimum_msat: None,
6373                                 outbound_htlc_maximum_msat: None,
6374                         },
6375                         funding_txo: Some(OutPoint {
6376                                 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0
6377                         }),
6378                         channel_type: None,
6379                         short_channel_id: Some(1),
6380                         inbound_scid_alias: None,
6381                         outbound_scid_alias: None,
6382                         channel_value_satoshis: 10_000_000_000,
6383                         user_channel_id: 0,
6384                         balance_msat: 10_000_000_000,
6385                         outbound_capacity_msat: 10_000_000_000,
6386                         next_outbound_htlc_minimum_msat: 0,
6387                         next_outbound_htlc_limit_msat: 10_000_000_000,
6388                         inbound_capacity_msat: 0,
6389                         unspendable_punishment_reserve: None,
6390                         confirmations_required: None,
6391                         confirmations: None,
6392                         force_close_spend_delay: None,
6393                         is_outbound: true,
6394                         is_channel_ready: true,
6395                         is_usable: true,
6396                         is_public: true,
6397                         inbound_htlc_minimum_msat: None,
6398                         inbound_htlc_maximum_msat: None,
6399                         config: None,
6400                         feerate_sat_per_1000_weight: None,
6401                 }
6402         }
6403
6404         pub(crate) fn generate_test_routes<S: Score>(graph: &NetworkGraph<&TestLogger>, scorer: &mut S,
6405                 score_params: &S::ScoreParams, features: InvoiceFeatures, mut seed: u64,
6406                 starting_amount: u64, route_count: usize,
6407         ) -> Vec<(ChannelDetails, PaymentParameters, u64)> {
6408                 let payer = payer_pubkey();
6409                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6410                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6411
6412                 let nodes = graph.read_only().nodes().clone();
6413                 let mut route_endpoints = Vec::new();
6414                 // Fetch 1.5x more routes than we need as after we do some scorer updates we may end up
6415                 // with some routes we picked being un-routable.
6416                 for _ in 0..route_count * 3 / 2 {
6417                         loop {
6418                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6419                                 let src = PublicKey::from_slice(nodes.unordered_keys()
6420                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6421                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6422                                 let dst = PublicKey::from_slice(nodes.unordered_keys()
6423                                         .skip((seed as usize) % nodes.len()).next().unwrap().as_slice()).unwrap();
6424                                 let params = PaymentParameters::from_node_id(dst, 42)
6425                                         .with_bolt11_features(features.clone()).unwrap();
6426                                 let first_hop = first_hop(src);
6427                                 let amt = starting_amount + seed % 1_000_000;
6428                                 let path_exists =
6429                                         get_route(&payer, &params, &graph.read_only(), Some(&[&first_hop]),
6430                                                 amt, &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok();
6431                                 if path_exists {
6432                                         // ...and seed the scorer with success and failure data...
6433                                         seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6434                                         let mut score_amt = seed % 1_000_000_000;
6435                                         loop {
6436                                                 // Generate fail/success paths for a wider range of potential amounts with
6437                                                 // MPP enabled to give us a chance to apply penalties for more potential
6438                                                 // routes.
6439                                                 let mpp_features = channelmanager::provided_invoice_features(&UserConfig::default());
6440                                                 let params = PaymentParameters::from_node_id(dst, 42)
6441                                                         .with_bolt11_features(mpp_features).unwrap();
6442
6443                                                 let route_res = get_route(&payer, &params, &graph.read_only(),
6444                                                         Some(&[&first_hop]), score_amt, &TestLogger::new(), &scorer,
6445                                                         score_params, &random_seed_bytes);
6446                                                 if let Ok(route) = route_res {
6447                                                         for path in route.paths {
6448                                                                 if seed & 0x80 == 0 {
6449                                                                         scorer.payment_path_successful(&path);
6450                                                                 } else {
6451                                                                         let short_channel_id = path.hops[path.hops.len() / 2].short_channel_id;
6452                                                                         scorer.payment_path_failed(&path, short_channel_id);
6453                                                                 }
6454                                                                 seed = seed.overflowing_mul(6364136223846793005).0.overflowing_add(1).0;
6455                                                         }
6456                                                         break;
6457                                                 }
6458                                                 // If we couldn't find a path with a higer amount, reduce and try again.
6459                                                 score_amt /= 100;
6460                                         }
6461
6462                                         route_endpoints.push((first_hop, params, amt));
6463                                         break;
6464                                 }
6465                         }
6466                 }
6467
6468                 // Because we've changed channel scores, it's possible we'll take different routes to the
6469                 // selected destinations, possibly causing us to fail because, eg, the newly-selected path
6470                 // requires a too-high CLTV delta.
6471                 route_endpoints.retain(|(first_hop, params, amt)| {
6472                         get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6473                                 &TestLogger::new(), &scorer, score_params, &random_seed_bytes).is_ok()
6474                 });
6475                 route_endpoints.truncate(route_count);
6476                 assert_eq!(route_endpoints.len(), route_count);
6477                 route_endpoints
6478         }
6479 }
6480
6481 #[cfg(ldk_bench)]
6482 pub mod benches {
6483         use super::*;
6484         use crate::sign::{EntropySource, KeysManager};
6485         use crate::ln::channelmanager;
6486         use crate::ln::features::InvoiceFeatures;
6487         use crate::routing::gossip::NetworkGraph;
6488         use crate::routing::scoring::{FixedPenaltyScorer, ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
6489         use crate::util::config::UserConfig;
6490         use crate::util::logger::{Logger, Record};
6491         use crate::util::test_utils::TestLogger;
6492
6493         use criterion::Criterion;
6494
6495         struct DummyLogger {}
6496         impl Logger for DummyLogger {
6497                 fn log(&self, _record: &Record) {}
6498         }
6499
6500         pub fn generate_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6501                 let logger = TestLogger::new();
6502                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6503                 let scorer = FixedPenaltyScorer::with_penalty(0);
6504                 generate_routes(bench, &network_graph, scorer, &(), InvoiceFeatures::empty(), 0,
6505                         "generate_routes_with_zero_penalty_scorer");
6506         }
6507
6508         pub fn generate_mpp_routes_with_zero_penalty_scorer(bench: &mut Criterion) {
6509                 let logger = TestLogger::new();
6510                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6511                 let scorer = FixedPenaltyScorer::with_penalty(0);
6512                 generate_routes(bench, &network_graph, scorer, &(),
6513                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6514                         "generate_mpp_routes_with_zero_penalty_scorer");
6515         }
6516
6517         pub fn generate_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6518                 let logger = TestLogger::new();
6519                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6520                 let params = ProbabilisticScoringFeeParameters::default();
6521                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6522                 generate_routes(bench, &network_graph, scorer, &params, InvoiceFeatures::empty(), 0,
6523                         "generate_routes_with_probabilistic_scorer");
6524         }
6525
6526         pub fn generate_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6527                 let logger = TestLogger::new();
6528                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6529                 let params = ProbabilisticScoringFeeParameters::default();
6530                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6531                 generate_routes(bench, &network_graph, scorer, &params,
6532                         channelmanager::provided_invoice_features(&UserConfig::default()), 0,
6533                         "generate_mpp_routes_with_probabilistic_scorer");
6534         }
6535
6536         pub fn generate_large_mpp_routes_with_probabilistic_scorer(bench: &mut Criterion) {
6537                 let logger = TestLogger::new();
6538                 let network_graph = bench_utils::read_network_graph(&logger).unwrap();
6539                 let params = ProbabilisticScoringFeeParameters::default();
6540                 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &network_graph, &logger);
6541                 generate_routes(bench, &network_graph, scorer, &params,
6542                         channelmanager::provided_invoice_features(&UserConfig::default()), 100_000_000,
6543                         "generate_large_mpp_routes_with_probabilistic_scorer");
6544         }
6545
6546         fn generate_routes<S: Score>(
6547                 bench: &mut Criterion, graph: &NetworkGraph<&TestLogger>, mut scorer: S,
6548                 score_params: &S::ScoreParams, features: InvoiceFeatures, starting_amount: u64,
6549                 bench_name: &'static str,
6550         ) {
6551                 let payer = bench_utils::payer_pubkey();
6552                 let keys_manager = KeysManager::new(&[0u8; 32], 42, 42);
6553                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
6554
6555                 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
6556                 let route_endpoints = bench_utils::generate_test_routes(graph, &mut scorer, score_params, features, 0xdeadbeef, starting_amount, 50);
6557
6558                 // ...then benchmark finding paths between the nodes we learned.
6559                 let mut idx = 0;
6560                 bench.bench_function(bench_name, |b| b.iter(|| {
6561                         let (first_hop, params, amt) = &route_endpoints[idx % route_endpoints.len()];
6562                         assert!(get_route(&payer, params, &graph.read_only(), Some(&[first_hop]), *amt,
6563                                 &DummyLogger{}, &scorer, score_params, &random_seed_bytes).is_ok());
6564                         idx += 1;
6565                 }));
6566         }
6567 }