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