1 // This file is Copyright its original authors, visible in version control
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
10 //! The top-level routing/network map tracking logic lives here.
12 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
13 //! interrogate it to get routes for your own payments.
15 use bitcoin::secp256k1::key::PublicKey;
17 use ln::channelmanager::ChannelDetails;
18 use ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
19 use ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
21 use routing::network_graph::{NetworkGraph, NodeId, RoutingFees};
22 use util::ser::{Writeable, Readable};
23 use util::logger::{Level, Logger};
27 use alloc::collections::BinaryHeap;
32 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
34 /// The node_id of the node at this hop.
35 pub pubkey: PublicKey,
36 /// The node_announcement features of the node at this hop. For the last hop, these may be
37 /// amended to match the features present in the invoice this node generated.
38 pub node_features: NodeFeatures,
39 /// The channel that should be used from the previous hop to reach this node.
40 pub short_channel_id: u64,
41 /// The channel_announcement features of the channel that should be used from the previous hop
42 /// to reach this node.
43 pub channel_features: ChannelFeatures,
44 /// The fee taken on this hop (for paying for the use of the *next* channel in the path).
45 /// For the last hop, this should be the full value of the payment (might be more than
46 /// requested if we had to match htlc_minimum_msat).
48 /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
49 /// expected at the destination, in excess of the current block height.
50 pub cltv_expiry_delta: u32,
53 impl_writeable_tlv_based!(RouteHop, {
54 (0, pubkey, required),
55 (2, node_features, required),
56 (4, short_channel_id, required),
57 (6, channel_features, required),
58 (8, fee_msat, required),
59 (10, cltv_expiry_delta, required),
62 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
63 /// it can take multiple paths. Each path is composed of one or more hops through the network.
64 #[derive(Clone, Hash, PartialEq, Eq)]
66 /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
67 /// last RouteHop in each path must be the same.
68 /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
69 /// destination. Thus, this must always be at least length one. While the maximum length of any
70 /// given path is variable, keeping the length of any path to less than 20 should currently
71 /// ensure it is viable.
72 pub paths: Vec<Vec<RouteHop>>,
73 /// The `payee` parameter passed to [`find_route`].
74 /// This is used by `ChannelManager` to track information which may be required for retries,
75 /// provided back to you via [`Event::PaymentPathFailed`].
77 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
78 pub payee: Option<Payee>,
81 pub(crate) trait RoutePath {
82 /// Gets the fees for a given path, excluding any excess paid to the recipient.
83 fn get_path_fees(&self) -> u64;
85 impl RoutePath for Vec<RouteHop> {
86 fn get_path_fees(&self) -> u64 {
87 // Do not count last hop of each path since that's the full value of the payment
88 self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
89 .iter().map(|hop| &hop.fee_msat)
95 /// Returns the total amount of fees paid on this [`Route`].
97 /// This doesn't include any extra payment made to the recipient, which can happen in excess of
98 /// the amount passed to [`find_route`]'s `params.final_value_msat`.
99 pub fn get_total_fees(&self) -> u64 {
100 self.paths.iter().map(|path| path.get_path_fees()).sum()
103 /// Returns the total amount paid on this [`Route`], excluding the fees.
104 pub fn get_total_amount(&self) -> u64 {
105 return self.paths.iter()
106 .map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
111 const SERIALIZATION_VERSION: u8 = 1;
112 const MIN_SERIALIZATION_VERSION: u8 = 1;
114 impl Writeable for Route {
115 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
116 write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
117 (self.paths.len() as u64).write(writer)?;
118 for hops in self.paths.iter() {
119 (hops.len() as u8).write(writer)?;
120 for hop in hops.iter() {
124 write_tlv_fields!(writer, {
125 (1, self.payee, option),
131 impl Readable for Route {
132 fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
133 let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
134 let path_count: u64 = Readable::read(reader)?;
135 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
136 for _ in 0..path_count {
137 let hop_count: u8 = Readable::read(reader)?;
138 let mut hops = Vec::with_capacity(hop_count as usize);
139 for _ in 0..hop_count {
140 hops.push(Readable::read(reader)?);
144 let mut payee = None;
145 read_tlv_fields!(reader, {
148 Ok(Route { paths, payee })
152 /// Parameters needed to find a [`Route`] for paying a [`Payee`].
154 /// Passed to [`find_route`] and also provided in [`Event::PaymentPathFailed`] for retrying a failed
157 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
158 #[derive(Clone, Debug)]
159 pub struct RouteParameters {
160 /// The recipient of the failed payment path.
163 /// The amount in msats sent on the failed payment path.
164 pub final_value_msat: u64,
166 /// The CLTV on the final hop of the failed payment path.
167 pub final_cltv_expiry_delta: u32,
170 impl_writeable_tlv_based!(RouteParameters, {
171 (0, payee, required),
172 (2, final_value_msat, required),
173 (4, final_cltv_expiry_delta, required),
176 /// The recipient of a payment.
177 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
179 /// The node id of the payee.
180 pub pubkey: PublicKey,
182 /// Features supported by the payee.
184 /// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
185 /// does not contain any features.
187 /// [`for_keysend`]: Self::for_keysend
188 pub features: Option<InvoiceFeatures>,
190 /// Hints for routing to the payee, containing channels connecting the payee to public nodes.
191 pub route_hints: Vec<RouteHint>,
193 /// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
194 pub expiry_time: Option<u64>,
197 impl_writeable_tlv_based!(Payee, {
198 (0, pubkey, required),
199 (2, features, option),
200 (4, route_hints, vec_type),
201 (6, expiry_time, option),
205 /// Creates a payee with the node id of the given `pubkey`.
206 pub fn new(pubkey: PublicKey) -> Self {
215 /// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
216 pub fn for_keysend(pubkey: PublicKey) -> Self {
217 Self::new(pubkey).with_features(InvoiceFeatures::for_keysend())
220 /// Includes the payee's features.
222 /// (C-not exported) since bindings don't support move semantics
223 pub fn with_features(self, features: InvoiceFeatures) -> Self {
224 Self { features: Some(features), ..self }
227 /// Includes hints for routing to the payee.
229 /// (C-not exported) since bindings don't support move semantics
230 pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
231 Self { route_hints, ..self }
234 /// Includes a payment expiration in seconds relative to the UNIX epoch.
235 pub fn with_expiry_time(self, expiry_time: u64) -> Self {
236 Self { expiry_time: Some(expiry_time), ..self }
240 /// A list of hops along a payment path terminating with a channel to the recipient.
241 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
242 pub struct RouteHint(pub Vec<RouteHintHop>);
245 impl Writeable for RouteHint {
246 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
247 (self.0.len() as u64).write(writer)?;
248 for hop in self.0.iter() {
255 impl Readable for RouteHint {
256 fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
257 let hop_count: u64 = Readable::read(reader)?;
258 let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
259 for _ in 0..hop_count {
260 hops.push(Readable::read(reader)?);
266 /// A channel descriptor for a hop along a payment path.
267 #[derive(Clone, Debug, Hash, Eq, PartialEq)]
268 pub struct RouteHintHop {
269 /// The node_id of the non-target end of the route
270 pub src_node_id: PublicKey,
271 /// The short_channel_id of this channel
272 pub short_channel_id: u64,
273 /// The fees which must be paid to use this channel
274 pub fees: RoutingFees,
275 /// The difference in CLTV values between this node and the next node.
276 pub cltv_expiry_delta: u16,
277 /// The minimum value, in msat, which must be relayed to the next hop.
278 pub htlc_minimum_msat: Option<u64>,
279 /// The maximum value in msat available for routing with a single HTLC.
280 pub htlc_maximum_msat: Option<u64>,
283 impl_writeable_tlv_based!(RouteHintHop, {
284 (0, src_node_id, required),
285 (1, htlc_minimum_msat, option),
286 (2, short_channel_id, required),
287 (3, htlc_maximum_msat, option),
289 (6, cltv_expiry_delta, required),
292 #[derive(Eq, PartialEq)]
293 struct RouteGraphNode {
295 lowest_fee_to_peer_through_node: u64,
296 lowest_fee_to_node: u64,
297 // The maximum value a yet-to-be-constructed payment path might flow through this node.
298 // This value is upper-bounded by us by:
299 // - how much is needed for a path being constructed
300 // - how much value can channels following this node (up to the destination) can contribute,
301 // considering their capacity and fees
302 value_contribution_msat: u64,
303 /// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
304 /// minimum, we use it, plus the fees required at each earlier hop to meet it.
305 path_htlc_minimum_msat: u64,
306 /// All penalties incurred from this hop on the way to the destination, as calculated using
308 path_penalty_msat: u64,
311 impl cmp::Ord for RouteGraphNode {
312 fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
313 let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
314 .checked_add(other.path_penalty_msat)
315 .unwrap_or_else(|| u64::max_value());
316 let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
317 .checked_add(self.path_penalty_msat)
318 .unwrap_or_else(|| u64::max_value());
319 other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
323 impl cmp::PartialOrd for RouteGraphNode {
324 fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
325 Some(self.cmp(other))
329 struct DummyDirectionalChannelInfo {
330 cltv_expiry_delta: u32,
331 htlc_minimum_msat: u64,
332 htlc_maximum_msat: Option<u64>,
336 /// It's useful to keep track of the hops associated with the fees required to use them,
337 /// so that we can choose cheaper paths (as per Dijkstra's algorithm).
338 /// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
339 /// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
340 #[derive(Clone, Debug)]
341 struct PathBuildingHop<'a> {
342 // The RouteHintHop fields which will eventually be used if this hop is used in a final Route.
343 // Note that node_features is calculated separately after our initial graph walk.
345 short_channel_id: u64,
346 channel_features: &'a ChannelFeatures,
348 cltv_expiry_delta: u32,
350 /// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
351 src_lowest_inbound_fees: RoutingFees,
352 /// Fees of the channel used in this hop.
353 channel_fees: RoutingFees,
354 /// All the fees paid *after* this channel on the way to the destination
355 next_hops_fee_msat: u64,
356 /// Fee paid for the use of the current channel (see channel_fees).
357 /// The value will be actually deducted from the counterparty balance on the previous link.
358 hop_use_fee_msat: u64,
359 /// Used to compare channels when choosing the for routing.
360 /// Includes paying for the use of a hop and the following hops, as well as
361 /// an estimated cost of reaching this hop.
362 /// Might get stale when fees are recomputed. Primarily for internal use.
364 /// This is useful for update_value_and_recompute_fees to make sure
365 /// we don't fall below the minimum. Should not be updated manually and
366 /// generally should not be accessed.
367 htlc_minimum_msat: u64,
368 /// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
369 /// walk and may be invalid thereafter.
370 path_htlc_minimum_msat: u64,
371 /// All penalties incurred from this channel on the way to the destination, as calculated using
373 path_penalty_msat: u64,
374 /// If we've already processed a node as the best node, we shouldn't process it again. Normally
375 /// we'd just ignore it if we did as all channels would have a higher new fee, but because we
376 /// may decrease the amounts in use as we walk the graph, the actual calculated fee may
377 /// decrease as well. Thus, we have to explicitly track which nodes have been processed and
378 /// avoid processing them again.
380 #[cfg(any(test, feature = "fuzztarget"))]
381 // In tests, we apply further sanity checks on cases where we skip nodes we already processed
382 // to ensure it is specifically in cases where the fee has gone down because of a decrease in
383 // value_contribution_msat, which requires tracking it here. See comments below where it is
384 // used for more info.
385 value_contribution_msat: u64,
388 // Instantiated with a list of hops with correct data in them collected during path finding,
389 // an instance of this struct should be further modified only via given methods.
391 struct PaymentPath<'a> {
392 hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
395 impl<'a> PaymentPath<'a> {
396 // TODO: Add a value_msat field to PaymentPath and use it instead of this function.
397 fn get_value_msat(&self) -> u64 {
398 self.hops.last().unwrap().0.fee_msat
401 fn get_total_fee_paid_msat(&self) -> u64 {
402 if self.hops.len() < 1 {
406 // Can't use next_hops_fee_msat because it gets outdated.
407 for (i, (hop, _)) in self.hops.iter().enumerate() {
408 if i != self.hops.len() - 1 {
409 result += hop.fee_msat;
415 // If the amount transferred by the path is updated, the fees should be adjusted. Any other way
416 // to change fees may result in an inconsistency.
418 // Sometimes we call this function right after constructing a path which is inconsistent in
419 // that it the value being transferred has decreased while we were doing path finding, leading
420 // to the fees being paid not lining up with the actual limits.
422 // Note that this function is not aware of the available_liquidity limit, and thus does not
423 // support increasing the value being transferred.
424 fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
425 assert!(value_msat <= self.hops.last().unwrap().0.fee_msat);
427 let mut total_fee_paid_msat = 0 as u64;
428 for i in (0..self.hops.len()).rev() {
429 let last_hop = i == self.hops.len() - 1;
431 // For non-last-hop, this value will represent the fees paid on the current hop. It
432 // will consist of the fees for the use of the next hop, and extra fees to match
433 // htlc_minimum_msat of the current channel. Last hop is handled separately.
434 let mut cur_hop_fees_msat = 0;
436 cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
439 let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
440 cur_hop.next_hops_fee_msat = total_fee_paid_msat;
441 // Overpay in fees if we can't save these funds due to htlc_minimum_msat.
442 // We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
443 // set it too high just to maliciously take more fees by exploiting this
444 // match htlc_minimum_msat logic.
445 let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
446 if let Some(extra_fees_msat) = cur_hop.htlc_minimum_msat.checked_sub(cur_hop_transferred_amount_msat) {
447 // Note that there is a risk that *previous hops* (those closer to us, as we go
448 // payee->our_node here) would exceed their htlc_maximum_msat or available balance.
450 // This might make us end up with a broken route, although this should be super-rare
451 // in practice, both because of how healthy channels look like, and how we pick
452 // channels in add_entry.
453 // Also, this can't be exploited more heavily than *announce a free path and fail
455 cur_hop_transferred_amount_msat += extra_fees_msat;
456 total_fee_paid_msat += extra_fees_msat;
457 cur_hop_fees_msat += extra_fees_msat;
461 // Final hop is a special case: it usually has just value_msat (by design), but also
462 // it still could overpay for the htlc_minimum_msat.
463 cur_hop.fee_msat = cur_hop_transferred_amount_msat;
465 // Propagate updated fees for the use of the channels to one hop back, where they
466 // will be actually paid (fee_msat). The last hop is handled above separately.
467 cur_hop.fee_msat = cur_hop_fees_msat;
470 // Fee for the use of the current hop which will be deducted on the previous hop.
471 // Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
472 // this channel is free for us.
474 if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.channel_fees) {
475 cur_hop.hop_use_fee_msat = new_fee;
476 total_fee_paid_msat += new_fee;
478 // It should not be possible because this function is called only to reduce the
479 // value. In that case, compute_fee was already called with the same fees for
480 // larger amount and there was no overflow.
488 fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
489 let proportional_fee_millions =
490 amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
491 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
492 (channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
496 // This function may be (indirectly) called without any verification,
497 // with channel_fees provided by a caller. We should handle it gracefully.
502 /// Finds a route from us (payer) to the given target node (payee).
504 /// If the payee provided features in their invoice, they should be provided via `params.payee`.
505 /// Without this, MPP will only be used if the payee's features are available in the network graph.
507 /// Private routing paths between a public node and the target may be included in `params.payee`.
509 /// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
510 /// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of our local
511 /// channels from [`NetworkGraph`] will be ignored, and only those in `first_hops` will be used.
513 /// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
514 /// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
515 /// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
519 /// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
520 /// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
525 /// Panics if first_hops contains channels without short_channel_ids;
526 /// [`ChannelManager::list_usable_channels`] will never include such channels.
528 /// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
529 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
530 pub fn find_route<L: Deref, S: routing::Score>(
531 our_node_pubkey: &PublicKey, params: &RouteParameters, network: &NetworkGraph,
532 first_hops: Option<&[&ChannelDetails]>, logger: L, scorer: &S
533 ) -> Result<Route, LightningError>
534 where L::Target: Logger {
536 our_node_pubkey, ¶ms.payee, network, first_hops, params.final_value_msat,
537 params.final_cltv_expiry_delta, logger, scorer
541 pub(crate) fn get_route<L: Deref, S: routing::Score>(
542 our_node_pubkey: &PublicKey, payee: &Payee, network: &NetworkGraph,
543 first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
544 logger: L, scorer: &S
545 ) -> Result<Route, LightningError>
546 where L::Target: Logger {
547 let payee_node_id = NodeId::from_pubkey(&payee.pubkey);
548 let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
550 if payee_node_id == our_node_id {
551 return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
554 if final_value_msat > MAX_VALUE_MSAT {
555 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
558 if final_value_msat == 0 {
559 return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
562 for route in payee.route_hints.iter() {
563 for hop in &route.0 {
564 if hop.src_node_id == payee.pubkey {
565 return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
570 // The general routing idea is the following:
571 // 1. Fill first/last hops communicated by the caller.
572 // 2. Attempt to construct a path from payer to payee for transferring
573 // any ~sufficient (described later) value.
574 // If succeed, remember which channels were used and how much liquidity they have available,
575 // so that future paths don't rely on the same liquidity.
576 // 3. Prooceed to the next step if:
577 // - we hit the recommended target value;
578 // - OR if we could not construct a new path. Any next attempt will fail too.
579 // Otherwise, repeat step 2.
580 // 4. See if we managed to collect paths which aggregately are able to transfer target value
581 // (not recommended value). If yes, proceed. If not, fail routing.
582 // 5. Randomly combine paths into routes having enough to fulfill the payment. (TODO: knapsack)
583 // 6. Of all the found paths, select only those with the lowest total fee.
584 // 7. The last path in every selected route is likely to be more than we need.
585 // Reduce its value-to-transfer and recompute fees.
586 // 8. Choose the best route by the lowest total fee.
588 // As for the actual search algorithm,
589 // we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
590 // plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
592 // We are not a faithful Dijkstra's implementation because we can change values which impact
593 // earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
594 // liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) then
595 // the value we are currently attempting to send over a path, we simply reduce the value being
596 // sent along the path for any hops after that channel. This may imply that later fees (which
597 // we've already tabulated) are lower because a smaller value is passing through the channels
598 // (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
599 // channels which were selected earlier (and which may still be used for other paths without a
600 // lower liquidity limit), so we simply accept that some liquidity-limited paths may be
603 // One potentially problematic case for this algorithm would be if there are many
604 // liquidity-limited paths which are liquidity-limited near the destination (ie early in our
605 // graph walking), we may never find a path which is not liquidity-limited and has lower
606 // proportional fee (and only lower absolute fee when considering the ultimate value sent).
607 // Because we only consider paths with at least 5% of the total value being sent, the damage
608 // from such a case should be limited, however this could be further reduced in the future by
609 // calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
610 // limits for the purposes of fee calculation.
612 // Alternatively, we could store more detailed path information in the heap (targets, below)
613 // and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
614 // up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
615 // and practically (as we would need to store dynamically-allocated path information in heap
616 // objects, increasing malloc traffic and indirect memory access significantly). Further, the
617 // results of such an algorithm would likely be biased towards lower-value paths.
619 // Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
620 // outside of our current search value, running a path search more times to gather candidate
621 // paths at different values. While this may be acceptable, further path searches may increase
622 // runtime for little gain. Specifically, the current algorithm rather efficiently explores the
623 // graph for candidate paths, calculating the maximum value which can realistically be sent at
624 // the same time, remaining generic across different payment values.
626 // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
627 // to use as the A* heuristic beyond just the cost to get one node further than the current
630 let network_graph = network.read_only();
631 let network_channels = network_graph.channels();
632 let network_nodes = network_graph.nodes();
633 let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
634 cltv_expiry_delta: 0,
635 htlc_minimum_msat: 0,
636 htlc_maximum_msat: None,
639 proportional_millionths: 0,
643 // Allow MPP only if we have a features set from somewhere that indicates the payee supports
644 // it. If the payee supports it they're supposed to include it in the invoice, so that should
646 let allow_mpp = if let Some(features) = &payee.features {
647 features.supports_basic_mpp()
648 } else if let Some(node) = network_nodes.get(&payee_node_id) {
649 if let Some(node_info) = node.announcement_info.as_ref() {
650 node_info.features.supports_basic_mpp()
653 log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP", our_node_pubkey,
654 payee.pubkey, if allow_mpp { "with" } else { "without" });
657 // Prepare the data we'll use for payee-to-payer search by
658 // inserting first hops suggested by the caller as targets.
659 // Our search will then attempt to reach them while traversing from the payee node.
660 let mut first_hop_targets: HashMap<_, Vec<(_, ChannelFeatures, _, NodeFeatures)>> =
661 HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
662 if let Some(hops) = first_hops {
664 let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
665 if chan.counterparty.node_id == *our_node_pubkey {
666 return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
668 first_hop_targets.entry(NodeId::from_pubkey(&chan.counterparty.node_id)).or_insert(Vec::new())
669 .push((short_channel_id, chan.counterparty.features.to_context(), chan.outbound_capacity_msat, chan.counterparty.features.to_context()));
671 if first_hop_targets.is_empty() {
672 return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
676 let empty_channel_features = ChannelFeatures::empty();
678 // The main heap containing all candidate next-hops sorted by their score (max(A* fee,
679 // htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
680 // adding duplicate entries when we find a better path to a given node.
681 let mut targets = BinaryHeap::new();
683 // Map from node_id to information about the best current path to that node, including feerate
685 let mut dist = HashMap::with_capacity(network_nodes.len());
687 // During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
688 // indicating that we may wish to try again with a higher value, potentially paying to meet an
689 // htlc_minimum with extra fees while still finding a cheaper path.
690 let mut hit_minimum_limit;
692 // When arranging a route, we select multiple paths so that we can make a multi-path payment.
693 // We start with a path_value of the exact amount we want, and if that generates a route we may
694 // return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
695 // amount we want in total across paths, selecting the best subset at the end.
696 const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
697 let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
698 let mut path_value_msat = final_value_msat;
700 // We don't want multiple paths (as per MPP) share liquidity of the same channels.
701 // This map allows paths to be aware of the channel use by other paths in the same call.
702 // This would help to make a better path finding decisions and not "overbook" channels.
703 // It is unaware of the directions (except for `outbound_capacity_msat` in `first_hops`).
704 let mut bookkeeped_channels_liquidity_available_msat = HashMap::with_capacity(network_nodes.len());
706 // Keeping track of how much value we already collected across other paths. Helps to decide:
707 // - how much a new path should be transferring (upper bound);
708 // - whether a channel should be disregarded because
709 // it's available liquidity is too small comparing to how much more we need to collect;
710 // - when we want to stop looking for new paths.
711 let mut already_collected_value_msat = 0;
713 log_trace!(logger, "Building path from {} (payee) to {} (us/payer) for value {} msat.", payee.pubkey, our_node_pubkey, final_value_msat);
715 macro_rules! add_entry {
716 // Adds entry which goes from $src_node_id to $dest_node_id
717 // over the channel with id $chan_id with fees described in
718 // $directional_info.
719 // $next_hops_fee_msat represents the fees paid for using all the channel *after* this one,
720 // since that value has to be transferred over this channel.
721 // Returns whether this channel caused an update to `targets`.
722 ( $chan_id: expr, $src_node_id: expr, $dest_node_id: expr, $directional_info: expr, $capacity_sats: expr, $chan_features: expr, $next_hops_fee_msat: expr,
723 $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => { {
724 // We "return" whether we updated the path at the end, via this:
725 let mut did_add_update_path_to_src_node = false;
726 // Channels to self should not be used. This is more of belt-and-suspenders, because in
727 // practice these cases should be caught earlier:
728 // - for regular channels at channel announcement (TODO)
729 // - for first and last hops early in get_route
730 if $src_node_id != $dest_node_id.clone() {
731 let available_liquidity_msat = bookkeeped_channels_liquidity_available_msat.entry($chan_id.clone()).or_insert_with(|| {
732 let mut initial_liquidity_available_msat = None;
733 if let Some(capacity_sats) = $capacity_sats {
734 initial_liquidity_available_msat = Some(capacity_sats * 1000);
737 if let Some(htlc_maximum_msat) = $directional_info.htlc_maximum_msat {
738 if let Some(available_msat) = initial_liquidity_available_msat {
739 initial_liquidity_available_msat = Some(cmp::min(available_msat, htlc_maximum_msat));
741 initial_liquidity_available_msat = Some(htlc_maximum_msat);
745 match initial_liquidity_available_msat {
746 Some(available_msat) => available_msat,
747 // We assume channels with unknown balance have
748 // a capacity of 0.0025 BTC (or 250_000 sats).
749 None => 250_000 * 1000
753 // It is tricky to substract $next_hops_fee_msat from available liquidity here.
754 // It may be misleading because we might later choose to reduce the value transferred
755 // over these channels, and the channel which was insufficient might become sufficient.
756 // Worst case: we drop a good channel here because it can't cover the high following
757 // fees caused by one expensive channel, but then this channel could have been used
758 // if the amount being transferred over this path is lower.
759 // We do this for now, but this is a subject for removal.
760 if let Some(available_value_contribution_msat) = available_liquidity_msat.checked_sub($next_hops_fee_msat) {
762 // Routing Fragmentation Mitigation heuristic:
764 // Routing fragmentation across many payment paths increases the overall routing
765 // fees as you have irreducible routing fees per-link used (`fee_base_msat`).
766 // Taking too many smaller paths also increases the chance of payment failure.
767 // Thus to avoid this effect, we require from our collected links to provide
768 // at least a minimal contribution to the recommended value yet-to-be-fulfilled.
770 // This requirement is currently 5% of the remaining-to-be-collected value.
771 // This means as we successfully advance in our collection,
772 // the absolute liquidity contribution is lowered,
773 // thus increasing the number of potential channels to be selected.
775 // Derive the minimal liquidity contribution with a ratio of 20 (5%, rounded up)
776 // or 100% if we're not allowed to do multipath payments.
777 let minimal_value_contribution_msat: u64 = if allow_mpp {
778 (recommended_value_msat - already_collected_value_msat + 19) / 20
782 // Verify the liquidity offered by this channel complies to the minimal contribution.
783 let contributes_sufficient_value = available_value_contribution_msat >= minimal_value_contribution_msat;
785 let value_contribution_msat = cmp::min(available_value_contribution_msat, $next_hops_value_contribution);
786 // Includes paying fees for the use of the following channels.
787 let amount_to_transfer_over_msat: u64 = match value_contribution_msat.checked_add($next_hops_fee_msat) {
788 Some(result) => result,
789 // Can't overflow due to how the values were computed right above.
790 None => unreachable!(),
792 #[allow(unused_comparisons)] // $next_hops_path_htlc_minimum_msat is 0 in some calls so rustc complains
793 let over_path_minimum_msat = amount_to_transfer_over_msat >= $directional_info.htlc_minimum_msat &&
794 amount_to_transfer_over_msat >= $next_hops_path_htlc_minimum_msat;
796 // If HTLC minimum is larger than the amount we're going to transfer, we shouldn't
797 // bother considering this channel.
798 // Since we're choosing amount_to_transfer_over_msat as maximum possible, it can
799 // be only reduced later (not increased), so this channel should just be skipped
800 // as not sufficient.
801 if !over_path_minimum_msat {
802 hit_minimum_limit = true;
803 } else if contributes_sufficient_value {
804 // Note that low contribution here (limited by available_liquidity_msat)
805 // might violate htlc_minimum_msat on the hops which are next along the
806 // payment path (upstream to the payee). To avoid that, we recompute path
807 // path fees knowing the final path contribution after constructing it.
808 let path_htlc_minimum_msat = compute_fees($next_hops_path_htlc_minimum_msat, $directional_info.fees)
809 .and_then(|fee_msat| fee_msat.checked_add($next_hops_path_htlc_minimum_msat))
810 .map(|fee_msat| cmp::max(fee_msat, $directional_info.htlc_minimum_msat))
811 .unwrap_or_else(|| u64::max_value());
812 let hm_entry = dist.entry($src_node_id);
813 let old_entry = hm_entry.or_insert_with(|| {
814 // If there was previously no known way to access
815 // the source node (recall it goes payee-to-payer) of $chan_id, first add
816 // a semi-dummy record just to compute the fees to reach the source node.
817 // This will affect our decision on selecting $chan_id
818 // as a way to reach the $dest_node_id.
819 let mut fee_base_msat = u32::max_value();
820 let mut fee_proportional_millionths = u32::max_value();
821 if let Some(Some(fees)) = network_nodes.get(&$src_node_id).map(|node| node.lowest_inbound_channel_fees) {
822 fee_base_msat = fees.base_msat;
823 fee_proportional_millionths = fees.proportional_millionths;
826 node_id: $dest_node_id.clone(),
828 channel_features: $chan_features,
830 cltv_expiry_delta: 0,
831 src_lowest_inbound_fees: RoutingFees {
832 base_msat: fee_base_msat,
833 proportional_millionths: fee_proportional_millionths,
835 channel_fees: $directional_info.fees,
836 next_hops_fee_msat: u64::max_value(),
837 hop_use_fee_msat: u64::max_value(),
838 total_fee_msat: u64::max_value(),
839 htlc_minimum_msat: $directional_info.htlc_minimum_msat,
840 path_htlc_minimum_msat,
841 path_penalty_msat: u64::max_value(),
842 was_processed: false,
843 #[cfg(any(test, feature = "fuzztarget"))]
844 value_contribution_msat,
848 #[allow(unused_mut)] // We only use the mut in cfg(test)
849 let mut should_process = !old_entry.was_processed;
850 #[cfg(any(test, feature = "fuzztarget"))]
852 // In test/fuzzing builds, we do extra checks to make sure the skipping
853 // of already-seen nodes only happens in cases we expect (see below).
854 if !should_process { should_process = true; }
858 let mut hop_use_fee_msat = 0;
859 let mut total_fee_msat = $next_hops_fee_msat;
861 // Ignore hop_use_fee_msat for channel-from-us as we assume all channels-from-us
862 // will have the same effective-fee
863 if $src_node_id != our_node_id {
864 match compute_fees(amount_to_transfer_over_msat, $directional_info.fees) {
865 // max_value means we'll always fail
866 // the old_entry.total_fee_msat > total_fee_msat check
867 None => total_fee_msat = u64::max_value(),
869 hop_use_fee_msat = fee_msat;
870 total_fee_msat += hop_use_fee_msat;
871 // When calculating the lowest inbound fees to a node, we
872 // calculate fees here not based on the actual value we think
873 // will flow over this channel, but on the minimum value that
874 // we'll accept flowing over it. The minimum accepted value
875 // is a constant through each path collection run, ensuring
876 // consistent basis. Otherwise we may later find a
877 // different path to the source node that is more expensive,
878 // but which we consider to be cheaper because we are capacity
879 // constrained and the relative fee becomes lower.
880 match compute_fees(minimal_value_contribution_msat, old_entry.src_lowest_inbound_fees)
881 .map(|a| a.checked_add(total_fee_msat)) {
886 total_fee_msat = u64::max_value();
893 let path_penalty_msat = $next_hops_path_penalty_msat
894 .checked_add(scorer.channel_penalty_msat($chan_id.clone(), &$src_node_id, &$dest_node_id))
895 .unwrap_or_else(|| u64::max_value());
896 let new_graph_node = RouteGraphNode {
897 node_id: $src_node_id,
898 lowest_fee_to_peer_through_node: total_fee_msat,
899 lowest_fee_to_node: $next_hops_fee_msat as u64 + hop_use_fee_msat,
900 value_contribution_msat: value_contribution_msat,
901 path_htlc_minimum_msat,
905 // Update the way of reaching $src_node_id with the given $chan_id (from $dest_node_id),
906 // if this way is cheaper than the already known
907 // (considering the cost to "reach" this channel from the route destination,
908 // the cost of using this channel,
909 // and the cost of routing to the source node of this channel).
910 // Also, consider that htlc_minimum_msat_difference, because we might end up
911 // paying it. Consider the following exploit:
912 // we use 2 paths to transfer 1.5 BTC. One of them is 0-fee normal 1 BTC path,
913 // and for the other one we picked a 1sat-fee path with htlc_minimum_msat of
914 // 1 BTC. Now, since the latter is more expensive, we gonna try to cut it
915 // by 0.5 BTC, but then match htlc_minimum_msat by paying a fee of 0.5 BTC
917 // Ideally the scoring could be smarter (e.g. 0.5*htlc_minimum_msat here),
918 // but it may require additional tracking - we don't want to double-count
919 // the fees included in $next_hops_path_htlc_minimum_msat, but also
920 // can't use something that may decrease on future hops.
921 let old_cost = cmp::max(old_entry.total_fee_msat, old_entry.path_htlc_minimum_msat)
922 .checked_add(old_entry.path_penalty_msat)
923 .unwrap_or_else(|| u64::max_value());
924 let new_cost = cmp::max(total_fee_msat, path_htlc_minimum_msat)
925 .checked_add(path_penalty_msat)
926 .unwrap_or_else(|| u64::max_value());
928 if !old_entry.was_processed && new_cost < old_cost {
929 targets.push(new_graph_node);
930 old_entry.next_hops_fee_msat = $next_hops_fee_msat;
931 old_entry.hop_use_fee_msat = hop_use_fee_msat;
932 old_entry.total_fee_msat = total_fee_msat;
933 old_entry.node_id = $dest_node_id.clone();
934 old_entry.short_channel_id = $chan_id.clone();
935 old_entry.channel_features = $chan_features;
936 old_entry.fee_msat = 0; // This value will be later filled with hop_use_fee_msat of the following channel
937 old_entry.cltv_expiry_delta = $directional_info.cltv_expiry_delta as u32;
938 old_entry.channel_fees = $directional_info.fees;
939 old_entry.htlc_minimum_msat = $directional_info.htlc_minimum_msat;
940 old_entry.path_htlc_minimum_msat = path_htlc_minimum_msat;
941 old_entry.path_penalty_msat = path_penalty_msat;
942 #[cfg(any(test, feature = "fuzztarget"))]
944 old_entry.value_contribution_msat = value_contribution_msat;
946 did_add_update_path_to_src_node = true;
947 } else if old_entry.was_processed && new_cost < old_cost {
948 #[cfg(any(test, feature = "fuzztarget"))]
950 // If we're skipping processing a node which was previously
951 // processed even though we found another path to it with a
952 // cheaper fee, check that it was because the second path we
953 // found (which we are processing now) has a lower value
954 // contribution due to an HTLC minimum limit.
956 // e.g. take a graph with two paths from node 1 to node 2, one
957 // through channel A, and one through channel B. Channel A and
958 // B are both in the to-process heap, with their scores set by
959 // a higher htlc_minimum than fee.
960 // Channel A is processed first, and the channels onwards from
961 // node 1 are added to the to-process heap. Thereafter, we pop
962 // Channel B off of the heap, note that it has a much more
963 // restrictive htlc_maximum_msat, and recalculate the fees for
964 // all of node 1's channels using the new, reduced, amount.
966 // This would be bogus - we'd be selecting a higher-fee path
967 // with a lower htlc_maximum_msat instead of the one we'd
968 // already decided to use.
969 debug_assert!(path_htlc_minimum_msat < old_entry.path_htlc_minimum_msat);
971 value_contribution_msat + path_penalty_msat <
972 old_entry.value_contribution_msat + old_entry.path_penalty_msat
980 did_add_update_path_to_src_node
984 let empty_node_features = NodeFeatures::empty();
985 // Find ways (channels with destination) to reach a given node and store them
986 // in the corresponding data structures (routing graph etc).
987 // $fee_to_target_msat represents how much it costs to reach to this node from the payee,
988 // meaning how much will be paid in fees after this node (to the best of our knowledge).
989 // This data can later be helpful to optimize routing (pay lower fees).
990 macro_rules! add_entries_to_cheapest_to_target_node {
991 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr, $next_hops_value_contribution: expr, $next_hops_path_htlc_minimum_msat: expr, $next_hops_path_penalty_msat: expr ) => {
992 let skip_node = if let Some(elem) = dist.get_mut(&$node_id) {
993 let was_processed = elem.was_processed;
994 elem.was_processed = true;
997 // Entries are added to dist in add_entry!() when there is a channel from a node.
998 // Because there are no channels from payee, it will not have a dist entry at this point.
999 // If we're processing any other node, it is always be the result of a channel from it.
1000 assert_eq!($node_id, payee_node_id);
1005 if let Some(first_channels) = first_hop_targets.get(&$node_id) {
1006 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1007 add_entry!(first_hop, our_node_id, $node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat);
1011 let features = if let Some(node_info) = $node.announcement_info.as_ref() {
1014 &empty_node_features
1017 if !features.requires_unknown_bits() {
1018 for chan_id in $node.channels.iter() {
1019 let chan = network_channels.get(chan_id).unwrap();
1020 if !chan.features.requires_unknown_bits() {
1021 if chan.node_one == $node_id {
1022 // ie $node is one, ie next hop in A* is two, via the two_to_one channel
1023 if first_hops.is_none() || chan.node_two != our_node_id {
1024 if let Some(two_to_one) = chan.two_to_one.as_ref() {
1025 if two_to_one.enabled {
1026 add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat);
1031 if first_hops.is_none() || chan.node_one != our_node_id{
1032 if let Some(one_to_two) = chan.one_to_two.as_ref() {
1033 if one_to_two.enabled {
1034 add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.capacity_sats, &chan.features, $fee_to_target_msat, $next_hops_value_contribution, $next_hops_path_htlc_minimum_msat, $next_hops_path_penalty_msat);
1046 let mut payment_paths = Vec::<PaymentPath>::new();
1048 // TODO: diversify by nodes (so that all paths aren't doomed if one node is offline).
1049 'paths_collection: loop {
1050 // For every new path, start from scratch, except
1051 // bookkeeped_channels_liquidity_available_msat, which will improve
1052 // the further iterations of path finding. Also don't erase first_hop_targets.
1055 hit_minimum_limit = false;
1057 // If first hop is a private channel and the only way to reach the payee, this is the only
1058 // place where it could be added.
1059 if let Some(first_channels) = first_hop_targets.get(&payee_node_id) {
1060 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1061 let added = add_entry!(first_hop, our_node_id, payee_node_id, dummy_directional_info, Some(outbound_capacity_msat / 1000), features, 0, path_value_msat, 0, 0u64);
1062 log_trace!(logger, "{} direct route to payee via SCID {}", if added { "Added" } else { "Skipped" }, first_hop);
1066 // Add the payee as a target, so that the payee-to-payer
1067 // search algorithm knows what to start with.
1068 match network_nodes.get(&payee_node_id) {
1069 // The payee is not in our network graph, so nothing to add here.
1070 // There is still a chance of reaching them via last_hops though,
1071 // so don't yet fail the payment here.
1072 // If not, targets.pop() will not even let us enter the loop in step 2.
1075 add_entries_to_cheapest_to_target_node!(node, payee_node_id, 0, path_value_msat, 0, 0u64);
1080 // If a caller provided us with last hops, add them to routing targets. Since this happens
1081 // earlier than general path finding, they will be somewhat prioritized, although currently
1082 // it matters only if the fees are exactly the same.
1083 for route in payee.route_hints.iter().filter(|route| !route.0.is_empty()) {
1084 let first_hop_in_route = &(route.0)[0];
1085 let have_hop_src_in_graph =
1086 // Only add the hops in this route to our candidate set if either
1087 // we have a direct channel to the first hop or the first hop is
1088 // in the regular network graph.
1089 first_hop_targets.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some() ||
1090 network_nodes.get(&NodeId::from_pubkey(&first_hop_in_route.src_node_id)).is_some();
1091 if have_hop_src_in_graph {
1092 // We start building the path from reverse, i.e., from payee
1093 // to the first RouteHintHop in the path.
1094 let hop_iter = route.0.iter().rev();
1095 let prev_hop_iter = core::iter::once(&payee.pubkey).chain(
1096 route.0.iter().skip(1).rev().map(|hop| &hop.src_node_id));
1097 let mut hop_used = true;
1098 let mut aggregate_next_hops_fee_msat: u64 = 0;
1099 let mut aggregate_next_hops_path_htlc_minimum_msat: u64 = 0;
1100 let mut aggregate_next_hops_path_penalty_msat: u64 = 0;
1102 for (idx, (hop, prev_hop_id)) in hop_iter.zip(prev_hop_iter).enumerate() {
1103 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
1104 // really sucks, cause we're gonna need that eventually.
1105 let hop_htlc_minimum_msat: u64 = hop.htlc_minimum_msat.unwrap_or(0);
1107 let directional_info = DummyDirectionalChannelInfo {
1108 cltv_expiry_delta: hop.cltv_expiry_delta as u32,
1109 htlc_minimum_msat: hop_htlc_minimum_msat,
1110 htlc_maximum_msat: hop.htlc_maximum_msat,
1114 let reqd_channel_cap = if let Some (val) = final_value_msat.checked_add(match idx {
1116 _ => aggregate_next_hops_fee_msat.checked_add(999).unwrap_or(u64::max_value())
1117 }) { Some( val / 1000 ) } else { break; }; // converting from msat or breaking if max ~ infinity
1119 let src_node_id = NodeId::from_pubkey(&hop.src_node_id);
1120 let dest_node_id = NodeId::from_pubkey(&prev_hop_id);
1121 aggregate_next_hops_path_penalty_msat = aggregate_next_hops_path_penalty_msat
1122 .checked_add(scorer.channel_penalty_msat(hop.short_channel_id, &src_node_id, &dest_node_id))
1123 .unwrap_or_else(|| u64::max_value());
1125 // We assume that the recipient only included route hints for routes which had
1126 // sufficient value to route `final_value_msat`. Note that in the case of "0-value"
1127 // invoices where the invoice does not specify value this may not be the case, but
1128 // better to include the hints than not.
1129 if !add_entry!(hop.short_channel_id, src_node_id, dest_node_id, directional_info, reqd_channel_cap, &empty_channel_features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat) {
1130 // If this hop was not used then there is no use checking the preceding hops
1131 // in the RouteHint. We can break by just searching for a direct channel between
1132 // last checked hop and first_hop_targets
1136 // Searching for a direct channel between last checked hop and first_hop_targets
1137 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&prev_hop_id)) {
1138 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1139 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&prev_hop_id), dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat);
1147 // In the next values of the iterator, the aggregate fees already reflects
1148 // the sum of value sent from payer (final_value_msat) and routing fees
1149 // for the last node in the RouteHint. We need to just add the fees to
1150 // route through the current node so that the preceeding node (next iteration)
1152 let hops_fee = compute_fees(aggregate_next_hops_fee_msat + final_value_msat, hop.fees)
1153 .map_or(None, |inc| inc.checked_add(aggregate_next_hops_fee_msat));
1154 aggregate_next_hops_fee_msat = if let Some(val) = hops_fee { val } else { break; };
1156 let hop_htlc_minimum_msat_inc = if let Some(val) = compute_fees(aggregate_next_hops_path_htlc_minimum_msat, hop.fees) { val } else { break; };
1157 let hops_path_htlc_minimum = aggregate_next_hops_path_htlc_minimum_msat
1158 .checked_add(hop_htlc_minimum_msat_inc);
1159 aggregate_next_hops_path_htlc_minimum_msat = if let Some(val) = hops_path_htlc_minimum { cmp::max(hop_htlc_minimum_msat, val) } else { break; };
1161 if idx == route.0.len() - 1 {
1162 // The last hop in this iterator is the first hop in
1163 // overall RouteHint.
1164 // If this hop connects to a node with which we have a direct channel,
1165 // ignore the network graph and, if the last hop was added, add our
1166 // direct channel to the candidate set.
1168 // Note that we *must* check if the last hop was added as `add_entry`
1169 // always assumes that the third argument is a node to which we have a
1171 if let Some(first_channels) = first_hop_targets.get(&NodeId::from_pubkey(&hop.src_node_id)) {
1172 for (ref first_hop, ref features, ref outbound_capacity_msat, _) in first_channels {
1173 add_entry!(first_hop, our_node_id , NodeId::from_pubkey(&hop.src_node_id), dummy_directional_info, Some(outbound_capacity_msat / 1000), features, aggregate_next_hops_fee_msat, path_value_msat, aggregate_next_hops_path_htlc_minimum_msat, aggregate_next_hops_path_penalty_msat);
1181 log_trace!(logger, "Starting main path collection loop with {} nodes pre-filled from first/last hops.", targets.len());
1183 // At this point, targets are filled with the data from first and
1184 // last hops communicated by the caller, and the payment receiver.
1185 let mut found_new_path = false;
1188 // If this loop terminates due the exhaustion of targets, two situations are possible:
1189 // - not enough outgoing liquidity:
1190 // 0 < already_collected_value_msat < final_value_msat
1191 // - enough outgoing liquidity:
1192 // final_value_msat <= already_collected_value_msat < recommended_value_msat
1193 // Both these cases (and other cases except reaching recommended_value_msat) mean that
1194 // paths_collection will be stopped because found_new_path==false.
1195 // This is not necessarily a routing failure.
1196 'path_construction: while let Some(RouteGraphNode { node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat, .. }) = targets.pop() {
1198 // Since we're going payee-to-payer, hitting our node as a target means we should stop
1199 // traversing the graph and arrange the path out of what we found.
1200 if node_id == our_node_id {
1201 let mut new_entry = dist.remove(&our_node_id).unwrap();
1202 let mut ordered_hops = vec!((new_entry.clone(), NodeFeatures::empty()));
1205 let mut features_set = false;
1206 if let Some(first_channels) = first_hop_targets.get(&ordered_hops.last().unwrap().0.node_id) {
1207 for (scid, _, _, ref features) in first_channels {
1208 if *scid == ordered_hops.last().unwrap().0.short_channel_id {
1209 ordered_hops.last_mut().unwrap().1 = features.clone();
1210 features_set = true;
1216 if let Some(node) = network_nodes.get(&ordered_hops.last().unwrap().0.node_id) {
1217 if let Some(node_info) = node.announcement_info.as_ref() {
1218 ordered_hops.last_mut().unwrap().1 = node_info.features.clone();
1220 ordered_hops.last_mut().unwrap().1 = NodeFeatures::empty();
1223 // We should be able to fill in features for everything except the last
1224 // hop, if the last hop was provided via a BOLT 11 invoice (though we
1225 // should be able to extend it further as BOLT 11 does have feature
1226 // flags for the last hop node itself).
1227 assert!(ordered_hops.last().unwrap().0.node_id == payee_node_id);
1231 // Means we succesfully traversed from the payer to the payee, now
1232 // save this path for the payment route. Also, update the liquidity
1233 // remaining on the used hops, so that we take them into account
1234 // while looking for more paths.
1235 if ordered_hops.last().unwrap().0.node_id == payee_node_id {
1239 new_entry = match dist.remove(&ordered_hops.last().unwrap().0.node_id) {
1240 Some(payment_hop) => payment_hop,
1241 // We can't arrive at None because, if we ever add an entry to targets,
1242 // we also fill in the entry in dist (see add_entry!).
1243 None => unreachable!(),
1245 // We "propagate" the fees one hop backward (topologically) here,
1246 // so that fees paid for a HTLC forwarding on the current channel are
1247 // associated with the previous channel (where they will be subtracted).
1248 ordered_hops.last_mut().unwrap().0.fee_msat = new_entry.hop_use_fee_msat;
1249 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = new_entry.cltv_expiry_delta;
1250 ordered_hops.push((new_entry.clone(), NodeFeatures::empty()));
1252 ordered_hops.last_mut().unwrap().0.fee_msat = value_contribution_msat;
1253 ordered_hops.last_mut().unwrap().0.hop_use_fee_msat = 0;
1254 ordered_hops.last_mut().unwrap().0.cltv_expiry_delta = final_cltv_expiry_delta;
1256 log_trace!(logger, "Found a path back to us from the target with {} hops contributing up to {} msat: {:?}",
1257 ordered_hops.len(), value_contribution_msat, ordered_hops);
1259 let mut payment_path = PaymentPath {hops: ordered_hops};
1261 // We could have possibly constructed a slightly inconsistent path: since we reduce
1262 // value being transferred along the way, we could have violated htlc_minimum_msat
1263 // on some channels we already passed (assuming dest->source direction). Here, we
1264 // recompute the fees again, so that if that's the case, we match the currently
1265 // underpaid htlc_minimum_msat with fees.
1266 payment_path.update_value_and_recompute_fees(cmp::min(value_contribution_msat, final_value_msat));
1268 // Since a path allows to transfer as much value as
1269 // the smallest channel it has ("bottleneck"), we should recompute
1270 // the fees so sender HTLC don't overpay fees when traversing
1271 // larger channels than the bottleneck. This may happen because
1272 // when we were selecting those channels we were not aware how much value
1273 // this path will transfer, and the relative fee for them
1274 // might have been computed considering a larger value.
1275 // Remember that we used these channels so that we don't rely
1276 // on the same liquidity in future paths.
1277 let mut prevented_redundant_path_selection = false;
1278 for (payment_hop, _) in payment_path.hops.iter() {
1279 let channel_liquidity_available_msat = bookkeeped_channels_liquidity_available_msat.get_mut(&payment_hop.short_channel_id).unwrap();
1280 let mut spent_on_hop_msat = value_contribution_msat;
1281 let next_hops_fee_msat = payment_hop.next_hops_fee_msat;
1282 spent_on_hop_msat += next_hops_fee_msat;
1283 if spent_on_hop_msat == *channel_liquidity_available_msat {
1284 // If this path used all of this channel's available liquidity, we know
1285 // this path will not be selected again in the next loop iteration.
1286 prevented_redundant_path_selection = true;
1288 *channel_liquidity_available_msat -= spent_on_hop_msat;
1290 if !prevented_redundant_path_selection {
1291 // If we weren't capped by hitting a liquidity limit on a channel in the path,
1292 // we'll probably end up picking the same path again on the next iteration.
1293 // Decrease the available liquidity of a hop in the middle of the path.
1294 let victim_scid = payment_path.hops[(payment_path.hops.len() - 1) / 2].0.short_channel_id;
1295 log_trace!(logger, "Disabling channel {} for future path building iterations to avoid duplicates.", victim_scid);
1296 let victim_liquidity = bookkeeped_channels_liquidity_available_msat.get_mut(&victim_scid).unwrap();
1297 *victim_liquidity = 0;
1300 // Track the total amount all our collected paths allow to send so that we:
1301 // - know when to stop looking for more paths
1302 // - know which of the hops are useless considering how much more sats we need
1303 // (contributes_sufficient_value)
1304 already_collected_value_msat += value_contribution_msat;
1306 payment_paths.push(payment_path);
1307 found_new_path = true;
1308 break 'path_construction;
1311 // If we found a path back to the payee, we shouldn't try to process it again. This is
1312 // the equivalent of the `elem.was_processed` check in
1313 // add_entries_to_cheapest_to_target_node!() (see comment there for more info).
1314 if node_id == payee_node_id { continue 'path_construction; }
1316 // Otherwise, since the current target node is not us,
1317 // keep "unrolling" the payment graph from payee to payer by
1318 // finding a way to reach the current target from the payer side.
1319 match network_nodes.get(&node_id) {
1322 add_entries_to_cheapest_to_target_node!(node, node_id, lowest_fee_to_node, value_contribution_msat, path_htlc_minimum_msat, path_penalty_msat);
1328 // If we don't support MPP, no use trying to gather more value ever.
1329 break 'paths_collection;
1333 // Stop either when the recommended value is reached or if no new path was found in this
1335 // In the latter case, making another path finding attempt won't help,
1336 // because we deterministically terminated the search due to low liquidity.
1337 if already_collected_value_msat >= recommended_value_msat || !found_new_path {
1338 log_trace!(logger, "Have now collected {} msat (seeking {} msat) in paths. Last path loop {} a new path.",
1339 already_collected_value_msat, recommended_value_msat, if found_new_path { "found" } else { "did not find" });
1340 break 'paths_collection;
1341 } else if found_new_path && already_collected_value_msat == final_value_msat && payment_paths.len() == 1 {
1342 // Further, if this was our first walk of the graph, and we weren't limited by an
1343 // htlc_minimum_msat, return immediately because this path should suffice. If we were
1344 // limited by an htlc_minimum_msat value, find another path with a higher value,
1345 // potentially allowing us to pay fees to meet the htlc_minimum on the new path while
1346 // still keeping a lower total fee than this path.
1347 if !hit_minimum_limit {
1348 log_trace!(logger, "Collected exactly our payment amount on the first pass, without hitting an htlc_minimum_msat limit, exiting.");
1349 break 'paths_collection;
1351 log_trace!(logger, "Collected our payment amount on the first pass, but running again to collect extra paths with a potentially higher limit.");
1352 path_value_msat = recommended_value_msat;
1357 if payment_paths.len() == 0 {
1358 return Err(LightningError{err: "Failed to find a path to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1361 if already_collected_value_msat < final_value_msat {
1362 return Err(LightningError{err: "Failed to find a sufficient route to the given destination".to_owned(), action: ErrorAction::IgnoreError});
1365 // Sort by total fees and take the best paths.
1366 payment_paths.sort_by_key(|path| path.get_total_fee_paid_msat());
1367 if payment_paths.len() > 50 {
1368 payment_paths.truncate(50);
1371 // Draw multiple sufficient routes by randomly combining the selected paths.
1372 let mut drawn_routes = Vec::new();
1373 for i in 0..payment_paths.len() {
1374 let mut cur_route = Vec::<PaymentPath>::new();
1375 let mut aggregate_route_value_msat = 0;
1378 // TODO: real random shuffle
1379 // Currently just starts with i_th and goes up to i-1_th in a looped way.
1380 let cur_payment_paths = [&payment_paths[i..], &payment_paths[..i]].concat();
1383 for payment_path in cur_payment_paths {
1384 cur_route.push(payment_path.clone());
1385 aggregate_route_value_msat += payment_path.get_value_msat();
1386 if aggregate_route_value_msat > final_value_msat {
1387 // Last path likely overpaid. Substract it from the most expensive
1388 // (in terms of proportional fee) path in this route and recompute fees.
1389 // This might be not the most economically efficient way, but fewer paths
1390 // also makes routing more reliable.
1391 let mut overpaid_value_msat = aggregate_route_value_msat - final_value_msat;
1393 // First, drop some expensive low-value paths entirely if possible.
1394 // Sort by value so that we drop many really-low values first, since
1395 // fewer paths is better: the payment is less likely to fail.
1396 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1397 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1398 cur_route.sort_by_key(|path| path.get_value_msat());
1399 // We should make sure that at least 1 path left.
1400 let mut paths_left = cur_route.len();
1401 cur_route.retain(|path| {
1402 if paths_left == 1 {
1405 let mut keep = true;
1406 let path_value_msat = path.get_value_msat();
1407 if path_value_msat <= overpaid_value_msat {
1409 overpaid_value_msat -= path_value_msat;
1415 if overpaid_value_msat == 0 {
1419 assert!(cur_route.len() > 0);
1422 // Now, substract the overpaid value from the most-expensive path.
1423 // TODO: this could also be optimized by also sorting by feerate_per_sat_routed,
1424 // so that the sender pays less fees overall. And also htlc_minimum_msat.
1425 cur_route.sort_by_key(|path| { path.hops.iter().map(|hop| hop.0.channel_fees.proportional_millionths as u64).sum::<u64>() });
1426 let expensive_payment_path = cur_route.first_mut().unwrap();
1427 // We already dropped all the small channels above, meaning all the
1428 // remaining channels are larger than remaining overpaid_value_msat.
1429 // Thus, this can't be negative.
1430 let expensive_path_new_value_msat = expensive_payment_path.get_value_msat() - overpaid_value_msat;
1431 expensive_payment_path.update_value_and_recompute_fees(expensive_path_new_value_msat);
1435 drawn_routes.push(cur_route);
1439 // Select the best route by lowest total fee.
1440 drawn_routes.sort_by_key(|paths| paths.iter().map(|path| path.get_total_fee_paid_msat()).sum::<u64>());
1441 let mut selected_paths = Vec::<Vec<Result<RouteHop, LightningError>>>::new();
1442 for payment_path in drawn_routes.first().unwrap() {
1443 selected_paths.push(payment_path.hops.iter().map(|(payment_hop, node_features)| {
1445 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)})?,
1446 node_features: node_features.clone(),
1447 short_channel_id: payment_hop.short_channel_id,
1448 channel_features: payment_hop.channel_features.clone(),
1449 fee_msat: payment_hop.fee_msat,
1450 cltv_expiry_delta: payment_hop.cltv_expiry_delta,
1455 if let Some(features) = &payee.features {
1456 for path in selected_paths.iter_mut() {
1457 if let Ok(route_hop) = path.last_mut().unwrap() {
1458 route_hop.node_features = features.to_context();
1464 paths: selected_paths.into_iter().map(|path| path.into_iter().collect()).collect::<Result<Vec<_>, _>>()?,
1465 payee: Some(payee.clone()),
1467 log_info!(logger, "Got route to {}: {}", payee.pubkey, log_route!(route));
1474 use routing::network_graph::{NetworkGraph, NetGraphMsgHandler, NodeId};
1475 use routing::router::{get_route, Payee, Route, RouteHint, RouteHintHop, RouteHop, RoutingFees};
1476 use chain::transaction::OutPoint;
1477 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
1478 use ln::msgs::{ErrorAction, LightningError, OptionalField, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
1479 NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
1480 use ln::channelmanager;
1481 use util::test_utils;
1482 use util::ser::Writeable;
1484 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
1485 use bitcoin::hashes::Hash;
1486 use bitcoin::network::constants::Network;
1487 use bitcoin::blockdata::constants::genesis_block;
1488 use bitcoin::blockdata::script::Builder;
1489 use bitcoin::blockdata::opcodes;
1490 use bitcoin::blockdata::transaction::TxOut;
1494 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
1495 use bitcoin::secp256k1::{Secp256k1, All};
1498 use sync::{self, Arc};
1500 fn get_channel_details(short_channel_id: Option<u64>, node_id: PublicKey,
1501 features: InitFeatures, outbound_capacity_msat: u64) -> channelmanager::ChannelDetails {
1502 channelmanager::ChannelDetails {
1503 channel_id: [0; 32],
1504 counterparty: channelmanager::ChannelCounterparty {
1507 unspendable_punishment_reserve: 0,
1508 forwarding_info: None,
1510 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
1512 channel_value_satoshis: 0,
1514 outbound_capacity_msat,
1515 inbound_capacity_msat: 42,
1516 unspendable_punishment_reserve: None,
1517 confirmations_required: None,
1518 force_close_spend_delay: None,
1519 is_outbound: true, is_funding_locked: true,
1520 is_usable: true, is_public: true,
1524 // Using the same keys for LN and BTC ids
1526 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1527 secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey, node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64
1529 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
1530 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
1532 let unsigned_announcement = UnsignedChannelAnnouncement {
1534 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1538 bitcoin_key_1: node_id_1,
1539 bitcoin_key_2: node_id_2,
1540 excess_data: Vec::new(),
1543 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1544 let valid_announcement = ChannelAnnouncement {
1545 node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1546 node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1547 bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
1548 bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
1549 contents: unsigned_announcement.clone(),
1551 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
1552 Ok(res) => assert!(res),
1558 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1559 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate
1561 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
1562 let valid_channel_update = ChannelUpdate {
1563 signature: secp_ctx.sign(&msghash, node_privkey),
1564 contents: update.clone()
1567 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
1568 Ok(res) => assert!(res),
1573 fn add_or_update_node(
1574 net_graph_msg_handler: &NetGraphMsgHandler<Arc<NetworkGraph>, Arc<test_utils::TestChainSource>, Arc<test_utils::TestLogger>>,
1575 secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, features: NodeFeatures, timestamp: u32
1577 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
1578 let unsigned_announcement = UnsignedNodeAnnouncement {
1584 addresses: Vec::new(),
1585 excess_address_data: Vec::new(),
1586 excess_data: Vec::new(),
1588 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
1589 let valid_announcement = NodeAnnouncement {
1590 signature: secp_ctx.sign(&msghash, node_privkey),
1591 contents: unsigned_announcement.clone()
1594 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
1600 fn get_nodes(secp_ctx: &Secp256k1<All>) -> (SecretKey, PublicKey, Vec<SecretKey>, Vec<PublicKey>) {
1601 let privkeys: Vec<SecretKey> = (2..10).map(|i| {
1602 SecretKey::from_slice(&hex::decode(format!("{:02}", i).repeat(32)).unwrap()[..]).unwrap()
1605 let pubkeys = privkeys.iter().map(|secret| PublicKey::from_secret_key(&secp_ctx, secret)).collect();
1607 let our_privkey = SecretKey::from_slice(&hex::decode("01".repeat(32)).unwrap()[..]).unwrap();
1608 let our_id = PublicKey::from_secret_key(&secp_ctx, &our_privkey);
1610 (our_privkey, our_id, privkeys, pubkeys)
1613 fn id_to_feature_flags(id: u8) -> Vec<u8> {
1614 // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
1615 // test for it later.
1616 let idx = (id - 1) * 2 + 1;
1618 vec![1 << (idx - 8*3), 0, 0, 0]
1619 } else if idx > 8*2 {
1620 vec![1 << (idx - 8*2), 0, 0]
1621 } else if idx > 8*1 {
1622 vec![1 << (idx - 8*1), 0]
1628 fn build_graph() -> (
1630 sync::Arc<NetworkGraph>,
1631 NetGraphMsgHandler<sync::Arc<NetworkGraph>, sync::Arc<test_utils::TestChainSource>, sync::Arc<crate::util::test_utils::TestLogger>>,
1632 sync::Arc<test_utils::TestChainSource>,
1633 sync::Arc<test_utils::TestLogger>,
1635 let secp_ctx = Secp256k1::new();
1636 let logger = Arc::new(test_utils::TestLogger::new());
1637 let chain_monitor = Arc::new(test_utils::TestChainSource::new(Network::Testnet));
1638 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
1639 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
1640 // Build network from our_id to node6:
1642 // -1(1)2- node0 -1(3)2-
1644 // our_id -1(12)2- node7 -1(13)2--- node2
1646 // -1(2)2- node1 -1(4)2-
1649 // chan1 1-to-2: disabled
1650 // chan1 2-to-1: enabled, 0 fee
1652 // chan2 1-to-2: enabled, ignored fee
1653 // chan2 2-to-1: enabled, 0 fee
1655 // chan3 1-to-2: enabled, 0 fee
1656 // chan3 2-to-1: enabled, 100 msat fee
1658 // chan4 1-to-2: enabled, 100% fee
1659 // chan4 2-to-1: enabled, 0 fee
1661 // chan12 1-to-2: enabled, ignored fee
1662 // chan12 2-to-1: enabled, 0 fee
1664 // chan13 1-to-2: enabled, 200% fee
1665 // chan13 2-to-1: enabled, 0 fee
1668 // -1(5)2- node3 -1(8)2--
1672 // node2--1(6)2- node4 -1(9)2--- node6 (not in global route map)
1674 // -1(7)2- node5 -1(10)2-
1676 // Channels 5, 8, 9 and 10 are private channels.
1678 // chan5 1-to-2: enabled, 100 msat fee
1679 // chan5 2-to-1: enabled, 0 fee
1681 // chan6 1-to-2: enabled, 0 fee
1682 // chan6 2-to-1: enabled, 0 fee
1684 // chan7 1-to-2: enabled, 100% fee
1685 // chan7 2-to-1: enabled, 0 fee
1687 // chan8 1-to-2: enabled, variable fee (0 then 1000 msat)
1688 // chan8 2-to-1: enabled, 0 fee
1690 // chan9 1-to-2: enabled, 1001 msat fee
1691 // chan9 2-to-1: enabled, 0 fee
1693 // chan10 1-to-2: enabled, 0 fee
1694 // chan10 2-to-1: enabled, 0 fee
1696 // chan11 1-to-2: enabled, 0 fee
1697 // chan11 2-to-1: enabled, 0 fee
1699 let (our_privkey, _, privkeys, _) = get_nodes(&secp_ctx);
1701 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[0], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
1702 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1703 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1704 short_channel_id: 1,
1707 cltv_expiry_delta: 0,
1708 htlc_minimum_msat: 0,
1709 htlc_maximum_msat: OptionalField::Absent,
1711 fee_proportional_millionths: 0,
1712 excess_data: Vec::new()
1715 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
1717 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
1718 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1719 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1720 short_channel_id: 2,
1723 cltv_expiry_delta: u16::max_value(),
1724 htlc_minimum_msat: 0,
1725 htlc_maximum_msat: OptionalField::Absent,
1726 fee_base_msat: u32::max_value(),
1727 fee_proportional_millionths: u32::max_value(),
1728 excess_data: Vec::new()
1730 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1731 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1732 short_channel_id: 2,
1735 cltv_expiry_delta: 0,
1736 htlc_minimum_msat: 0,
1737 htlc_maximum_msat: OptionalField::Absent,
1739 fee_proportional_millionths: 0,
1740 excess_data: Vec::new()
1743 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
1745 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[7], ChannelFeatures::from_le_bytes(id_to_feature_flags(12)), 12);
1746 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
1747 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1748 short_channel_id: 12,
1751 cltv_expiry_delta: u16::max_value(),
1752 htlc_minimum_msat: 0,
1753 htlc_maximum_msat: OptionalField::Absent,
1754 fee_base_msat: u32::max_value(),
1755 fee_proportional_millionths: u32::max_value(),
1756 excess_data: Vec::new()
1758 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1759 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1760 short_channel_id: 12,
1763 cltv_expiry_delta: 0,
1764 htlc_minimum_msat: 0,
1765 htlc_maximum_msat: OptionalField::Absent,
1767 fee_proportional_millionths: 0,
1768 excess_data: Vec::new()
1771 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], NodeFeatures::from_le_bytes(id_to_feature_flags(8)), 0);
1773 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
1774 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
1775 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1776 short_channel_id: 3,
1779 cltv_expiry_delta: (3 << 8) | 1,
1780 htlc_minimum_msat: 0,
1781 htlc_maximum_msat: OptionalField::Absent,
1783 fee_proportional_millionths: 0,
1784 excess_data: Vec::new()
1786 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1787 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1788 short_channel_id: 3,
1791 cltv_expiry_delta: (3 << 8) | 2,
1792 htlc_minimum_msat: 0,
1793 htlc_maximum_msat: OptionalField::Absent,
1795 fee_proportional_millionths: 0,
1796 excess_data: Vec::new()
1799 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
1800 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
1801 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1802 short_channel_id: 4,
1805 cltv_expiry_delta: (4 << 8) | 1,
1806 htlc_minimum_msat: 0,
1807 htlc_maximum_msat: OptionalField::Absent,
1809 fee_proportional_millionths: 1000000,
1810 excess_data: Vec::new()
1812 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1813 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1814 short_channel_id: 4,
1817 cltv_expiry_delta: (4 << 8) | 2,
1818 htlc_minimum_msat: 0,
1819 htlc_maximum_msat: OptionalField::Absent,
1821 fee_proportional_millionths: 0,
1822 excess_data: Vec::new()
1825 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(13)), 13);
1826 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
1827 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1828 short_channel_id: 13,
1831 cltv_expiry_delta: (13 << 8) | 1,
1832 htlc_minimum_msat: 0,
1833 htlc_maximum_msat: OptionalField::Absent,
1835 fee_proportional_millionths: 2000000,
1836 excess_data: Vec::new()
1838 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1840 short_channel_id: 13,
1843 cltv_expiry_delta: (13 << 8) | 2,
1844 htlc_minimum_msat: 0,
1845 htlc_maximum_msat: OptionalField::Absent,
1847 fee_proportional_millionths: 0,
1848 excess_data: Vec::new()
1851 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
1853 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
1854 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1855 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1856 short_channel_id: 6,
1859 cltv_expiry_delta: (6 << 8) | 1,
1860 htlc_minimum_msat: 0,
1861 htlc_maximum_msat: OptionalField::Absent,
1863 fee_proportional_millionths: 0,
1864 excess_data: Vec::new()
1866 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1867 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1868 short_channel_id: 6,
1871 cltv_expiry_delta: (6 << 8) | 2,
1872 htlc_minimum_msat: 0,
1873 htlc_maximum_msat: OptionalField::Absent,
1875 fee_proportional_millionths: 0,
1876 excess_data: Vec::new(),
1879 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(11)), 11);
1880 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
1881 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1882 short_channel_id: 11,
1885 cltv_expiry_delta: (11 << 8) | 1,
1886 htlc_minimum_msat: 0,
1887 htlc_maximum_msat: OptionalField::Absent,
1889 fee_proportional_millionths: 0,
1890 excess_data: Vec::new()
1892 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
1893 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1894 short_channel_id: 11,
1897 cltv_expiry_delta: (11 << 8) | 2,
1898 htlc_minimum_msat: 0,
1899 htlc_maximum_msat: OptionalField::Absent,
1901 fee_proportional_millionths: 0,
1902 excess_data: Vec::new()
1905 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(5)), 0);
1907 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
1909 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[5], ChannelFeatures::from_le_bytes(id_to_feature_flags(7)), 7);
1910 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
1911 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1912 short_channel_id: 7,
1915 cltv_expiry_delta: (7 << 8) | 1,
1916 htlc_minimum_msat: 0,
1917 htlc_maximum_msat: OptionalField::Absent,
1919 fee_proportional_millionths: 1000000,
1920 excess_data: Vec::new()
1922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[5], UnsignedChannelUpdate {
1923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
1924 short_channel_id: 7,
1927 cltv_expiry_delta: (7 << 8) | 2,
1928 htlc_minimum_msat: 0,
1929 htlc_maximum_msat: OptionalField::Absent,
1931 fee_proportional_millionths: 0,
1932 excess_data: Vec::new()
1935 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[5], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
1937 (secp_ctx, network_graph, net_graph_msg_handler, chain_monitor, logger)
1941 fn simple_route_test() {
1942 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1943 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1944 let payee = Payee::new(nodes[2]);
1945 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1947 // Simple route to 2 via 1
1949 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 0, 42, Arc::clone(&logger), &scorer) {
1950 assert_eq!(err, "Cannot send a payment of 0 msat");
1951 } else { panic!(); }
1953 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1954 assert_eq!(route.paths[0].len(), 2);
1956 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
1957 assert_eq!(route.paths[0][0].short_channel_id, 2);
1958 assert_eq!(route.paths[0][0].fee_msat, 100);
1959 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1960 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
1961 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
1963 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
1964 assert_eq!(route.paths[0][1].short_channel_id, 4);
1965 assert_eq!(route.paths[0][1].fee_msat, 100);
1966 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1967 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
1968 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
1972 fn invalid_first_hop_test() {
1973 let (secp_ctx, network_graph, _, _, logger) = build_graph();
1974 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
1975 let payee = Payee::new(nodes[2]);
1976 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1978 // Simple route to 2 via 1
1980 let our_chans = vec![get_channel_details(Some(2), our_id, InitFeatures::from_le_bytes(vec![0b11]), 100000)];
1982 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer) {
1983 assert_eq!(err, "First hop cannot have our_node_pubkey as a destination.");
1984 } else { panic!(); }
1986 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
1987 assert_eq!(route.paths[0].len(), 2);
1991 fn htlc_minimum_test() {
1992 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
1993 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
1994 let payee = Payee::new(nodes[2]);
1995 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
1997 // Simple route to 2 via 1
1999 // Disable other paths
2000 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2001 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2002 short_channel_id: 12,
2004 flags: 2, // to disable
2005 cltv_expiry_delta: 0,
2006 htlc_minimum_msat: 0,
2007 htlc_maximum_msat: OptionalField::Absent,
2009 fee_proportional_millionths: 0,
2010 excess_data: Vec::new()
2012 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
2013 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2014 short_channel_id: 3,
2016 flags: 2, // to disable
2017 cltv_expiry_delta: 0,
2018 htlc_minimum_msat: 0,
2019 htlc_maximum_msat: OptionalField::Absent,
2021 fee_proportional_millionths: 0,
2022 excess_data: Vec::new()
2024 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2025 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2026 short_channel_id: 13,
2028 flags: 2, // to disable
2029 cltv_expiry_delta: 0,
2030 htlc_minimum_msat: 0,
2031 htlc_maximum_msat: OptionalField::Absent,
2033 fee_proportional_millionths: 0,
2034 excess_data: Vec::new()
2036 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2037 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2038 short_channel_id: 6,
2040 flags: 2, // to disable
2041 cltv_expiry_delta: 0,
2042 htlc_minimum_msat: 0,
2043 htlc_maximum_msat: OptionalField::Absent,
2045 fee_proportional_millionths: 0,
2046 excess_data: Vec::new()
2048 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2049 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2050 short_channel_id: 7,
2052 flags: 2, // to disable
2053 cltv_expiry_delta: 0,
2054 htlc_minimum_msat: 0,
2055 htlc_maximum_msat: OptionalField::Absent,
2057 fee_proportional_millionths: 0,
2058 excess_data: Vec::new()
2061 // Check against amount_to_transfer_over_msat.
2062 // Set minimal HTLC of 200_000_000 msat.
2063 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2064 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2065 short_channel_id: 2,
2068 cltv_expiry_delta: 0,
2069 htlc_minimum_msat: 200_000_000,
2070 htlc_maximum_msat: OptionalField::Absent,
2072 fee_proportional_millionths: 0,
2073 excess_data: Vec::new()
2076 // Second hop only allows to forward 199_999_999 at most, thus not allowing the first hop to
2078 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2080 short_channel_id: 4,
2083 cltv_expiry_delta: 0,
2084 htlc_minimum_msat: 0,
2085 htlc_maximum_msat: OptionalField::Present(199_999_999),
2087 fee_proportional_millionths: 0,
2088 excess_data: Vec::new()
2091 // Not possible to send 199_999_999, because the minimum on channel=2 is 200_000_000.
2092 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer) {
2093 assert_eq!(err, "Failed to find a path to the given destination");
2094 } else { panic!(); }
2096 // Lift the restriction on the first hop.
2097 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2098 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2099 short_channel_id: 2,
2102 cltv_expiry_delta: 0,
2103 htlc_minimum_msat: 0,
2104 htlc_maximum_msat: OptionalField::Absent,
2106 fee_proportional_millionths: 0,
2107 excess_data: Vec::new()
2110 // A payment above the minimum should pass
2111 let route = get_route(&our_id, &payee, &network_graph, None, 199_999_999, 42, Arc::clone(&logger), &scorer).unwrap();
2112 assert_eq!(route.paths[0].len(), 2);
2116 fn htlc_minimum_overpay_test() {
2117 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2118 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2119 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2120 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2122 // A route to node#2 via two paths.
2123 // One path allows transferring 35-40 sats, another one also allows 35-40 sats.
2124 // Thus, they can't send 60 without overpaying.
2125 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2126 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2127 short_channel_id: 2,
2130 cltv_expiry_delta: 0,
2131 htlc_minimum_msat: 35_000,
2132 htlc_maximum_msat: OptionalField::Present(40_000),
2134 fee_proportional_millionths: 0,
2135 excess_data: Vec::new()
2137 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2138 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2139 short_channel_id: 12,
2142 cltv_expiry_delta: 0,
2143 htlc_minimum_msat: 35_000,
2144 htlc_maximum_msat: OptionalField::Present(40_000),
2146 fee_proportional_millionths: 0,
2147 excess_data: Vec::new()
2151 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
2152 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2153 short_channel_id: 13,
2156 cltv_expiry_delta: 0,
2157 htlc_minimum_msat: 0,
2158 htlc_maximum_msat: OptionalField::Absent,
2160 fee_proportional_millionths: 0,
2161 excess_data: Vec::new()
2163 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2164 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2165 short_channel_id: 4,
2168 cltv_expiry_delta: 0,
2169 htlc_minimum_msat: 0,
2170 htlc_maximum_msat: OptionalField::Absent,
2172 fee_proportional_millionths: 0,
2173 excess_data: Vec::new()
2176 // Disable other paths
2177 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2178 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2179 short_channel_id: 1,
2181 flags: 2, // to disable
2182 cltv_expiry_delta: 0,
2183 htlc_minimum_msat: 0,
2184 htlc_maximum_msat: OptionalField::Absent,
2186 fee_proportional_millionths: 0,
2187 excess_data: Vec::new()
2190 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2191 // Overpay fees to hit htlc_minimum_msat.
2192 let overpaid_fees = route.paths[0][0].fee_msat + route.paths[1][0].fee_msat;
2193 // TODO: this could be better balanced to overpay 10k and not 15k.
2194 assert_eq!(overpaid_fees, 15_000);
2196 // Now, test that if there are 2 paths, a "cheaper" by fee path wouldn't be prioritized
2197 // while taking even more fee to match htlc_minimum_msat.
2198 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2199 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2200 short_channel_id: 12,
2203 cltv_expiry_delta: 0,
2204 htlc_minimum_msat: 65_000,
2205 htlc_maximum_msat: OptionalField::Present(80_000),
2207 fee_proportional_millionths: 0,
2208 excess_data: Vec::new()
2210 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2211 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2212 short_channel_id: 2,
2215 cltv_expiry_delta: 0,
2216 htlc_minimum_msat: 0,
2217 htlc_maximum_msat: OptionalField::Absent,
2219 fee_proportional_millionths: 0,
2220 excess_data: Vec::new()
2222 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2223 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2224 short_channel_id: 4,
2227 cltv_expiry_delta: 0,
2228 htlc_minimum_msat: 0,
2229 htlc_maximum_msat: OptionalField::Absent,
2231 fee_proportional_millionths: 100_000,
2232 excess_data: Vec::new()
2235 let route = get_route(&our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer).unwrap();
2236 // Fine to overpay for htlc_minimum_msat if it allows us to save fee.
2237 assert_eq!(route.paths.len(), 1);
2238 assert_eq!(route.paths[0][0].short_channel_id, 12);
2239 let fees = route.paths[0][0].fee_msat;
2240 assert_eq!(fees, 5_000);
2242 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
2243 // Not fine to overpay for htlc_minimum_msat if it requires paying more than fee on
2244 // the other channel.
2245 assert_eq!(route.paths.len(), 1);
2246 assert_eq!(route.paths[0][0].short_channel_id, 2);
2247 let fees = route.paths[0][0].fee_msat;
2248 assert_eq!(fees, 5_000);
2252 fn disable_channels_test() {
2253 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2254 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2255 let payee = Payee::new(nodes[2]);
2256 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2258 // // Disable channels 4 and 12 by flags=2
2259 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
2260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2261 short_channel_id: 4,
2263 flags: 2, // to disable
2264 cltv_expiry_delta: 0,
2265 htlc_minimum_msat: 0,
2266 htlc_maximum_msat: OptionalField::Absent,
2268 fee_proportional_millionths: 0,
2269 excess_data: Vec::new()
2271 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
2272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2273 short_channel_id: 12,
2275 flags: 2, // to disable
2276 cltv_expiry_delta: 0,
2277 htlc_minimum_msat: 0,
2278 htlc_maximum_msat: OptionalField::Absent,
2280 fee_proportional_millionths: 0,
2281 excess_data: Vec::new()
2284 // If all the channels require some features we don't understand, route should fail
2285 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2286 assert_eq!(err, "Failed to find a path to the given destination");
2287 } else { panic!(); }
2289 // If we specify a channel to node7, that overrides our local channel view and that gets used
2290 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2291 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2292 assert_eq!(route.paths[0].len(), 2);
2294 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2295 assert_eq!(route.paths[0][0].short_channel_id, 42);
2296 assert_eq!(route.paths[0][0].fee_msat, 200);
2297 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2298 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2299 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2301 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2302 assert_eq!(route.paths[0][1].short_channel_id, 13);
2303 assert_eq!(route.paths[0][1].fee_msat, 100);
2304 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2305 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2306 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2310 fn disable_node_test() {
2311 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2312 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2313 let payee = Payee::new(nodes[2]);
2314 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2316 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
2317 let unknown_features = NodeFeatures::known().set_unknown_feature_required();
2318 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[0], unknown_features.clone(), 1);
2319 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], unknown_features.clone(), 1);
2320 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[7], unknown_features.clone(), 1);
2322 // If all nodes require some features we don't understand, route should fail
2323 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2324 assert_eq!(err, "Failed to find a path to the given destination");
2325 } else { panic!(); }
2327 // If we specify a channel to node7, that overrides our local channel view and that gets used
2328 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2329 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2330 assert_eq!(route.paths[0].len(), 2);
2332 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2333 assert_eq!(route.paths[0][0].short_channel_id, 42);
2334 assert_eq!(route.paths[0][0].fee_msat, 200);
2335 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2336 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
2337 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2339 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2340 assert_eq!(route.paths[0][1].short_channel_id, 13);
2341 assert_eq!(route.paths[0][1].fee_msat, 100);
2342 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2343 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2344 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2346 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
2347 // naively) assume that the user checked the feature bits on the invoice, which override
2348 // the node_announcement.
2352 fn our_chans_test() {
2353 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2354 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2355 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2357 // Route to 1 via 2 and 3 because our channel to 1 is disabled
2358 let payee = Payee::new(nodes[0]);
2359 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2360 assert_eq!(route.paths[0].len(), 3);
2362 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2363 assert_eq!(route.paths[0][0].short_channel_id, 2);
2364 assert_eq!(route.paths[0][0].fee_msat, 200);
2365 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2366 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2367 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2369 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2370 assert_eq!(route.paths[0][1].short_channel_id, 4);
2371 assert_eq!(route.paths[0][1].fee_msat, 100);
2372 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
2373 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2374 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2376 assert_eq!(route.paths[0][2].pubkey, nodes[0]);
2377 assert_eq!(route.paths[0][2].short_channel_id, 3);
2378 assert_eq!(route.paths[0][2].fee_msat, 100);
2379 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
2380 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(1));
2381 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(3));
2383 // If we specify a channel to node7, that overrides our local channel view and that gets used
2384 let payee = Payee::new(nodes[2]);
2385 let our_chans = vec![get_channel_details(Some(42), nodes[7].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2386 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2387 assert_eq!(route.paths[0].len(), 2);
2389 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
2390 assert_eq!(route.paths[0][0].short_channel_id, 42);
2391 assert_eq!(route.paths[0][0].fee_msat, 200);
2392 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
2393 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2394 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2396 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2397 assert_eq!(route.paths[0][1].short_channel_id, 13);
2398 assert_eq!(route.paths[0][1].fee_msat, 100);
2399 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2400 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2401 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
2404 fn last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2405 let zero_fees = RoutingFees {
2407 proportional_millionths: 0,
2409 vec![RouteHint(vec![RouteHintHop {
2410 src_node_id: nodes[3],
2411 short_channel_id: 8,
2413 cltv_expiry_delta: (8 << 8) | 1,
2414 htlc_minimum_msat: None,
2415 htlc_maximum_msat: None,
2417 ]), RouteHint(vec![RouteHintHop {
2418 src_node_id: nodes[4],
2419 short_channel_id: 9,
2422 proportional_millionths: 0,
2424 cltv_expiry_delta: (9 << 8) | 1,
2425 htlc_minimum_msat: None,
2426 htlc_maximum_msat: None,
2427 }]), RouteHint(vec![RouteHintHop {
2428 src_node_id: nodes[5],
2429 short_channel_id: 10,
2431 cltv_expiry_delta: (10 << 8) | 1,
2432 htlc_minimum_msat: None,
2433 htlc_maximum_msat: None,
2437 fn last_hops_multi_private_channels(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2438 let zero_fees = RoutingFees {
2440 proportional_millionths: 0,
2442 vec![RouteHint(vec![RouteHintHop {
2443 src_node_id: nodes[2],
2444 short_channel_id: 5,
2447 proportional_millionths: 0,
2449 cltv_expiry_delta: (5 << 8) | 1,
2450 htlc_minimum_msat: None,
2451 htlc_maximum_msat: None,
2453 src_node_id: nodes[3],
2454 short_channel_id: 8,
2456 cltv_expiry_delta: (8 << 8) | 1,
2457 htlc_minimum_msat: None,
2458 htlc_maximum_msat: None,
2460 ]), RouteHint(vec![RouteHintHop {
2461 src_node_id: nodes[4],
2462 short_channel_id: 9,
2465 proportional_millionths: 0,
2467 cltv_expiry_delta: (9 << 8) | 1,
2468 htlc_minimum_msat: None,
2469 htlc_maximum_msat: None,
2470 }]), RouteHint(vec![RouteHintHop {
2471 src_node_id: nodes[5],
2472 short_channel_id: 10,
2474 cltv_expiry_delta: (10 << 8) | 1,
2475 htlc_minimum_msat: None,
2476 htlc_maximum_msat: None,
2481 fn partial_route_hint_test() {
2482 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2483 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2484 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2486 // Simple test across 2, 3, 5, and 4 via a last_hop channel
2487 // Tests the behaviour when the RouteHint contains a suboptimal hop.
2488 // RouteHint may be partially used by the algo to build the best path.
2490 // First check that last hop can't have its source as the payee.
2491 let invalid_last_hop = RouteHint(vec![RouteHintHop {
2492 src_node_id: nodes[6],
2493 short_channel_id: 8,
2496 proportional_millionths: 0,
2498 cltv_expiry_delta: (8 << 8) | 1,
2499 htlc_minimum_msat: None,
2500 htlc_maximum_msat: None,
2503 let mut invalid_last_hops = last_hops_multi_private_channels(&nodes);
2504 invalid_last_hops.push(invalid_last_hop);
2506 let payee = Payee::new(nodes[6]).with_route_hints(invalid_last_hops);
2507 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer) {
2508 assert_eq!(err, "Route hint cannot have the payee as the source.");
2509 } else { panic!(); }
2512 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_multi_private_channels(&nodes));
2513 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2514 assert_eq!(route.paths[0].len(), 5);
2516 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2517 assert_eq!(route.paths[0][0].short_channel_id, 2);
2518 assert_eq!(route.paths[0][0].fee_msat, 100);
2519 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2520 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2521 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2523 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2524 assert_eq!(route.paths[0][1].short_channel_id, 4);
2525 assert_eq!(route.paths[0][1].fee_msat, 0);
2526 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2527 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2528 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2530 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2531 assert_eq!(route.paths[0][2].short_channel_id, 6);
2532 assert_eq!(route.paths[0][2].fee_msat, 0);
2533 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2534 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2535 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2537 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2538 assert_eq!(route.paths[0][3].short_channel_id, 11);
2539 assert_eq!(route.paths[0][3].fee_msat, 0);
2540 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2541 // If we have a peer in the node map, we'll use their features here since we don't have
2542 // a way of figuring out their features from the invoice:
2543 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2544 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2546 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2547 assert_eq!(route.paths[0][4].short_channel_id, 8);
2548 assert_eq!(route.paths[0][4].fee_msat, 100);
2549 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2550 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2551 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2554 fn empty_last_hop(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2555 let zero_fees = RoutingFees {
2557 proportional_millionths: 0,
2559 vec![RouteHint(vec![RouteHintHop {
2560 src_node_id: nodes[3],
2561 short_channel_id: 8,
2563 cltv_expiry_delta: (8 << 8) | 1,
2564 htlc_minimum_msat: None,
2565 htlc_maximum_msat: None,
2566 }]), RouteHint(vec![
2568 ]), RouteHint(vec![RouteHintHop {
2569 src_node_id: nodes[5],
2570 short_channel_id: 10,
2572 cltv_expiry_delta: (10 << 8) | 1,
2573 htlc_minimum_msat: None,
2574 htlc_maximum_msat: None,
2579 fn ignores_empty_last_hops_test() {
2580 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2581 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2582 let payee = Payee::new(nodes[6]).with_route_hints(empty_last_hop(&nodes));
2583 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2585 // Test handling of an empty RouteHint passed in Invoice.
2587 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2588 assert_eq!(route.paths[0].len(), 5);
2590 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2591 assert_eq!(route.paths[0][0].short_channel_id, 2);
2592 assert_eq!(route.paths[0][0].fee_msat, 100);
2593 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2594 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2595 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2597 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2598 assert_eq!(route.paths[0][1].short_channel_id, 4);
2599 assert_eq!(route.paths[0][1].fee_msat, 0);
2600 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2601 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2602 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2604 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2605 assert_eq!(route.paths[0][2].short_channel_id, 6);
2606 assert_eq!(route.paths[0][2].fee_msat, 0);
2607 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2608 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2609 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2611 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2612 assert_eq!(route.paths[0][3].short_channel_id, 11);
2613 assert_eq!(route.paths[0][3].fee_msat, 0);
2614 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2615 // If we have a peer in the node map, we'll use their features here since we don't have
2616 // a way of figuring out their features from the invoice:
2617 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2618 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2620 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2621 assert_eq!(route.paths[0][4].short_channel_id, 8);
2622 assert_eq!(route.paths[0][4].fee_msat, 100);
2623 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2624 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2625 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2628 fn multi_hint_last_hops(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2629 let zero_fees = RoutingFees {
2631 proportional_millionths: 0,
2633 vec![RouteHint(vec![RouteHintHop {
2634 src_node_id: nodes[2],
2635 short_channel_id: 5,
2638 proportional_millionths: 0,
2640 cltv_expiry_delta: (5 << 8) | 1,
2641 htlc_minimum_msat: None,
2642 htlc_maximum_msat: None,
2644 src_node_id: nodes[3],
2645 short_channel_id: 8,
2647 cltv_expiry_delta: (8 << 8) | 1,
2648 htlc_minimum_msat: None,
2649 htlc_maximum_msat: None,
2650 }]), RouteHint(vec![RouteHintHop {
2651 src_node_id: nodes[5],
2652 short_channel_id: 10,
2654 cltv_expiry_delta: (10 << 8) | 1,
2655 htlc_minimum_msat: None,
2656 htlc_maximum_msat: None,
2661 fn multi_hint_last_hops_test() {
2662 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
2663 let (_, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2664 let payee = Payee::new(nodes[6]).with_route_hints(multi_hint_last_hops(&nodes));
2665 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2666 // Test through channels 2, 3, 5, 8.
2667 // Test shows that multiple hop hints are considered.
2669 // Disabling channels 6 & 7 by flags=2
2670 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2671 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2672 short_channel_id: 6,
2674 flags: 2, // to disable
2675 cltv_expiry_delta: 0,
2676 htlc_minimum_msat: 0,
2677 htlc_maximum_msat: OptionalField::Absent,
2679 fee_proportional_millionths: 0,
2680 excess_data: Vec::new()
2682 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
2683 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
2684 short_channel_id: 7,
2686 flags: 2, // to disable
2687 cltv_expiry_delta: 0,
2688 htlc_minimum_msat: 0,
2689 htlc_maximum_msat: OptionalField::Absent,
2691 fee_proportional_millionths: 0,
2692 excess_data: Vec::new()
2695 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2696 assert_eq!(route.paths[0].len(), 4);
2698 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2699 assert_eq!(route.paths[0][0].short_channel_id, 2);
2700 assert_eq!(route.paths[0][0].fee_msat, 200);
2701 assert_eq!(route.paths[0][0].cltv_expiry_delta, 1025);
2702 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2703 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2705 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2706 assert_eq!(route.paths[0][1].short_channel_id, 4);
2707 assert_eq!(route.paths[0][1].fee_msat, 100);
2708 assert_eq!(route.paths[0][1].cltv_expiry_delta, 1281);
2709 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2710 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2712 assert_eq!(route.paths[0][2].pubkey, nodes[3]);
2713 assert_eq!(route.paths[0][2].short_channel_id, 5);
2714 assert_eq!(route.paths[0][2].fee_msat, 0);
2715 assert_eq!(route.paths[0][2].cltv_expiry_delta, 2049);
2716 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(4));
2717 assert_eq!(route.paths[0][2].channel_features.le_flags(), &Vec::<u8>::new());
2719 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2720 assert_eq!(route.paths[0][3].short_channel_id, 8);
2721 assert_eq!(route.paths[0][3].fee_msat, 100);
2722 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2723 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2724 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2727 fn last_hops_with_public_channel(nodes: &Vec<PublicKey>) -> Vec<RouteHint> {
2728 let zero_fees = RoutingFees {
2730 proportional_millionths: 0,
2732 vec![RouteHint(vec![RouteHintHop {
2733 src_node_id: nodes[4],
2734 short_channel_id: 11,
2736 cltv_expiry_delta: (11 << 8) | 1,
2737 htlc_minimum_msat: None,
2738 htlc_maximum_msat: None,
2740 src_node_id: nodes[3],
2741 short_channel_id: 8,
2743 cltv_expiry_delta: (8 << 8) | 1,
2744 htlc_minimum_msat: None,
2745 htlc_maximum_msat: None,
2746 }]), RouteHint(vec![RouteHintHop {
2747 src_node_id: nodes[4],
2748 short_channel_id: 9,
2751 proportional_millionths: 0,
2753 cltv_expiry_delta: (9 << 8) | 1,
2754 htlc_minimum_msat: None,
2755 htlc_maximum_msat: None,
2756 }]), RouteHint(vec![RouteHintHop {
2757 src_node_id: nodes[5],
2758 short_channel_id: 10,
2760 cltv_expiry_delta: (10 << 8) | 1,
2761 htlc_minimum_msat: None,
2762 htlc_maximum_msat: None,
2767 fn last_hops_with_public_channel_test() {
2768 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2769 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2770 let payee = Payee::new(nodes[6]).with_route_hints(last_hops_with_public_channel(&nodes));
2771 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2772 // This test shows that public routes can be present in the invoice
2773 // which would be handled in the same manner.
2775 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2776 assert_eq!(route.paths[0].len(), 5);
2778 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2779 assert_eq!(route.paths[0][0].short_channel_id, 2);
2780 assert_eq!(route.paths[0][0].fee_msat, 100);
2781 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2782 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2783 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2785 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2786 assert_eq!(route.paths[0][1].short_channel_id, 4);
2787 assert_eq!(route.paths[0][1].fee_msat, 0);
2788 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2789 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2790 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2792 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2793 assert_eq!(route.paths[0][2].short_channel_id, 6);
2794 assert_eq!(route.paths[0][2].fee_msat, 0);
2795 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2796 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2797 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2799 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2800 assert_eq!(route.paths[0][3].short_channel_id, 11);
2801 assert_eq!(route.paths[0][3].fee_msat, 0);
2802 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2803 // If we have a peer in the node map, we'll use their features here since we don't have
2804 // a way of figuring out their features from the invoice:
2805 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2806 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new());
2808 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2809 assert_eq!(route.paths[0][4].short_channel_id, 8);
2810 assert_eq!(route.paths[0][4].fee_msat, 100);
2811 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2812 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2813 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2817 fn our_chans_last_hop_connect_test() {
2818 let (secp_ctx, network_graph, _, _, logger) = build_graph();
2819 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
2820 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2822 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
2823 let our_chans = vec![get_channel_details(Some(42), nodes[3].clone(), InitFeatures::from_le_bytes(vec![0b11]), 250_000_000)];
2824 let mut last_hops = last_hops(&nodes);
2825 let payee = Payee::new(nodes[6]).with_route_hints(last_hops.clone());
2826 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 100, 42, Arc::clone(&logger), &scorer).unwrap();
2827 assert_eq!(route.paths[0].len(), 2);
2829 assert_eq!(route.paths[0][0].pubkey, nodes[3]);
2830 assert_eq!(route.paths[0][0].short_channel_id, 42);
2831 assert_eq!(route.paths[0][0].fee_msat, 0);
2832 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2833 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
2834 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::<u8>::new()); // No feature flags will meet the relevant-to-channel conversion
2836 assert_eq!(route.paths[0][1].pubkey, nodes[6]);
2837 assert_eq!(route.paths[0][1].short_channel_id, 8);
2838 assert_eq!(route.paths[0][1].fee_msat, 100);
2839 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2840 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2841 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2843 last_hops[0].0[0].fees.base_msat = 1000;
2845 // Revert to via 6 as the fee on 8 goes up
2846 let payee = Payee::new(nodes[6]).with_route_hints(last_hops);
2847 let route = get_route(&our_id, &payee, &network_graph, None, 100, 42, Arc::clone(&logger), &scorer).unwrap();
2848 assert_eq!(route.paths[0].len(), 4);
2850 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2851 assert_eq!(route.paths[0][0].short_channel_id, 2);
2852 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
2853 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2854 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2855 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2857 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2858 assert_eq!(route.paths[0][1].short_channel_id, 4);
2859 assert_eq!(route.paths[0][1].fee_msat, 100);
2860 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
2861 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2862 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2864 assert_eq!(route.paths[0][2].pubkey, nodes[5]);
2865 assert_eq!(route.paths[0][2].short_channel_id, 7);
2866 assert_eq!(route.paths[0][2].fee_msat, 0);
2867 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
2868 // If we have a peer in the node map, we'll use their features here since we don't have
2869 // a way of figuring out their features from the invoice:
2870 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
2871 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(7));
2873 assert_eq!(route.paths[0][3].pubkey, nodes[6]);
2874 assert_eq!(route.paths[0][3].short_channel_id, 10);
2875 assert_eq!(route.paths[0][3].fee_msat, 100);
2876 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
2877 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2878 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2880 // ...but still use 8 for larger payments as 6 has a variable feerate
2881 let route = get_route(&our_id, &payee, &network_graph, None, 2000, 42, Arc::clone(&logger), &scorer).unwrap();
2882 assert_eq!(route.paths[0].len(), 5);
2884 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
2885 assert_eq!(route.paths[0][0].short_channel_id, 2);
2886 assert_eq!(route.paths[0][0].fee_msat, 3000);
2887 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
2888 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(2));
2889 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(2));
2891 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
2892 assert_eq!(route.paths[0][1].short_channel_id, 4);
2893 assert_eq!(route.paths[0][1].fee_msat, 0);
2894 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
2895 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
2896 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(4));
2898 assert_eq!(route.paths[0][2].pubkey, nodes[4]);
2899 assert_eq!(route.paths[0][2].short_channel_id, 6);
2900 assert_eq!(route.paths[0][2].fee_msat, 0);
2901 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
2902 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5));
2903 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(6));
2905 assert_eq!(route.paths[0][3].pubkey, nodes[3]);
2906 assert_eq!(route.paths[0][3].short_channel_id, 11);
2907 assert_eq!(route.paths[0][3].fee_msat, 1000);
2908 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
2909 // If we have a peer in the node map, we'll use their features here since we don't have
2910 // a way of figuring out their features from the invoice:
2911 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags(4));
2912 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags(11));
2914 assert_eq!(route.paths[0][4].pubkey, nodes[6]);
2915 assert_eq!(route.paths[0][4].short_channel_id, 8);
2916 assert_eq!(route.paths[0][4].fee_msat, 2000);
2917 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
2918 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::<u8>::new()); // We dont pass flags in from invoices yet
2919 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::<u8>::new()); // We can't learn any flags from invoices, sadly
2922 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> {
2923 let source_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 41).repeat(32)).unwrap()[..]).unwrap());
2924 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2925 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2927 // If we specify a channel to a middle hop, that overrides our local channel view and that gets used
2928 let last_hops = RouteHint(vec![RouteHintHop {
2929 src_node_id: middle_node_id,
2930 short_channel_id: 8,
2933 proportional_millionths: last_hop_fee_prop,
2935 cltv_expiry_delta: (8 << 8) | 1,
2936 htlc_minimum_msat: None,
2937 htlc_maximum_msat: last_hop_htlc_max,
2939 let payee = Payee::new(target_node_id).with_route_hints(vec![last_hops]);
2940 let our_chans = vec![get_channel_details(Some(42), middle_node_id, InitFeatures::from_le_bytes(vec![0b11]), outbound_capacity_msat)];
2941 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2942 get_route(&source_node_id, &payee, &NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()), Some(&our_chans.iter().collect::<Vec<_>>()), route_val, 42, &test_utils::TestLogger::new(), &scorer)
2946 fn unannounced_path_test() {
2947 // We should be able to send a payment to a destination without any help of a routing graph
2948 // if we have a channel with a common counterparty that appears in the first and last hop
2950 let route = do_unannounced_path_test(None, 1, 2000000, 1000000).unwrap();
2952 let middle_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 42).repeat(32)).unwrap()[..]).unwrap());
2953 let target_node_id = PublicKey::from_secret_key(&Secp256k1::new(), &SecretKey::from_slice(&hex::decode(format!("{:02}", 43).repeat(32)).unwrap()[..]).unwrap());
2954 assert_eq!(route.paths[0].len(), 2);
2956 assert_eq!(route.paths[0][0].pubkey, middle_node_id);
2957 assert_eq!(route.paths[0][0].short_channel_id, 42);
2958 assert_eq!(route.paths[0][0].fee_msat, 1001);
2959 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
2960 assert_eq!(route.paths[0][0].node_features.le_flags(), &[0b11]);
2961 assert_eq!(route.paths[0][0].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2963 assert_eq!(route.paths[0][1].pubkey, target_node_id);
2964 assert_eq!(route.paths[0][1].short_channel_id, 8);
2965 assert_eq!(route.paths[0][1].fee_msat, 1000000);
2966 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
2967 assert_eq!(route.paths[0][1].node_features.le_flags(), &[0; 0]); // We dont pass flags in from invoices yet
2968 assert_eq!(route.paths[0][1].channel_features.le_flags(), &[0; 0]); // We can't learn any flags from invoices, sadly
2972 fn overflow_unannounced_path_test_liquidity_underflow() {
2973 // Previously, when we had a last-hop hint connected directly to a first-hop channel, where
2974 // the last-hop had a fee which overflowed a u64, we'd panic.
2975 // This was due to us adding the first-hop from us unconditionally, causing us to think
2976 // we'd built a path (as our node is in the "best candidate" set), when we had not.
2977 // In this test, we previously hit a subtraction underflow due to having less available
2978 // liquidity at the last hop than 0.
2979 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());
2983 fn overflow_unannounced_path_test_feerate_overflow() {
2984 // This tests for the same case as above, except instead of hitting a subtraction
2985 // underflow, we hit a case where the fee charged at a hop overflowed.
2986 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());
2990 fn available_amount_while_routing_test() {
2991 // Tests whether we choose the correct available channel amount while routing.
2993 let (secp_ctx, network_graph, mut net_graph_msg_handler, chain_monitor, logger) = build_graph();
2994 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
2995 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
2996 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
2998 // We will use a simple single-path route from
2999 // our node to node2 via node0: channels {1, 3}.
3001 // First disable all other paths.
3002 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3003 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3004 short_channel_id: 2,
3007 cltv_expiry_delta: 0,
3008 htlc_minimum_msat: 0,
3009 htlc_maximum_msat: OptionalField::Present(100_000),
3011 fee_proportional_millionths: 0,
3012 excess_data: Vec::new()
3014 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3015 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3016 short_channel_id: 12,
3019 cltv_expiry_delta: 0,
3020 htlc_minimum_msat: 0,
3021 htlc_maximum_msat: OptionalField::Present(100_000),
3023 fee_proportional_millionths: 0,
3024 excess_data: Vec::new()
3027 // Make the first channel (#1) very permissive,
3028 // and we will be testing all limits on the second channel.
3029 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3030 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3031 short_channel_id: 1,
3034 cltv_expiry_delta: 0,
3035 htlc_minimum_msat: 0,
3036 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3038 fee_proportional_millionths: 0,
3039 excess_data: Vec::new()
3042 // First, let's see if routing works if we have absolutely no idea about the available amount.
3043 // In this case, it should be set to 250_000 sats.
3044 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3045 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3046 short_channel_id: 3,
3049 cltv_expiry_delta: 0,
3050 htlc_minimum_msat: 0,
3051 htlc_maximum_msat: OptionalField::Absent,
3053 fee_proportional_millionths: 0,
3054 excess_data: Vec::new()
3058 // Attempt to route more than available results in a failure.
3059 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3060 &our_id, &payee, &network_graph, None, 250_000_001, 42, Arc::clone(&logger), &scorer) {
3061 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3062 } else { panic!(); }
3066 // Now, attempt to route an exact amount we have should be fine.
3067 let route = get_route(&our_id, &payee, &network_graph, None, 250_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3068 assert_eq!(route.paths.len(), 1);
3069 let path = route.paths.last().unwrap();
3070 assert_eq!(path.len(), 2);
3071 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3072 assert_eq!(path.last().unwrap().fee_msat, 250_000_000);
3075 // Check that setting outbound_capacity_msat in first_hops limits the channels.
3076 // Disable channel #1 and use another first hop.
3077 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3078 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3079 short_channel_id: 1,
3082 cltv_expiry_delta: 0,
3083 htlc_minimum_msat: 0,
3084 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3086 fee_proportional_millionths: 0,
3087 excess_data: Vec::new()
3090 // Now, limit the first_hop by the outbound_capacity_msat of 200_000 sats.
3091 let our_chans = vec![get_channel_details(Some(42), nodes[0].clone(), InitFeatures::from_le_bytes(vec![0b11]), 200_000_000)];
3094 // Attempt to route more than available results in a failure.
3095 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3096 &our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_001, 42, Arc::clone(&logger), &scorer) {
3097 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3098 } else { panic!(); }
3102 // Now, attempt to route an exact amount we have should be fine.
3103 let route = get_route(&our_id, &payee, &network_graph, Some(&our_chans.iter().collect::<Vec<_>>()), 200_000_000, 42, Arc::clone(&logger), &scorer).unwrap();
3104 assert_eq!(route.paths.len(), 1);
3105 let path = route.paths.last().unwrap();
3106 assert_eq!(path.len(), 2);
3107 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3108 assert_eq!(path.last().unwrap().fee_msat, 200_000_000);
3111 // Enable channel #1 back.
3112 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3113 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3114 short_channel_id: 1,
3117 cltv_expiry_delta: 0,
3118 htlc_minimum_msat: 0,
3119 htlc_maximum_msat: OptionalField::Present(1_000_000_000),
3121 fee_proportional_millionths: 0,
3122 excess_data: Vec::new()
3126 // Now let's see if routing works if we know only htlc_maximum_msat.
3127 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3128 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3129 short_channel_id: 3,
3132 cltv_expiry_delta: 0,
3133 htlc_minimum_msat: 0,
3134 htlc_maximum_msat: OptionalField::Present(15_000),
3136 fee_proportional_millionths: 0,
3137 excess_data: Vec::new()
3141 // Attempt to route more than available results in a failure.
3142 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3143 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3144 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3145 } else { panic!(); }
3149 // Now, attempt to route an exact amount we have should be fine.
3150 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3151 assert_eq!(route.paths.len(), 1);
3152 let path = route.paths.last().unwrap();
3153 assert_eq!(path.len(), 2);
3154 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3155 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3158 // Now let's see if routing works if we know only capacity from the UTXO.
3160 // We can't change UTXO capacity on the fly, so we'll disable
3161 // the existing channel and add another one with the capacity we need.
3162 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3163 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3164 short_channel_id: 3,
3167 cltv_expiry_delta: 0,
3168 htlc_minimum_msat: 0,
3169 htlc_maximum_msat: OptionalField::Absent,
3171 fee_proportional_millionths: 0,
3172 excess_data: Vec::new()
3175 let good_script = Builder::new().push_opcode(opcodes::all::OP_PUSHNUM_2)
3176 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[0]).serialize())
3177 .push_slice(&PublicKey::from_secret_key(&secp_ctx, &privkeys[2]).serialize())
3178 .push_opcode(opcodes::all::OP_PUSHNUM_2)
3179 .push_opcode(opcodes::all::OP_CHECKMULTISIG).into_script().to_v0_p2wsh();
3181 *chain_monitor.utxo_ret.lock().unwrap() = Ok(TxOut { value: 15, script_pubkey: good_script.clone() });
3182 net_graph_msg_handler.add_chain_access(Some(chain_monitor));
3184 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 333);
3185 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3186 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3187 short_channel_id: 333,
3190 cltv_expiry_delta: (3 << 8) | 1,
3191 htlc_minimum_msat: 0,
3192 htlc_maximum_msat: OptionalField::Absent,
3194 fee_proportional_millionths: 0,
3195 excess_data: Vec::new()
3197 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3198 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3199 short_channel_id: 333,
3202 cltv_expiry_delta: (3 << 8) | 2,
3203 htlc_minimum_msat: 0,
3204 htlc_maximum_msat: OptionalField::Absent,
3206 fee_proportional_millionths: 0,
3207 excess_data: Vec::new()
3211 // Attempt to route more than available results in a failure.
3212 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3213 &our_id, &payee, &network_graph, None, 15_001, 42, Arc::clone(&logger), &scorer) {
3214 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3215 } else { panic!(); }
3219 // Now, attempt to route an exact amount we have should be fine.
3220 let route = get_route(&our_id, &payee, &network_graph, None, 15_000, 42, Arc::clone(&logger), &scorer).unwrap();
3221 assert_eq!(route.paths.len(), 1);
3222 let path = route.paths.last().unwrap();
3223 assert_eq!(path.len(), 2);
3224 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3225 assert_eq!(path.last().unwrap().fee_msat, 15_000);
3228 // Now let's see if routing chooses htlc_maximum_msat over UTXO capacity.
3229 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3230 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3231 short_channel_id: 333,
3234 cltv_expiry_delta: 0,
3235 htlc_minimum_msat: 0,
3236 htlc_maximum_msat: OptionalField::Present(10_000),
3238 fee_proportional_millionths: 0,
3239 excess_data: Vec::new()
3243 // Attempt to route more than available results in a failure.
3244 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3245 &our_id, &payee, &network_graph, None, 10_001, 42, Arc::clone(&logger), &scorer) {
3246 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3247 } else { panic!(); }
3251 // Now, attempt to route an exact amount we have should be fine.
3252 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
3253 assert_eq!(route.paths.len(), 1);
3254 let path = route.paths.last().unwrap();
3255 assert_eq!(path.len(), 2);
3256 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3257 assert_eq!(path.last().unwrap().fee_msat, 10_000);
3262 fn available_liquidity_last_hop_test() {
3263 // Check that available liquidity properly limits the path even when only
3264 // one of the latter hops is limited.
3265 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3266 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3267 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3268 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3270 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3271 // {12, 13, 11} have the capacities of 100, {6} has a capacity of 50.
3272 // Total capacity: 50 sats.
3274 // Disable other potential paths.
3275 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3276 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3277 short_channel_id: 2,
3280 cltv_expiry_delta: 0,
3281 htlc_minimum_msat: 0,
3282 htlc_maximum_msat: OptionalField::Present(100_000),
3284 fee_proportional_millionths: 0,
3285 excess_data: Vec::new()
3287 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3288 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3289 short_channel_id: 7,
3292 cltv_expiry_delta: 0,
3293 htlc_minimum_msat: 0,
3294 htlc_maximum_msat: OptionalField::Present(100_000),
3296 fee_proportional_millionths: 0,
3297 excess_data: Vec::new()
3302 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3303 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3304 short_channel_id: 12,
3307 cltv_expiry_delta: 0,
3308 htlc_minimum_msat: 0,
3309 htlc_maximum_msat: OptionalField::Present(100_000),
3311 fee_proportional_millionths: 0,
3312 excess_data: Vec::new()
3314 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3315 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3316 short_channel_id: 13,
3319 cltv_expiry_delta: 0,
3320 htlc_minimum_msat: 0,
3321 htlc_maximum_msat: OptionalField::Present(100_000),
3323 fee_proportional_millionths: 0,
3324 excess_data: Vec::new()
3327 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3328 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3329 short_channel_id: 6,
3332 cltv_expiry_delta: 0,
3333 htlc_minimum_msat: 0,
3334 htlc_maximum_msat: OptionalField::Present(50_000),
3336 fee_proportional_millionths: 0,
3337 excess_data: Vec::new()
3339 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3340 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3341 short_channel_id: 11,
3344 cltv_expiry_delta: 0,
3345 htlc_minimum_msat: 0,
3346 htlc_maximum_msat: OptionalField::Present(100_000),
3348 fee_proportional_millionths: 0,
3349 excess_data: Vec::new()
3352 // Attempt to route more than available results in a failure.
3353 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3354 &our_id, &payee, &network_graph, None, 60_000, 42, Arc::clone(&logger), &scorer) {
3355 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3356 } else { panic!(); }
3360 // Now, attempt to route 49 sats (just a bit below the capacity).
3361 let route = get_route(&our_id, &payee, &network_graph, None, 49_000, 42, Arc::clone(&logger), &scorer).unwrap();
3362 assert_eq!(route.paths.len(), 1);
3363 let mut total_amount_paid_msat = 0;
3364 for path in &route.paths {
3365 assert_eq!(path.len(), 4);
3366 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3367 total_amount_paid_msat += path.last().unwrap().fee_msat;
3369 assert_eq!(total_amount_paid_msat, 49_000);
3373 // Attempt to route an exact amount is also fine
3374 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3375 assert_eq!(route.paths.len(), 1);
3376 let mut total_amount_paid_msat = 0;
3377 for path in &route.paths {
3378 assert_eq!(path.len(), 4);
3379 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3380 total_amount_paid_msat += path.last().unwrap().fee_msat;
3382 assert_eq!(total_amount_paid_msat, 50_000);
3387 fn ignore_fee_first_hop_test() {
3388 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3389 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3390 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3391 let payee = Payee::new(nodes[2]);
3393 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3394 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3395 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3396 short_channel_id: 1,
3399 cltv_expiry_delta: 0,
3400 htlc_minimum_msat: 0,
3401 htlc_maximum_msat: OptionalField::Present(100_000),
3402 fee_base_msat: 1_000_000,
3403 fee_proportional_millionths: 0,
3404 excess_data: Vec::new()
3406 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3407 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3408 short_channel_id: 3,
3411 cltv_expiry_delta: 0,
3412 htlc_minimum_msat: 0,
3413 htlc_maximum_msat: OptionalField::Present(50_000),
3415 fee_proportional_millionths: 0,
3416 excess_data: Vec::new()
3420 let route = get_route(&our_id, &payee, &network_graph, None, 50_000, 42, Arc::clone(&logger), &scorer).unwrap();
3421 assert_eq!(route.paths.len(), 1);
3422 let mut total_amount_paid_msat = 0;
3423 for path in &route.paths {
3424 assert_eq!(path.len(), 2);
3425 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3426 total_amount_paid_msat += path.last().unwrap().fee_msat;
3428 assert_eq!(total_amount_paid_msat, 50_000);
3433 fn simple_mpp_route_test() {
3434 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3435 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3436 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3437 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
3439 // We need a route consisting of 3 paths:
3440 // From our node to node2 via node0, node7, node1 (three paths one hop each).
3441 // To achieve this, the amount being transferred should be around
3442 // the total capacity of these 3 paths.
3444 // First, we set limits on these (previously unlimited) channels.
3445 // Their aggregate capacity will be 50 + 60 + 180 = 290 sats.
3447 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50).
3448 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3449 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3450 short_channel_id: 1,
3453 cltv_expiry_delta: 0,
3454 htlc_minimum_msat: 0,
3455 htlc_maximum_msat: OptionalField::Present(100_000),
3457 fee_proportional_millionths: 0,
3458 excess_data: Vec::new()
3460 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3461 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3462 short_channel_id: 3,
3465 cltv_expiry_delta: 0,
3466 htlc_minimum_msat: 0,
3467 htlc_maximum_msat: OptionalField::Present(50_000),
3469 fee_proportional_millionths: 0,
3470 excess_data: Vec::new()
3473 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats
3474 // (total limit 60).
3475 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3476 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3477 short_channel_id: 12,
3480 cltv_expiry_delta: 0,
3481 htlc_minimum_msat: 0,
3482 htlc_maximum_msat: OptionalField::Present(60_000),
3484 fee_proportional_millionths: 0,
3485 excess_data: Vec::new()
3487 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3488 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3489 short_channel_id: 13,
3492 cltv_expiry_delta: 0,
3493 htlc_minimum_msat: 0,
3494 htlc_maximum_msat: OptionalField::Present(60_000),
3496 fee_proportional_millionths: 0,
3497 excess_data: Vec::new()
3500 // Path via node1 is channels {2, 4}. Limit them to 200 and 180 sats
3501 // (total capacity 180 sats).
3502 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3503 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3504 short_channel_id: 2,
3507 cltv_expiry_delta: 0,
3508 htlc_minimum_msat: 0,
3509 htlc_maximum_msat: OptionalField::Present(200_000),
3511 fee_proportional_millionths: 0,
3512 excess_data: Vec::new()
3514 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
3515 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3516 short_channel_id: 4,
3519 cltv_expiry_delta: 0,
3520 htlc_minimum_msat: 0,
3521 htlc_maximum_msat: OptionalField::Present(180_000),
3523 fee_proportional_millionths: 0,
3524 excess_data: Vec::new()
3528 // Attempt to route more than available results in a failure.
3529 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3530 &our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer) {
3531 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3532 } else { panic!(); }
3536 // Now, attempt to route 250 sats (just a bit below the capacity).
3537 // Our algorithm should provide us with these 3 paths.
3538 let route = get_route(&our_id, &payee, &network_graph, None, 250_000, 42, Arc::clone(&logger), &scorer).unwrap();
3539 assert_eq!(route.paths.len(), 3);
3540 let mut total_amount_paid_msat = 0;
3541 for path in &route.paths {
3542 assert_eq!(path.len(), 2);
3543 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3544 total_amount_paid_msat += path.last().unwrap().fee_msat;
3546 assert_eq!(total_amount_paid_msat, 250_000);
3550 // Attempt to route an exact amount is also fine
3551 let route = get_route(&our_id, &payee, &network_graph, None, 290_000, 42, Arc::clone(&logger), &scorer).unwrap();
3552 assert_eq!(route.paths.len(), 3);
3553 let mut total_amount_paid_msat = 0;
3554 for path in &route.paths {
3555 assert_eq!(path.len(), 2);
3556 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
3557 total_amount_paid_msat += path.last().unwrap().fee_msat;
3559 assert_eq!(total_amount_paid_msat, 290_000);
3564 fn long_mpp_route_test() {
3565 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3566 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3567 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3568 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3570 // We need a route consisting of 3 paths:
3571 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3572 // Note that these paths overlap (channels 5, 12, 13).
3573 // We will route 300 sats.
3574 // Each path will have 100 sats capacity, those channels which
3575 // are used twice will have 200 sats capacity.
3577 // Disable other potential paths.
3578 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3579 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3580 short_channel_id: 2,
3583 cltv_expiry_delta: 0,
3584 htlc_minimum_msat: 0,
3585 htlc_maximum_msat: OptionalField::Present(100_000),
3587 fee_proportional_millionths: 0,
3588 excess_data: Vec::new()
3590 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3591 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3592 short_channel_id: 7,
3595 cltv_expiry_delta: 0,
3596 htlc_minimum_msat: 0,
3597 htlc_maximum_msat: OptionalField::Present(100_000),
3599 fee_proportional_millionths: 0,
3600 excess_data: Vec::new()
3603 // Path via {node0, node2} is channels {1, 3, 5}.
3604 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3605 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3606 short_channel_id: 1,
3609 cltv_expiry_delta: 0,
3610 htlc_minimum_msat: 0,
3611 htlc_maximum_msat: OptionalField::Present(100_000),
3613 fee_proportional_millionths: 0,
3614 excess_data: Vec::new()
3616 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3617 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3618 short_channel_id: 3,
3621 cltv_expiry_delta: 0,
3622 htlc_minimum_msat: 0,
3623 htlc_maximum_msat: OptionalField::Present(100_000),
3625 fee_proportional_millionths: 0,
3626 excess_data: Vec::new()
3629 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3630 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3631 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3632 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3633 short_channel_id: 5,
3636 cltv_expiry_delta: 0,
3637 htlc_minimum_msat: 0,
3638 htlc_maximum_msat: OptionalField::Present(200_000),
3640 fee_proportional_millionths: 0,
3641 excess_data: Vec::new()
3644 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3645 // Add 100 sats to the capacities of {12, 13}, because these channels
3646 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3647 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3648 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3649 short_channel_id: 12,
3652 cltv_expiry_delta: 0,
3653 htlc_minimum_msat: 0,
3654 htlc_maximum_msat: OptionalField::Present(200_000),
3656 fee_proportional_millionths: 0,
3657 excess_data: Vec::new()
3659 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3660 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3661 short_channel_id: 13,
3664 cltv_expiry_delta: 0,
3665 htlc_minimum_msat: 0,
3666 htlc_maximum_msat: OptionalField::Present(200_000),
3668 fee_proportional_millionths: 0,
3669 excess_data: Vec::new()
3672 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3673 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3674 short_channel_id: 6,
3677 cltv_expiry_delta: 0,
3678 htlc_minimum_msat: 0,
3679 htlc_maximum_msat: OptionalField::Present(100_000),
3681 fee_proportional_millionths: 0,
3682 excess_data: Vec::new()
3684 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3685 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3686 short_channel_id: 11,
3689 cltv_expiry_delta: 0,
3690 htlc_minimum_msat: 0,
3691 htlc_maximum_msat: OptionalField::Present(100_000),
3693 fee_proportional_millionths: 0,
3694 excess_data: Vec::new()
3697 // Path via {node7, node2} is channels {12, 13, 5}.
3698 // We already limited them to 200 sats (they are used twice for 100 sats).
3699 // Nothing to do here.
3702 // Attempt to route more than available results in a failure.
3703 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
3704 &our_id, &payee, &network_graph, None, 350_000, 42, Arc::clone(&logger), &scorer) {
3705 assert_eq!(err, "Failed to find a sufficient route to the given destination");
3706 } else { panic!(); }
3710 // Now, attempt to route 300 sats (exact amount we can route).
3711 // Our algorithm should provide us with these 3 paths, 100 sats each.
3712 let route = get_route(&our_id, &payee, &network_graph, None, 300_000, 42, Arc::clone(&logger), &scorer).unwrap();
3713 assert_eq!(route.paths.len(), 3);
3715 let mut total_amount_paid_msat = 0;
3716 for path in &route.paths {
3717 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3718 total_amount_paid_msat += path.last().unwrap().fee_msat;
3720 assert_eq!(total_amount_paid_msat, 300_000);
3726 fn mpp_cheaper_route_test() {
3727 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3728 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3729 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3730 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3732 // This test checks that if we have two cheaper paths and one more expensive path,
3733 // so that liquidity-wise any 2 of 3 combination is sufficient,
3734 // two cheaper paths will be taken.
3735 // These paths have equal available liquidity.
3737 // We need a combination of 3 paths:
3738 // From our node to node3 via {node0, node2}, {node7, node2, node4} and {node7, node2}.
3739 // Note that these paths overlap (channels 5, 12, 13).
3740 // Each path will have 100 sats capacity, those channels which
3741 // are used twice will have 200 sats capacity.
3743 // Disable other potential paths.
3744 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3745 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3746 short_channel_id: 2,
3749 cltv_expiry_delta: 0,
3750 htlc_minimum_msat: 0,
3751 htlc_maximum_msat: OptionalField::Present(100_000),
3753 fee_proportional_millionths: 0,
3754 excess_data: Vec::new()
3756 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3757 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3758 short_channel_id: 7,
3761 cltv_expiry_delta: 0,
3762 htlc_minimum_msat: 0,
3763 htlc_maximum_msat: OptionalField::Present(100_000),
3765 fee_proportional_millionths: 0,
3766 excess_data: Vec::new()
3769 // Path via {node0, node2} is channels {1, 3, 5}.
3770 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3771 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3772 short_channel_id: 1,
3775 cltv_expiry_delta: 0,
3776 htlc_minimum_msat: 0,
3777 htlc_maximum_msat: OptionalField::Present(100_000),
3779 fee_proportional_millionths: 0,
3780 excess_data: Vec::new()
3782 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3783 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3784 short_channel_id: 3,
3787 cltv_expiry_delta: 0,
3788 htlc_minimum_msat: 0,
3789 htlc_maximum_msat: OptionalField::Present(100_000),
3791 fee_proportional_millionths: 0,
3792 excess_data: Vec::new()
3795 // Capacity of 200 sats because this channel will be used by 3rd path as well.
3796 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3797 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3798 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3799 short_channel_id: 5,
3802 cltv_expiry_delta: 0,
3803 htlc_minimum_msat: 0,
3804 htlc_maximum_msat: OptionalField::Present(200_000),
3806 fee_proportional_millionths: 0,
3807 excess_data: Vec::new()
3810 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3811 // Add 100 sats to the capacities of {12, 13}, because these channels
3812 // are also used for 3rd path. 100 sats for the rest. Total capacity: 100 sats.
3813 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3814 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3815 short_channel_id: 12,
3818 cltv_expiry_delta: 0,
3819 htlc_minimum_msat: 0,
3820 htlc_maximum_msat: OptionalField::Present(200_000),
3822 fee_proportional_millionths: 0,
3823 excess_data: Vec::new()
3825 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3826 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3827 short_channel_id: 13,
3830 cltv_expiry_delta: 0,
3831 htlc_minimum_msat: 0,
3832 htlc_maximum_msat: OptionalField::Present(200_000),
3834 fee_proportional_millionths: 0,
3835 excess_data: Vec::new()
3838 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3839 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3840 short_channel_id: 6,
3843 cltv_expiry_delta: 0,
3844 htlc_minimum_msat: 0,
3845 htlc_maximum_msat: OptionalField::Present(100_000),
3846 fee_base_msat: 1_000,
3847 fee_proportional_millionths: 0,
3848 excess_data: Vec::new()
3850 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
3851 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3852 short_channel_id: 11,
3855 cltv_expiry_delta: 0,
3856 htlc_minimum_msat: 0,
3857 htlc_maximum_msat: OptionalField::Present(100_000),
3859 fee_proportional_millionths: 0,
3860 excess_data: Vec::new()
3863 // Path via {node7, node2} is channels {12, 13, 5}.
3864 // We already limited them to 200 sats (they are used twice for 100 sats).
3865 // Nothing to do here.
3868 // Now, attempt to route 180 sats.
3869 // Our algorithm should provide us with these 2 paths.
3870 let route = get_route(&our_id, &payee, &network_graph, None, 180_000, 42, Arc::clone(&logger), &scorer).unwrap();
3871 assert_eq!(route.paths.len(), 2);
3873 let mut total_value_transferred_msat = 0;
3874 let mut total_paid_msat = 0;
3875 for path in &route.paths {
3876 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
3877 total_value_transferred_msat += path.last().unwrap().fee_msat;
3879 total_paid_msat += hop.fee_msat;
3882 // If we paid fee, this would be higher.
3883 assert_eq!(total_value_transferred_msat, 180_000);
3884 let total_fees_paid = total_paid_msat - total_value_transferred_msat;
3885 assert_eq!(total_fees_paid, 0);
3890 fn fees_on_mpp_route_test() {
3891 // This test makes sure that MPP algorithm properly takes into account
3892 // fees charged on the channels, by making the fees impactful:
3893 // if the fee is not properly accounted for, the behavior is different.
3894 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
3895 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
3896 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
3897 let payee = Payee::new(nodes[3]).with_features(InvoiceFeatures::known());
3899 // We need a route consisting of 2 paths:
3900 // From our node to node3 via {node0, node2} and {node7, node2, node4}.
3901 // We will route 200 sats, Each path will have 100 sats capacity.
3903 // This test is not particularly stable: e.g.,
3904 // there's a way to route via {node0, node2, node4}.
3905 // It works while pathfinding is deterministic, but can be broken otherwise.
3906 // It's fine to ignore this concern for now.
3908 // Disable other potential paths.
3909 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3910 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3911 short_channel_id: 2,
3914 cltv_expiry_delta: 0,
3915 htlc_minimum_msat: 0,
3916 htlc_maximum_msat: OptionalField::Present(100_000),
3918 fee_proportional_millionths: 0,
3919 excess_data: Vec::new()
3922 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3923 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3924 short_channel_id: 7,
3927 cltv_expiry_delta: 0,
3928 htlc_minimum_msat: 0,
3929 htlc_maximum_msat: OptionalField::Present(100_000),
3931 fee_proportional_millionths: 0,
3932 excess_data: Vec::new()
3935 // Path via {node0, node2} is channels {1, 3, 5}.
3936 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3937 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3938 short_channel_id: 1,
3941 cltv_expiry_delta: 0,
3942 htlc_minimum_msat: 0,
3943 htlc_maximum_msat: OptionalField::Present(100_000),
3945 fee_proportional_millionths: 0,
3946 excess_data: Vec::new()
3948 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
3949 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3950 short_channel_id: 3,
3953 cltv_expiry_delta: 0,
3954 htlc_minimum_msat: 0,
3955 htlc_maximum_msat: OptionalField::Present(100_000),
3957 fee_proportional_millionths: 0,
3958 excess_data: Vec::new()
3961 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
3962 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
3963 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3964 short_channel_id: 5,
3967 cltv_expiry_delta: 0,
3968 htlc_minimum_msat: 0,
3969 htlc_maximum_msat: OptionalField::Present(100_000),
3971 fee_proportional_millionths: 0,
3972 excess_data: Vec::new()
3975 // Path via {node7, node2, node4} is channels {12, 13, 6, 11}.
3976 // All channels should be 100 sats capacity. But for the fee experiment,
3977 // we'll add absolute fee of 150 sats paid for the use channel 6 (paid to node2 on channel 13).
3978 // Since channel 12 allows to deliver only 250 sats to channel 13, channel 13 can transfer only
3979 // 100 sats (and pay 150 sats in fees for the use of channel 6),
3980 // so no matter how large are other channels,
3981 // the whole path will be limited by 100 sats with just these 2 conditions:
3982 // - channel 12 capacity is 250 sats
3983 // - fee for channel 6 is 150 sats
3984 // Let's test this by enforcing these 2 conditions and removing other limits.
3985 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
3986 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3987 short_channel_id: 12,
3990 cltv_expiry_delta: 0,
3991 htlc_minimum_msat: 0,
3992 htlc_maximum_msat: OptionalField::Present(250_000),
3994 fee_proportional_millionths: 0,
3995 excess_data: Vec::new()
3997 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
3998 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
3999 short_channel_id: 13,
4002 cltv_expiry_delta: 0,
4003 htlc_minimum_msat: 0,
4004 htlc_maximum_msat: OptionalField::Absent,
4006 fee_proportional_millionths: 0,
4007 excess_data: Vec::new()
4010 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4011 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4012 short_channel_id: 6,
4015 cltv_expiry_delta: 0,
4016 htlc_minimum_msat: 0,
4017 htlc_maximum_msat: OptionalField::Absent,
4018 fee_base_msat: 150_000,
4019 fee_proportional_millionths: 0,
4020 excess_data: Vec::new()
4022 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4023 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4024 short_channel_id: 11,
4027 cltv_expiry_delta: 0,
4028 htlc_minimum_msat: 0,
4029 htlc_maximum_msat: OptionalField::Absent,
4031 fee_proportional_millionths: 0,
4032 excess_data: Vec::new()
4036 // Attempt to route more than available results in a failure.
4037 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4038 &our_id, &payee, &network_graph, None, 210_000, 42, Arc::clone(&logger), &scorer) {
4039 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4040 } else { panic!(); }
4044 // Now, attempt to route 200 sats (exact amount we can route).
4045 let route = get_route(&our_id, &payee, &network_graph, None, 200_000, 42, Arc::clone(&logger), &scorer).unwrap();
4046 assert_eq!(route.paths.len(), 2);
4048 let mut total_amount_paid_msat = 0;
4049 for path in &route.paths {
4050 assert_eq!(path.last().unwrap().pubkey, nodes[3]);
4051 total_amount_paid_msat += path.last().unwrap().fee_msat;
4053 assert_eq!(total_amount_paid_msat, 200_000);
4054 assert_eq!(route.get_total_fees(), 150_000);
4060 fn drop_lowest_channel_mpp_route_test() {
4061 // This test checks that low-capacity channel is dropped when after
4062 // path finding we realize that we found more capacity than we need.
4063 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4064 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4065 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4066 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4068 // We need a route consisting of 3 paths:
4069 // From our node to node2 via node0, node7, node1 (three paths one hop each).
4071 // The first and the second paths should be sufficient, but the third should be
4072 // cheaper, so that we select it but drop later.
4074 // First, we set limits on these (previously unlimited) channels.
4075 // Their aggregate capacity will be 50 + 60 + 20 = 130 sats.
4077 // Path via node0 is channels {1, 3}. Limit them to 100 and 50 sats (total limit 50);
4078 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4079 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4080 short_channel_id: 1,
4083 cltv_expiry_delta: 0,
4084 htlc_minimum_msat: 0,
4085 htlc_maximum_msat: OptionalField::Present(100_000),
4087 fee_proportional_millionths: 0,
4088 excess_data: Vec::new()
4090 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[0], UnsignedChannelUpdate {
4091 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4092 short_channel_id: 3,
4095 cltv_expiry_delta: 0,
4096 htlc_minimum_msat: 0,
4097 htlc_maximum_msat: OptionalField::Present(50_000),
4099 fee_proportional_millionths: 0,
4100 excess_data: Vec::new()
4103 // Path via node7 is channels {12, 13}. Limit them to 60 and 60 sats (total limit 60);
4104 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4105 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4106 short_channel_id: 12,
4109 cltv_expiry_delta: 0,
4110 htlc_minimum_msat: 0,
4111 htlc_maximum_msat: OptionalField::Present(60_000),
4113 fee_proportional_millionths: 0,
4114 excess_data: Vec::new()
4116 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[7], UnsignedChannelUpdate {
4117 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4118 short_channel_id: 13,
4121 cltv_expiry_delta: 0,
4122 htlc_minimum_msat: 0,
4123 htlc_maximum_msat: OptionalField::Present(60_000),
4125 fee_proportional_millionths: 0,
4126 excess_data: Vec::new()
4129 // Path via node1 is channels {2, 4}. Limit them to 20 and 20 sats (total capacity 20 sats).
4130 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4131 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4132 short_channel_id: 2,
4135 cltv_expiry_delta: 0,
4136 htlc_minimum_msat: 0,
4137 htlc_maximum_msat: OptionalField::Present(20_000),
4139 fee_proportional_millionths: 0,
4140 excess_data: Vec::new()
4142 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4143 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4144 short_channel_id: 4,
4147 cltv_expiry_delta: 0,
4148 htlc_minimum_msat: 0,
4149 htlc_maximum_msat: OptionalField::Present(20_000),
4151 fee_proportional_millionths: 0,
4152 excess_data: Vec::new()
4156 // Attempt to route more than available results in a failure.
4157 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(
4158 &our_id, &payee, &network_graph, None, 150_000, 42, Arc::clone(&logger), &scorer) {
4159 assert_eq!(err, "Failed to find a sufficient route to the given destination");
4160 } else { panic!(); }
4164 // Now, attempt to route 125 sats (just a bit below the capacity of 3 channels).
4165 // Our algorithm should provide us with these 3 paths.
4166 let route = get_route(&our_id, &payee, &network_graph, None, 125_000, 42, Arc::clone(&logger), &scorer).unwrap();
4167 assert_eq!(route.paths.len(), 3);
4168 let mut total_amount_paid_msat = 0;
4169 for path in &route.paths {
4170 assert_eq!(path.len(), 2);
4171 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4172 total_amount_paid_msat += path.last().unwrap().fee_msat;
4174 assert_eq!(total_amount_paid_msat, 125_000);
4178 // Attempt to route without the last small cheap channel
4179 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4180 assert_eq!(route.paths.len(), 2);
4181 let mut total_amount_paid_msat = 0;
4182 for path in &route.paths {
4183 assert_eq!(path.len(), 2);
4184 assert_eq!(path.last().unwrap().pubkey, nodes[2]);
4185 total_amount_paid_msat += path.last().unwrap().fee_msat;
4187 assert_eq!(total_amount_paid_msat, 90_000);
4192 fn min_criteria_consistency() {
4193 // Test that we don't use an inconsistent metric between updating and walking nodes during
4194 // our Dijkstra's pass. In the initial version of MPP, the "best source" for a given node
4195 // was updated with a different criterion from the heap sorting, resulting in loops in
4196 // calculated paths. We test for that specific case here.
4198 // We construct a network that looks like this:
4200 // node2 -1(3)2- node3
4204 // node1 -1(5)2- node4 -1(1)2- node6
4210 // We create a loop on the side of our real path - our destination is node 6, with a
4211 // previous hop of node 4. From 4, the cheapest previous path is channel 2 from node 2,
4212 // followed by node 3 over channel 3. Thereafter, the cheapest next-hop is back to node 4
4213 // (this time over channel 4). Channel 4 has 0 htlc_minimum_msat whereas channel 1 (the
4214 // other channel with a previous-hop of node 4) has a high (but irrelevant to the overall
4215 // payment) htlc_minimum_msat. In the original algorithm, this resulted in node4's
4216 // "previous hop" being set to node 3, creating a loop in the path.
4217 let secp_ctx = Secp256k1::new();
4218 let logger = Arc::new(test_utils::TestLogger::new());
4219 let network_graph = Arc::new(NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash()));
4220 let net_graph_msg_handler = NetGraphMsgHandler::new(Arc::clone(&network_graph), None, Arc::clone(&logger));
4221 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4222 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4223 let payee = Payee::new(nodes[6]);
4225 add_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, &privkeys[1], ChannelFeatures::from_le_bytes(id_to_feature_flags(6)), 6);
4226 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4227 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4228 short_channel_id: 6,
4231 cltv_expiry_delta: (6 << 8) | 0,
4232 htlc_minimum_msat: 0,
4233 htlc_maximum_msat: OptionalField::Absent,
4235 fee_proportional_millionths: 0,
4236 excess_data: Vec::new()
4238 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[1], NodeFeatures::from_le_bytes(id_to_feature_flags(1)), 0);
4240 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(5)), 5);
4241 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4242 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4243 short_channel_id: 5,
4246 cltv_expiry_delta: (5 << 8) | 0,
4247 htlc_minimum_msat: 0,
4248 htlc_maximum_msat: OptionalField::Absent,
4250 fee_proportional_millionths: 0,
4251 excess_data: Vec::new()
4253 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[4], NodeFeatures::from_le_bytes(id_to_feature_flags(4)), 0);
4255 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[3], ChannelFeatures::from_le_bytes(id_to_feature_flags(4)), 4);
4256 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4257 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4258 short_channel_id: 4,
4261 cltv_expiry_delta: (4 << 8) | 0,
4262 htlc_minimum_msat: 0,
4263 htlc_maximum_msat: OptionalField::Absent,
4265 fee_proportional_millionths: 0,
4266 excess_data: Vec::new()
4268 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[3], NodeFeatures::from_le_bytes(id_to_feature_flags(3)), 0);
4270 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], &privkeys[2], ChannelFeatures::from_le_bytes(id_to_feature_flags(3)), 3);
4271 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[3], UnsignedChannelUpdate {
4272 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4273 short_channel_id: 3,
4276 cltv_expiry_delta: (3 << 8) | 0,
4277 htlc_minimum_msat: 0,
4278 htlc_maximum_msat: OptionalField::Absent,
4280 fee_proportional_millionths: 0,
4281 excess_data: Vec::new()
4283 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[2], NodeFeatures::from_le_bytes(id_to_feature_flags(2)), 0);
4285 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], &privkeys[4], ChannelFeatures::from_le_bytes(id_to_feature_flags(2)), 2);
4286 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[2], UnsignedChannelUpdate {
4287 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4288 short_channel_id: 2,
4291 cltv_expiry_delta: (2 << 8) | 0,
4292 htlc_minimum_msat: 0,
4293 htlc_maximum_msat: OptionalField::Absent,
4295 fee_proportional_millionths: 0,
4296 excess_data: Vec::new()
4299 add_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], &privkeys[6], ChannelFeatures::from_le_bytes(id_to_feature_flags(1)), 1);
4300 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[4], UnsignedChannelUpdate {
4301 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4302 short_channel_id: 1,
4305 cltv_expiry_delta: (1 << 8) | 0,
4306 htlc_minimum_msat: 100,
4307 htlc_maximum_msat: OptionalField::Absent,
4309 fee_proportional_millionths: 0,
4310 excess_data: Vec::new()
4312 add_or_update_node(&net_graph_msg_handler, &secp_ctx, &privkeys[6], NodeFeatures::from_le_bytes(id_to_feature_flags(6)), 0);
4315 // Now ensure the route flows simply over nodes 1 and 4 to 6.
4316 let route = get_route(&our_id, &payee, &network_graph, None, 10_000, 42, Arc::clone(&logger), &scorer).unwrap();
4317 assert_eq!(route.paths.len(), 1);
4318 assert_eq!(route.paths[0].len(), 3);
4320 assert_eq!(route.paths[0][0].pubkey, nodes[1]);
4321 assert_eq!(route.paths[0][0].short_channel_id, 6);
4322 assert_eq!(route.paths[0][0].fee_msat, 100);
4323 assert_eq!(route.paths[0][0].cltv_expiry_delta, (5 << 8) | 0);
4324 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(1));
4325 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(6));
4327 assert_eq!(route.paths[0][1].pubkey, nodes[4]);
4328 assert_eq!(route.paths[0][1].short_channel_id, 5);
4329 assert_eq!(route.paths[0][1].fee_msat, 0);
4330 assert_eq!(route.paths[0][1].cltv_expiry_delta, (1 << 8) | 0);
4331 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(4));
4332 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(5));
4334 assert_eq!(route.paths[0][2].pubkey, nodes[6]);
4335 assert_eq!(route.paths[0][2].short_channel_id, 1);
4336 assert_eq!(route.paths[0][2].fee_msat, 10_000);
4337 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
4338 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(6));
4339 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags(1));
4345 fn exact_fee_liquidity_limit() {
4346 // Test that if, while walking the graph, we find a hop that has exactly enough liquidity
4347 // for us, including later hop fees, we take it. In the first version of our MPP algorithm
4348 // we calculated fees on a higher value, resulting in us ignoring such paths.
4349 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4350 let (our_privkey, our_id, _, nodes) = get_nodes(&secp_ctx);
4351 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4352 let payee = Payee::new(nodes[2]);
4354 // We modify the graph to set the htlc_maximum of channel 2 to below the value we wish to
4356 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4357 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4358 short_channel_id: 2,
4361 cltv_expiry_delta: 0,
4362 htlc_minimum_msat: 0,
4363 htlc_maximum_msat: OptionalField::Present(85_000),
4365 fee_proportional_millionths: 0,
4366 excess_data: Vec::new()
4369 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4370 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4371 short_channel_id: 12,
4374 cltv_expiry_delta: (4 << 8) | 1,
4375 htlc_minimum_msat: 0,
4376 htlc_maximum_msat: OptionalField::Present(270_000),
4378 fee_proportional_millionths: 1000000,
4379 excess_data: Vec::new()
4383 // Now, attempt to route 90 sats, which is exactly 90 sats at the last hop, plus the
4384 // 200% fee charged channel 13 in the 1-to-2 direction.
4385 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4386 assert_eq!(route.paths.len(), 1);
4387 assert_eq!(route.paths[0].len(), 2);
4389 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4390 assert_eq!(route.paths[0][0].short_channel_id, 12);
4391 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4392 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4393 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4394 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4396 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4397 assert_eq!(route.paths[0][1].short_channel_id, 13);
4398 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4399 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4400 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags(3));
4401 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4406 fn htlc_max_reduction_below_min() {
4407 // Test that if, while walking the graph, we reduce the value being sent to meet an
4408 // htlc_maximum_msat, we don't end up undershooting a later htlc_minimum_msat. In the
4409 // initial version of MPP we'd accept such routes but reject them while recalculating fees,
4410 // resulting in us thinking there is no possible path, even if other paths exist.
4411 let (secp_ctx, network_graph, net_graph_msg_handler, _, logger) = build_graph();
4412 let (our_privkey, our_id, privkeys, nodes) = get_nodes(&secp_ctx);
4413 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4414 let payee = Payee::new(nodes[2]).with_features(InvoiceFeatures::known());
4416 // We modify the graph to set the htlc_minimum of channel 2 and 4 as needed - channel 2
4417 // gets an htlc_maximum_msat of 80_000 and channel 4 an htlc_minimum_msat of 90_000. We
4418 // then try to send 90_000.
4419 update_channel(&net_graph_msg_handler, &secp_ctx, &our_privkey, UnsignedChannelUpdate {
4420 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4421 short_channel_id: 2,
4424 cltv_expiry_delta: 0,
4425 htlc_minimum_msat: 0,
4426 htlc_maximum_msat: OptionalField::Present(80_000),
4428 fee_proportional_millionths: 0,
4429 excess_data: Vec::new()
4431 update_channel(&net_graph_msg_handler, &secp_ctx, &privkeys[1], UnsignedChannelUpdate {
4432 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4433 short_channel_id: 4,
4436 cltv_expiry_delta: (4 << 8) | 1,
4437 htlc_minimum_msat: 90_000,
4438 htlc_maximum_msat: OptionalField::Absent,
4440 fee_proportional_millionths: 0,
4441 excess_data: Vec::new()
4445 // Now, attempt to route 90 sats, hitting the htlc_minimum on channel 4, but
4446 // overshooting the htlc_maximum on channel 2. Thus, we should pick the (absurdly
4447 // expensive) channels 12-13 path.
4448 let route = get_route(&our_id, &payee, &network_graph, None, 90_000, 42, Arc::clone(&logger), &scorer).unwrap();
4449 assert_eq!(route.paths.len(), 1);
4450 assert_eq!(route.paths[0].len(), 2);
4452 assert_eq!(route.paths[0][0].pubkey, nodes[7]);
4453 assert_eq!(route.paths[0][0].short_channel_id, 12);
4454 assert_eq!(route.paths[0][0].fee_msat, 90_000*2);
4455 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
4456 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags(8));
4457 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags(12));
4459 assert_eq!(route.paths[0][1].pubkey, nodes[2]);
4460 assert_eq!(route.paths[0][1].short_channel_id, 13);
4461 assert_eq!(route.paths[0][1].fee_msat, 90_000);
4462 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
4463 assert_eq!(route.paths[0][1].node_features.le_flags(), InvoiceFeatures::known().le_flags());
4464 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags(13));
4469 fn multiple_direct_first_hops() {
4470 // Previously we'd only ever considered one first hop path per counterparty.
4471 // However, as we don't restrict users to one channel per peer, we really need to support
4472 // looking at all first hop paths.
4473 // Here we test that we do not ignore all-but-the-last first hop paths per counterparty (as
4474 // we used to do by overwriting the `first_hop_targets` hashmap entry) and that we can MPP
4475 // route over multiple channels with the same first hop.
4476 let secp_ctx = Secp256k1::new();
4477 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4478 let logger = Arc::new(test_utils::TestLogger::new());
4479 let network_graph = NetworkGraph::new(genesis_block(Network::Testnet).header.block_hash());
4480 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4481 let payee = Payee::new(nodes[0]).with_features(InvoiceFeatures::known());
4484 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4485 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 200_000),
4486 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 10_000),
4487 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4488 assert_eq!(route.paths.len(), 1);
4489 assert_eq!(route.paths[0].len(), 1);
4491 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4492 assert_eq!(route.paths[0][0].short_channel_id, 3);
4493 assert_eq!(route.paths[0][0].fee_msat, 100_000);
4496 let route = get_route(&our_id, &payee, &network_graph, Some(&[
4497 &get_channel_details(Some(3), nodes[0], InitFeatures::known(), 50_000),
4498 &get_channel_details(Some(2), nodes[0], InitFeatures::known(), 50_000),
4499 ]), 100_000, 42, Arc::clone(&logger), &scorer).unwrap();
4500 assert_eq!(route.paths.len(), 2);
4501 assert_eq!(route.paths[0].len(), 1);
4502 assert_eq!(route.paths[1].len(), 1);
4504 assert_eq!(route.paths[0][0].pubkey, nodes[0]);
4505 assert_eq!(route.paths[0][0].short_channel_id, 3);
4506 assert_eq!(route.paths[0][0].fee_msat, 50_000);
4508 assert_eq!(route.paths[1][0].pubkey, nodes[0]);
4509 assert_eq!(route.paths[1][0].short_channel_id, 2);
4510 assert_eq!(route.paths[1][0].fee_msat, 50_000);
4515 fn prefers_shorter_route_with_higher_fees() {
4516 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4517 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4518 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4520 // Without penalizing each hop 100 msats, a longer path with lower fees is chosen.
4521 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4522 let route = get_route(
4523 &our_id, &payee, &network_graph, None, 100, 42,
4524 Arc::clone(&logger), &scorer
4526 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4528 assert_eq!(route.get_total_fees(), 100);
4529 assert_eq!(route.get_total_amount(), 100);
4530 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4532 // Applying a 100 msat penalty to each hop results in taking channels 7 and 10 to nodes[6]
4533 // from nodes[2] rather than channel 6, 11, and 8, even though the longer path is cheaper.
4534 let scorer = test_utils::TestScorer::with_fixed_penalty(100);
4535 let route = get_route(
4536 &our_id, &payee, &network_graph, None, 100, 42,
4537 Arc::clone(&logger), &scorer
4539 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4541 assert_eq!(route.get_total_fees(), 300);
4542 assert_eq!(route.get_total_amount(), 100);
4543 assert_eq!(path, vec![2, 4, 7, 10]);
4546 struct BadChannelScorer {
4547 short_channel_id: u64,
4550 impl routing::Score for BadChannelScorer {
4551 fn channel_penalty_msat(&self, short_channel_id: u64, _source: &NodeId, _target: &NodeId) -> u64 {
4552 if short_channel_id == self.short_channel_id { u64::max_value() } else { 0 }
4555 fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, _short_channel_id: u64) {}
4558 struct BadNodeScorer {
4562 impl routing::Score for BadNodeScorer {
4563 fn channel_penalty_msat(&self, _short_channel_id: u64, _source: &NodeId, target: &NodeId) -> u64 {
4564 if *target == self.node_id { u64::max_value() } else { 0 }
4567 fn payment_path_failed(&mut self, _path: &Vec<RouteHop>, _short_channel_id: u64) {}
4571 fn avoids_routing_through_bad_channels_and_nodes() {
4572 let (secp_ctx, network_graph, _, _, logger) = build_graph();
4573 let (_, our_id, _, nodes) = get_nodes(&secp_ctx);
4574 let payee = Payee::new(nodes[6]).with_route_hints(last_hops(&nodes));
4576 // A path to nodes[6] exists when no penalties are applied to any channel.
4577 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4578 let route = get_route(
4579 &our_id, &payee, &network_graph, None, 100, 42,
4580 Arc::clone(&logger), &scorer
4582 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4584 assert_eq!(route.get_total_fees(), 100);
4585 assert_eq!(route.get_total_amount(), 100);
4586 assert_eq!(path, vec![2, 4, 6, 11, 8]);
4588 // A different path to nodes[6] exists if channel 6 cannot be routed over.
4589 let scorer = BadChannelScorer { short_channel_id: 6 };
4590 let route = get_route(
4591 &our_id, &payee, &network_graph, None, 100, 42,
4592 Arc::clone(&logger), &scorer
4594 let path = route.paths[0].iter().map(|hop| hop.short_channel_id).collect::<Vec<_>>();
4596 assert_eq!(route.get_total_fees(), 300);
4597 assert_eq!(route.get_total_amount(), 100);
4598 assert_eq!(path, vec![2, 4, 7, 10]);
4600 // A path to nodes[6] does not exist if nodes[2] cannot be routed through.
4601 let scorer = BadNodeScorer { node_id: NodeId::from_pubkey(&nodes[2]) };
4603 &our_id, &payee, &network_graph, None, 100, 42,
4604 Arc::clone(&logger), &scorer
4606 Err(LightningError { err, .. } ) => {
4607 assert_eq!(err, "Failed to find a path to the given destination");
4609 Ok(_) => panic!("Expected error"),
4614 fn total_fees_single_path() {
4618 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4619 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4620 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4623 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4624 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4625 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4628 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
4629 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4630 short_channel_id: 0, fee_msat: 225, cltv_expiry_delta: 0
4636 assert_eq!(route.get_total_fees(), 250);
4637 assert_eq!(route.get_total_amount(), 225);
4641 fn total_fees_multi_path() {
4645 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4646 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4647 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4650 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4651 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4652 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4656 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
4657 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4658 short_channel_id: 0, fee_msat: 100, cltv_expiry_delta: 0
4661 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
4662 channel_features: ChannelFeatures::empty(), node_features: NodeFeatures::empty(),
4663 short_channel_id: 0, fee_msat: 150, cltv_expiry_delta: 0
4669 assert_eq!(route.get_total_fees(), 200);
4670 assert_eq!(route.get_total_amount(), 300);
4674 fn total_empty_route_no_panic() {
4675 // In an earlier version of `Route::get_total_fees` and `Route::get_total_amount`, they
4676 // would both panic if the route was completely empty. We test to ensure they return 0
4677 // here, even though its somewhat nonsensical as a route.
4678 let route = Route { paths: Vec::new(), payee: None };
4680 assert_eq!(route.get_total_fees(), 0);
4681 assert_eq!(route.get_total_amount(), 0);
4684 #[cfg(not(feature = "no-std"))]
4685 pub(super) fn random_init_seed() -> u64 {
4686 // Because the default HashMap in std pulls OS randomness, we can use it as a (bad) RNG.
4687 use core::hash::{BuildHasher, Hasher};
4688 let seed = std::collections::hash_map::RandomState::new().build_hasher().finish();
4689 println!("Using seed of {}", seed);
4692 #[cfg(not(feature = "no-std"))]
4693 use util::ser::Readable;
4696 #[cfg(not(feature = "no-std"))]
4697 fn generate_routes() {
4698 let mut d = match super::test_utils::get_route_file() {
4705 let graph = NetworkGraph::read(&mut d).unwrap();
4706 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4708 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4709 let mut seed = random_init_seed() as usize;
4710 let nodes = graph.read_only().nodes().clone();
4711 'load_endpoints: for _ in 0..10 {
4713 seed = seed.overflowing_mul(0xdeadbeef).0;
4714 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4715 seed = seed.overflowing_mul(0xdeadbeef).0;
4716 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4717 let payee = Payee::new(dst);
4718 let amt = seed as u64 % 200_000_000;
4719 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4720 continue 'load_endpoints;
4727 #[cfg(not(feature = "no-std"))]
4728 fn generate_routes_mpp() {
4729 let mut d = match super::test_utils::get_route_file() {
4736 let graph = NetworkGraph::read(&mut d).unwrap();
4737 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
4739 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4740 let mut seed = random_init_seed() as usize;
4741 let nodes = graph.read_only().nodes().clone();
4742 'load_endpoints: for _ in 0..10 {
4744 seed = seed.overflowing_mul(0xdeadbeef).0;
4745 let src = &PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4746 seed = seed.overflowing_mul(0xdeadbeef).0;
4747 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4748 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4749 let amt = seed as u64 % 200_000_000;
4750 if get_route(src, &payee, &graph, None, amt, 42, &test_utils::TestLogger::new(), &scorer).is_ok() {
4751 continue 'load_endpoints;
4758 #[cfg(all(test, not(feature = "no-std")))]
4759 pub(crate) mod test_utils {
4761 /// Tries to open a network graph file, or panics with a URL to fetch it.
4762 pub(crate) fn get_route_file() -> Result<std::fs::File, &'static str> {
4763 let res = File::open("net_graph-2021-05-31.bin") // By default we're run in RL/lightning
4764 .or_else(|_| File::open("lightning/net_graph-2021-05-31.bin")) // We may be run manually in RL/
4765 .or_else(|_| { // Fall back to guessing based on the binary location
4766 // path is likely something like .../rust-lightning/target/debug/deps/lightning-...
4767 let mut path = std::env::current_exe().unwrap();
4768 path.pop(); // lightning-...
4770 path.pop(); // debug
4771 path.pop(); // target
4772 path.push("lightning");
4773 path.push("net_graph-2021-05-31.bin");
4774 eprintln!("{}", path.to_str().unwrap());
4777 .map_err(|_| "Please fetch https://bitcoin.ninja/ldk-net_graph-v0.0.15-2021-05-31.bin and place it at lightning/net_graph-2021-05-31.bin");
4778 #[cfg(require_route_graph_test)]
4779 return Ok(res.unwrap());
4780 #[cfg(not(require_route_graph_test))]
4785 #[cfg(all(test, feature = "unstable", not(feature = "no-std")))]
4788 use routing::scorer::Scorer;
4789 use util::logger::{Logger, Record};
4793 struct DummyLogger {}
4794 impl Logger for DummyLogger {
4795 fn log(&self, _record: &Record) {}
4799 fn generate_routes(bench: &mut Bencher) {
4800 let mut d = test_utils::get_route_file().unwrap();
4801 let graph = NetworkGraph::read(&mut d).unwrap();
4802 let nodes = graph.read_only().nodes().clone();
4803 let scorer = Scorer::with_fixed_penalty(0);
4805 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4806 let mut path_endpoints = Vec::new();
4807 let mut seed: usize = 0xdeadbeef;
4808 'load_endpoints: for _ in 0..100 {
4811 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4813 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4814 let payee = Payee::new(dst);
4815 let amt = seed as u64 % 1_000_000;
4816 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4817 path_endpoints.push((src, dst, amt));
4818 continue 'load_endpoints;
4823 // ...then benchmark finding paths between the nodes we learned.
4826 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4827 let payee = Payee::new(dst);
4828 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());
4834 fn generate_mpp_routes(bench: &mut Bencher) {
4835 let mut d = test_utils::get_route_file().unwrap();
4836 let graph = NetworkGraph::read(&mut d).unwrap();
4837 let nodes = graph.read_only().nodes().clone();
4838 let scorer = Scorer::with_fixed_penalty(0);
4840 // First, get 100 (source, destination) pairs for which route-getting actually succeeds...
4841 let mut path_endpoints = Vec::new();
4842 let mut seed: usize = 0xdeadbeef;
4843 'load_endpoints: for _ in 0..100 {
4846 let src = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4848 let dst = PublicKey::from_slice(nodes.keys().skip(seed % nodes.len()).next().unwrap().as_slice()).unwrap();
4849 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4850 let amt = seed as u64 % 1_000_000;
4851 if get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok() {
4852 path_endpoints.push((src, dst, amt));
4853 continue 'load_endpoints;
4858 // ...then benchmark finding paths between the nodes we learned.
4861 let (src, dst, amt) = path_endpoints[idx % path_endpoints.len()];
4862 let payee = Payee::new(dst).with_features(InvoiceFeatures::known());
4863 assert!(get_route(&src, &payee, &graph, None, amt, 42, &DummyLogger{}, &scorer).is_ok());